package events import ( "context" "errors" "io" "log/slog" "net/http" "net/http/httptest" "slices" "strings" "testing" "github.com/google/uuid" "github.com/samcharles93/archie-core/internal/platform/httpjson" "github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/events/internal/store" "github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/runs" ) // deliveryPolicy answers every delivery with one decision and records who // asked. type deliveryPolicy struct { decision governance.Decision asked []string } func (d *deliveryPolicy) AuthorizeDelivery(_ context.Context, org governance.OrgID, source, addr string) governance.Decision { d.asked = append(d.asked, string(org)+" "+source+" "+addr) return d.decision } // onceInserter stores an event once per source event id, as the table's // uniqueness constraint does. type onceInserter struct{ stored map[string]bool } func (o *onceInserter) Insert(_ context.Context, e store.Event) (bool, error) { if o.stored[e.SourceEventID] { return false, nil } o.stored[e.SourceEventID] = true return true, nil } type noEcho struct{} func (noEcho) SentBy(context.Context, string, ...string) (uuid.UUID, bool, error) { return uuid.Nil, false, nil } func (noEcho) Send(context.Context, string, string, string, string) error { return nil } // TestIntakeAppliesTheDeliveryPolicyBeforeStoring guards the webhook entry // point: a delivery that passes source verification is still refused when the // per-source, per-address delivery policy denies it or can't be read, and // nothing is parsed or stored then. A redelivery of a stored event id is // counted as a duplicate and stored once, so it can't dispatch again. func TestIntakeAppliesTheDeliveryPolicyBeforeStoring(t *testing.T) { const token = "not-a-real-token" //nolint:gosec // fixture bearer token the verifier must accept denied := governance.DeniedAt(governance.LevelObject, []string{"hook-allowlist"}) tests := []struct { name string bearer string policy governance.Decision unwired bool deliveries int want int wantBody string wantStored int wantAsked []string }{ {name: "an allowed delivery is stored", bearer: token, policy: governance.Allowed(), deliveries: 1, want: http.StatusAccepted, wantBody: `"stored":1`, wantStored: 1, wantAsked: []string{"org-sys hook 203.0.113.9"}}, {name: "a redelivered event id is counted, not stored again", bearer: token, policy: governance.Allowed(), deliveries: 2, want: http.StatusAccepted, wantBody: `"duplicates":1`, wantStored: 1, wantAsked: []string{"org-sys hook 203.0.113.9", "org-sys hook 203.0.113.9"}}, {name: "a valid token with a denying policy", bearer: token, policy: denied, deliveries: 1, want: http.StatusForbidden, wantAsked: []string{"org-sys hook 203.0.113.9"}}, {name: "a valid token while the chain is unavailable", bearer: token, policy: governance.Unavailable(), deliveries: 1, want: http.StatusServiceUnavailable, wantAsked: []string{"org-sys hook 203.0.113.9"}}, {name: "a valid token with no policy wired", bearer: token, unwired: true, deliveries: 1, want: http.StatusServiceUnavailable}, {name: "a wrong token never reaches the policy", bearer: "other", policy: governance.Allowed(), deliveries: 1, want: http.StatusUnauthorized}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { policy := &deliveryPolicy{decision: tt.policy} inserter := &onceInserter{stored: map[string]bool{}} m := &Module{ orgID: "default", log: slog.New(slog.DiscardHandler), inserter: inserter, deliveries: noEcho{}, reader: fakeSources{store.Source{OrgID: "default", Name: "hook", Connector: "c", Verification: store.Token, TokenSHA256: httpjson.TokenHash(token)}}, parse: func(context.Context, string, []byte, map[string]string) ([]connectors.Event, error) { return []connectors.Event{{Type: "alert", SourceEventID: "evt-1"}}, nil }, } if !tt.unwired { m.UseDeliveryPolicy(policy) } var rec *httptest.ResponseRecorder for range tt.deliveries { req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/hooks/hook", strings.NewReader(`{}`)) req.SetPathValue("source", "hook") req.RemoteAddr = "203.0.113.9:4711" req.Header.Set("Authorization", "Bearer "+tt.bearer) rec = httptest.NewRecorder() m.intake(rec, req) } body, _ := io.ReadAll(rec.Body) if rec.Code != tt.want || !strings.Contains(string(body), tt.wantBody) { t.Fatalf("status %d body %s, want %d containing %q", rec.Code, body, tt.want, tt.wantBody) } if len(inserter.stored) != tt.wantStored { t.Fatalf("events stored = %d, want %d", len(inserter.stored), tt.wantStored) } if !slices.Equal(policy.asked, tt.wantAsked) { t.Fatalf("delivery policy asked %v, want %v", policy.asked, tt.wantAsked) } }) } } // startRecorder is the run starter a trigger calls: it records the principal // each start carried and answers with a fixed error. type startRecorder struct { err error principals []governance.IdentityID } func (s *startRecorder) Start(ctx context.Context, _ runs.StartRequest) (uuid.UUID, error) { p, _ := governance.PrincipalFromContext(ctx) s.principals = append(s.principals, p.IdentityID) return uuid.New(), s.err } func (*startRecorder) CheckTrigger(context.Context, string, string) error { return nil } // TestTriggersStartRunsAsTheWorkload guards that dispatching an event never // starts a run without a principal: the workload principal acts, a refusal // skips the trigger for good, and a chain that can't decide fails the dispatch // so the event stays queued instead of being dropped. func TestTriggersStartRunsAsTheWorkload(t *testing.T) { tests := []struct { name string err error wantStarted bool wantErr error }{ {name: "an allowed start", wantStarted: true}, {name: "a refused start is final", err: governance.ErrDenied}, {name: "an undecidable start is retried", err: governance.ErrChainUnavailable, wantErr: governance.ErrChainUnavailable}, {name: "another failure is retried", err: errors.New("database down"), wantErr: errors.New("database down")}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { starts := &startRecorder{err: tt.err} m := &Module{runs: starts, log: slog.New(slog.DiscardHandler)} _, started, err := m.startRun(t.Context(), store.Event{ID: uuid.New(), OrgID: "default"}, store.Trigger{Name: "t", Workflow: "triage"}) if started != tt.wantStarted { t.Fatalf("started = %v, want %v", started, tt.wantStarted) } if (err == nil) != (tt.wantErr == nil) || (tt.wantErr != nil && !strings.Contains(err.Error(), tt.wantErr.Error())) { t.Fatalf("error = %v, want %v", err, tt.wantErr) } if !slices.Equal(starts.principals, []governance.IdentityID{governance.WorkloadID}) { t.Fatalf("start acted as %v, want the workload principal", starts.principals) } }) } }