package events import ( "context" "log/slog" "maps" "net/http" "net/http/httptest" "strings" "testing" "filippo.io/age" "github.com/samcharles93/archie-core/internal/platform/httpapi" "github.com/samcharles93/archie-core/internal/platform/httpjson" "github.com/samcharles93/archie-core/internal/platform/seal" "github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/events/internal/store" "github.com/samcharles93/archie-core/modules/governance" ) // rowRecorder keeps every event row intake stores. type rowRecorder struct{ rows []store.Event } func (r *rowRecorder) Insert(_ context.Context, e store.Event) (bool, error) { r.rows = append(r.rows, e) return true, nil } // TestIntakeRecordsHowEachDeliveryWasVerified guards three things about a // webhook delivery: each stored event records the scheme that verified it, a // source that checks nothing takes no deliveries until a person approved that, // and the kept headers never include a credential or the signature itself. func TestIntakeRecordsHowEachDeliveryWasVerified(t *testing.T) { const secret = "not-a-real-secret" //nolint:gosec // fixture signing secret the verifier must accept const token = "not-a-real-token" //nolint:gosec // fixture bearer token 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) } base := store.Source{OrgID: "org", Name: "hook", Connector: "c", Capture: true} hmacSource := base hmacSource.Verification, hmacSource.HMACHeader, hmacSource.HMACPrefix, hmacSource.HMACSecretSealed = store.HMAC, "X-Signature", "sha256=", sealed tokenSource := base tokenSource.Verification, tokenSource.TokenSHA256 = store.Token, httpjson.TokenHash(token) pending, approved, unkept := base, base, hmacSource pending.Verification, approved.Verification, approved.UnsignedApproved = store.None, store.None, true unkept.Capture = false tests := []struct { name string src store.Source header http.Header wantCode int wantVerdict string wantKept bool }{ {"a signed delivery", hmacSource, http.Header{"X-Signature": {"sha256=" + sign(secret, body)}}, http.StatusAccepted, store.Signed, true}, {"a token delivery", tokenSource, http.Header{"Authorization": {"Bearer " + token}}, http.StatusAccepted, store.TokenVerified, true}, {"an approved unsigned source", approved, http.Header{}, http.StatusAccepted, store.Unsigned, true}, {"an unsigned source nobody approved", pending, http.Header{}, http.StatusUnauthorized, "", false}, {"a source that keeps no payloads", unkept, http.Header{"X-Signature": {"sha256=" + sign(secret, body)}}, http.StatusAccepted, store.Signed, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { rows := &rowRecorder{} parsed := false m := &Module{ orgID: "org", reader: fakeSources{tt.src}, inserter: rows, sealer: sealer, delivery: permitAll{}, deliveries: noEcho{}, log: slog.New(slog.DiscardHandler), parse: func(context.Context, string, []byte, map[string]string) ([]connectors.Event, error) { parsed = true return []connectors.Event{{Type: "t", SourceEventID: "e1"}}, nil }, } req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/hooks/hook", strings.NewReader(body)) req.SetPathValue("source", "hook") maps.Copy(req.Header, tt.header) req.Header.Set("Cookie", "session=not-a-real-cookie") rec := httptest.NewRecorder() m.intake(rec, req) if rec.Code != tt.wantCode { t.Fatalf("status %d, want %d", rec.Code, tt.wantCode) } if tt.wantCode != http.StatusAccepted { if parsed || len(rows.rows) != 0 { t.Fatalf("a refused delivery was parsed (%v) or stored (%d rows)", parsed, len(rows.rows)) } return } if len(rows.rows) != 1 { t.Fatalf("%d rows stored, want 1", len(rows.rows)) } row := rows.rows[0] if row.Verification != tt.wantVerdict { t.Fatalf("recorded verification %q, want %q", row.Verification, tt.wantVerdict) } if kept := row.Headers != nil && row.Body != nil; kept != tt.wantKept { t.Fatalf("headers and body kept = %v, want %v", kept, tt.wantKept) } for _, secretHeader := range []string{"Authorization", "Cookie", "X-Signature", "not-a-real"} { if strings.Contains(string(row.Headers), secretHeader) { t.Fatalf("kept headers %s contain %q", row.Headers, secretHeader) } } }) } } type adminCaller struct{} func (adminCaller) Authenticate(ctx context.Context, _ *http.Request) (context.Context, bool, error) { return ctx, true, nil } // TestApprovalsNeedTheirOwnGrant guards the separation between asking and // approving: a role that may edit a source or trigger can't also approve what // it asked for, because approving unsigned deliveries and arming a trigger are // declared under the approve action and turning signing off is not. func TestApprovalsNeedTheirOwnGrant(t *testing.T) { api := httpapi.New(http.NewServeMux(), "test", adminCaller{}, nil) (&Module{}).Register(api) got := map[string][2]string{} for _, r := range httpapi.Routes(api) { if action, kind, ok := r.Access.Declared(); ok { got[r.ID] = [2]string{action, kind} } } for id, want := range map[string][2]string{ "approve-source-unsigned": {string(governance.ActionApprove), string(governance.KindSource)}, "approve-trigger": {string(governance.ActionApprove), string(governance.KindTrigger)}, "set-source-signing": {string(governance.ActionUpdate), string(governance.KindSource)}, "resume-trigger": {string(governance.ActionUpdate), string(governance.KindTrigger)}, "rotate-source-secret": {string(governance.ActionReadSecret), string(governance.KindSecret)}, } { if got[id] != want { t.Errorf("%s declares %v, want %v", id, got[id], want) } } }