-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathlogging_test.go
More file actions
82 lines (77 loc) · 2.08 KB
/
logging_test.go
File metadata and controls
82 lines (77 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"bytes"
"context"
"fmt"
"log/slog"
"testing"
)
func TestRedactingHandler(t *testing.T) {
tests := []struct {
name string
msg string
attrs []slog.Attr
notWant string // substring that must NOT appear in output
want string // substring that MUST appear in output
}{
{
name: "password in message",
msg: `connection to "host=foo password=secret123 dbname=bar" failed`,
notWant: "secret123",
want: "[REDACTED]",
},
{
name: "password in attr value",
msg: "connection failed",
attrs: []slog.Attr{slog.String("dsn", "host=foo password=hunter2 dbname=bar")},
notWant: "hunter2",
want: "[REDACTED]",
},
{
name: "password with colon separator",
msg: "err: password: s3cret in log",
notWant: "s3cret",
want: "[REDACTED]",
},
{
name: "no password present",
msg: "normal log message",
attrs: []slog.Attr{slog.String("key", "value")},
notWant: "[REDACTED]",
want: "normal log message",
},
{
name: "password in error attr",
msg: "query failed",
attrs: []slog.Attr{slog.Any("error", fmt.Errorf("password=oops"))},
notWant: "oops",
want: "[REDACTED]",
},
{
name: "quoted password value",
msg: `Unable to connect at "host=db password="topSecret" dbname=prod"`,
notWant: "topSecret",
want: "[REDACTED]",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var buf bytes.Buffer
inner := slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug})
handler := &redactingHandler{inner: inner}
logger := slog.New(handler)
logger.LogAttrs(context.Background(), slog.LevelInfo, tt.msg, tt.attrs...)
output := buf.String()
if tt.notWant != "" {
if bytes.Contains([]byte(output), []byte(tt.notWant)) {
t.Errorf("output contains %q which should have been redacted:\n%s", tt.notWant, output)
}
}
if tt.want != "" {
if !bytes.Contains([]byte(output), []byte(tt.want)) {
t.Errorf("output missing expected %q:\n%s", tt.want, output)
}
}
})
}
}