Skip to content

Commit f7dd036

Browse files
feat(sasl): enrich authentication context with metadata (#725)
* feat: enrich sasl context with metadata * feedback from first review * second round of feedback * remove unnecessary blank line * it has been a long day * Update dialer.go * Update sasl/sasl.go * Update sasl/sasl.go * Update transport.go Co-authored-by: Achille <[email protected]>
1 parent ea83b29 commit f7dd036

File tree

3 files changed

+28
-2
lines changed

3 files changed

+28
-2
lines changed

dialer.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -281,7 +281,10 @@ func (d *Dialer) connect(ctx context.Context, network, address string, connCfg C
281281
conn := NewConnWith(c, connCfg)
282282

283283
if d.SASLMechanism != nil {
284-
if err := d.authenticateSASL(ctx, conn); err != nil {
284+
metadata := &sasl.Metadata{
285+
Host: address,
286+
}
287+
if err := d.authenticateSASL(sasl.WithMetadata(ctx, metadata), conn); err != nil {
285288
_ = conn.Close()
286289
return nil, err
287290
}

sasl/sasl.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ package sasl
22

33
import "context"
44

5+
type ctxKey struct{}
6+
57
// Mechanism implements the SASL state machine for a particular mode of
68
// authentication. It is used by the kafka.Dialer to perform the SASL
79
// handshake.
@@ -42,3 +44,21 @@ type StateMachine interface {
4244
// value will be true.
4345
Next(ctx context.Context, challenge []byte) (done bool, response []byte, err error)
4446
}
47+
48+
// Metadata contains additional data for performing SASL authentication.
49+
type Metadata struct {
50+
// Host is the address of the broker the authentication will be
51+
// performed on.
52+
Host string
53+
}
54+
55+
// WithMetadata returns a copy of the context with associated Metadata.
56+
func WithMetadata(ctx context.Context, m *Metadata) context.Context {
57+
return context.WithValue(ctx, ctxKey{}, m)
58+
}
59+
60+
// MetadataFromContext retrieves the Metadata from the context.
61+
func MetadataFromContext(ctx context.Context) *Metadata {
62+
m, _ := ctx.Value(ctxKey{}).(*Metadata)
63+
return m
64+
}

transport.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1197,7 +1197,10 @@ func (g *connGroup) connect(ctx context.Context, addr net.Addr) (*conn, error) {
11971197
pc.SetDeadline(time.Time{})
11981198

11991199
if g.pool.sasl != nil {
1200-
if err := authenticateSASL(ctx, pc, g.pool.sasl); err != nil {
1200+
metadata := &sasl.Metadata{
1201+
Host: netAddr.String(),
1202+
}
1203+
if err := authenticateSASL(sasl.WithMetadata(ctx, metadata), pc, g.pool.sasl); err != nil {
12011204
return nil, err
12021205
}
12031206
}

0 commit comments

Comments
 (0)