Files

96 lines
3.0 KiB
Go

package events
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"filippo.io/age"
"github.com/samcharles93/archie-core/internal/platform/seal"
"github.com/samcharles93/archie-core/modules/connectors"
"github.com/samcharles93/archie-core/modules/events/internal/store"
)
type fakeSources struct{ src store.Source }
func (f fakeSources) Source(context.Context, string, string) (store.Source, error) {
return f.src, nil
}
func sign(secret, body string) string {
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(body))
return hex.EncodeToString(mac.Sum(nil))
}
// TestHMACSourceVerifiesBeforeParsing guards the invariant that a webhook's
// signature is checked on the raw body before the connector sees it: a wrong
// or missing signature answers 401 and Parse never runs.
func TestHMACSourceVerifiesBeforeParsing(t *testing.T) {
const secret = "not-a-real-secret" //nolint:gosec // fixture signing secret the verifier must accept
const body = `{"id":"1"}`
id, err := age.GenerateX25519Identity()
if err != nil {
t.Fatal(err)
}
sealer, err := seal.New(id.String(), nil)
if err != nil {
t.Fatal(err)
}
sealed, err := sealer.Seal(secretLabel("org", "hook"), []byte(secret))
if err != nil {
t.Fatal(err)
}
src := store.Source{
OrgID: "org", Name: "hook", Connector: "c", Verification: store.HMAC,
HMACHeader: "X-Signature", HMACPrefix: "sha256=", HMACSecretSealed: sealed,
}
tests := []struct {
name string
header string
wantCode int
wantParse bool
}{
{"correct signature", "sha256=" + sign(secret, body), 0, true},
{"correct signature in upper case", "sha256=" + strings.ToUpper(sign(secret, body)), 0, true},
{"missing signature", "", http.StatusUnauthorized, false},
{"wrong secret", "sha256=" + sign("other-secret", body), http.StatusUnauthorized, false},
{"signature of another body", "sha256=" + sign(secret, `{"id":"2"}`), http.StatusUnauthorized, false},
{"missing prefix", sign(secret, body), http.StatusUnauthorized, false},
{"not hex", "sha256=zz", http.StatusUnauthorized, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
parsed := false
m := &Module{
orgID: "org", reader: fakeSources{src}, sealer: sealer,
log: slog.New(slog.DiscardHandler),
parse: func(context.Context, string, []byte, map[string]string) ([]connectors.Event, error) {
parsed = true
return nil, nil
},
}
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/hooks/hook", strings.NewReader(body))
req.SetPathValue("source", "hook")
if tt.header != "" {
req.Header.Set("X-Signature", tt.header)
}
_, _, _, code, err := m.accept(req)
if code != tt.wantCode || (err != nil) != (tt.wantCode != 0) {
t.Fatalf("status %d, error %v; want status %d", code, err, tt.wantCode)
}
if parsed != tt.wantParse {
t.Fatalf("connector parsed = %v, want %v", parsed, tt.wantParse)
}
})
}
}