|
| 1 | +package security |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/brianvoe/gofakeit/v6" |
| 8 | + "github.com/stretchr/testify/require" |
| 9 | +) |
| 10 | + |
| 11 | +func TestNewSensitiveString(t *testing.T) { |
| 12 | + secretValue := gofakeit.LetterN(10) |
| 13 | + s := NewSensitiveString(secretValue) |
| 14 | + require.Equal(t, secretValue, s.Reveal()) |
| 15 | +} |
| 16 | + |
| 17 | +func TestStringRedaction(t *testing.T) { |
| 18 | + secretValue := gofakeit.LetterN(10) |
| 19 | + s := NewSensitiveString(secretValue) |
| 20 | + require.Equal(t, RedactionPlaceholder, s.String()) |
| 21 | +} |
| 22 | + |
| 23 | +func TestEmptyStringRedaction(t *testing.T) { |
| 24 | + s := NewSensitiveString("") |
| 25 | + require.Equal(t, "", s.String()) |
| 26 | +} |
| 27 | + |
| 28 | +func TestMarshalJSON(t *testing.T) { |
| 29 | + secretValue := gofakeit.LetterN(10) |
| 30 | + s := NewSensitiveString(secretValue) |
| 31 | + data, err := json.Marshal(s) |
| 32 | + require.NoError(t, err) |
| 33 | + require.JSONEq(t, `"`+RedactionPlaceholder+`"`, string(data)) |
| 34 | +} |
| 35 | + |
| 36 | +func TestMarshalJSONPointer(t *testing.T) { |
| 37 | + secretValue := gofakeit.LetterN(10) |
| 38 | + s := NewSensitiveString(secretValue) |
| 39 | + data, err := json.Marshal(&s) |
| 40 | + require.NoError(t, err) |
| 41 | + require.JSONEq(t, `"`+RedactionPlaceholder+`"`, string(data)) |
| 42 | +} |
| 43 | + |
| 44 | +func TestUnmarshalJSON(t *testing.T) { |
| 45 | + secretValue := gofakeit.LetterN(10) |
| 46 | + data := `"` + secretValue + `"` |
| 47 | + var s SensitiveString |
| 48 | + err := json.Unmarshal([]byte(data), &s) |
| 49 | + require.NoError(t, err) |
| 50 | + require.Equal(t, secretValue, s.Reveal()) |
| 51 | +} |
| 52 | + |
| 53 | +func TestUnamarshalJSONError(t *testing.T) { |
| 54 | + // Can't unmarshal a non-string value |
| 55 | + var s SensitiveString |
| 56 | + data := `{"key": "value"}` |
| 57 | + err := json.Unmarshal([]byte(data), &s) |
| 58 | + require.Error(t, err) |
| 59 | +} |
| 60 | + |
| 61 | +func TestCopySensitiveString(t *testing.T) { |
| 62 | + secretValue := gofakeit.LetterN(10) |
| 63 | + s := NewSensitiveString(secretValue) |
| 64 | + sCopy := s |
| 65 | + require.Equal(t, secretValue, sCopy.Reveal()) |
| 66 | +} |
0 commit comments