signature_test.go51 lines, 1.5 KB
| 1 | package signature_test |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "net/http" |
| 6 | "strconv" |
| 7 | "testing" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/fiston-user/payments/internal/webhook/signature" |
| 11 | ) |
| 12 | |
| 13 | func TestVerify(t *testing.T) { |
| 14 | t.Parallel() |
| 15 | secret := signature.NewSecret() |
| 16 | now := time.Now() |
| 17 | body := []byte(`{"type":"transfer.completed.v1","data":{"amount":1500}}`) |
| 18 | signed := func(secret string, at time.Time) http.Header { |
| 19 | h := http.Header{} |
| 20 | if err := signature.Sign(h, secret, "evt_1", at, body); err != nil { |
| 21 | t.Fatalf("Sign: %v", err) |
| 22 | } |
| 23 | return h |
| 24 | } |
| 25 | // An attacker re-sends an old message, with a fresh timestamp. |
| 26 | retimed := signed(secret, now.Add(-time.Hour)) |
| 27 | retimed.Set(signature.HeaderTimestamp, strconv.FormatInt(now.Unix(), 10)) |
| 28 | |
| 29 | tests := []struct { |
| 30 | name string |
| 31 | header http.Header |
| 32 | body []byte |
| 33 | want error |
| 34 | }{ |
| 35 | {"valid", signed(secret, now), body, nil}, |
| 36 | {"tampered body", signed(secret, now), []byte(`{"type":"transfer.completed.v1","data":{"amount":9999}}`), |
| 37 | signature.ErrNoMatch}, |
| 38 | {"wrong secret", signed(signature.NewSecret(), now), body, signature.ErrNoMatch}, |
| 39 | {"ten minutes old", signed(secret, now.Add(-10*time.Minute)), body, signature.ErrTimestamp}, |
| 40 | {"old, with a new timestamp", retimed, body, signature.ErrNoMatch}, |
| 41 | {"no headers", http.Header{}, body, signature.ErrMissingHeaders}, |
| 42 | } |
| 43 | for _, tt := range tests { |
| 44 | t.Run(tt.name, func(t *testing.T) { |
| 45 | t.Parallel() |
| 46 | if err := signature.Verify(tt.header, secret, tt.body, now); !errors.Is(err, tt.want) { |
| 47 | t.Errorf("Verify = %v, want %v", err, tt.want) |
| 48 | } |
| 49 | }) |
| 50 | } |
| 51 | } |