|
| 1 | +package secrets |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "io" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/stretchr/testify/assert" |
| 9 | +) |
| 10 | + |
| 11 | +func TestRedaction(t *testing.T) { |
| 12 | + tests := []struct { |
| 13 | + name string |
| 14 | + msg string |
| 15 | + want string |
| 16 | + env []string |
| 17 | + }{ |
| 18 | + { |
| 19 | + name: "replaces env var value with its name", |
| 20 | + env: []string{"DB_PASS=foobar123"}, |
| 21 | + msg: "wrong password foobar123", |
| 22 | + want: "wrong password DB_PASS", |
| 23 | + }, |
| 24 | + { |
| 25 | + name: "handles env var value with equals sign", |
| 26 | + env: []string{"SECRET=user=foo"}, |
| 27 | + msg: "wrong password for user=foo", |
| 28 | + want: "wrong password for SECRET", |
| 29 | + }, |
| 30 | + { |
| 31 | + name: "leaves original msg unchanged", |
| 32 | + env: []string{}, |
| 33 | + msg: "wrong password foobar123", |
| 34 | + want: "wrong password foobar123", |
| 35 | + }, |
| 36 | + { |
| 37 | + name: "handles env var with empty value", |
| 38 | + env: []string{"DB_PASS="}, |
| 39 | + msg: "wrong password foobar123", |
| 40 | + want: "wrong password foobar123", |
| 41 | + }, |
| 42 | + } |
| 43 | + for _, tt := range tests { |
| 44 | + redactor := NewSecretAwareRedactor() |
| 45 | + redactor.AddSecretEnv(tt.env) |
| 46 | + t.Run(tt.name, func(t *testing.T) { |
| 47 | + got := redactor.RedactStr(tt.msg) |
| 48 | + assert.Equal(t, tt.want, got) |
| 49 | + }) |
| 50 | + t.Run(tt.name+" in log", func(t *testing.T) { |
| 51 | + out := &bytes.Buffer{} |
| 52 | + writer := NewSecretAwareWriter(out, redactor) |
| 53 | + _, _ = writer.Write([]byte(tt.msg)) |
| 54 | + got, _ := io.ReadAll(out) |
| 55 | + assert.Equal(t, tt.want, string(got)) |
| 56 | + }) |
| 57 | + } |
| 58 | +} |
0 commit comments