Merge branch 'worktree-agent-a82ec64b6cc1a2809'

# Conflicts:
#	internal/app/archie/operations.go
#	modules/events/events.go
#	modules/governance/accounts_api.go
#	modules/governance/governance.go
This commit is contained in:
sam committed 2026-11-22 02:16:56 +11:00
commit e3130d53e7
44 files changed
+1462 -266

No files matched your search

+165
View File
@@ -0,0 +1,165 @@
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)
}
})
}
}
+9 -8
View File
@@ -17,6 +17,7 @@ import (
"github.com/samcharles93/archie-core/internal/platform/httpapi"
"github.com/samcharles93/archie-core/internal/platform/httpjson"
"github.com/samcharles93/archie-core/modules/events/internal/store"
"github.com/samcharles93/archie-core/modules/governance"
"github.com/samcharles93/archie-core/modules/runs"
)
@@ -24,35 +25,35 @@ import (
// and the events themselves.
func (m *Module) Register(api huma.API) {
tags := []string{"Events"}
huma.Register(api, huma.Operation{
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindSource), huma.Operation{
OperationID: "list-sources", Method: http.MethodGet, Path: "/api/sources",
Summary: "List sources", Tags: tags,
}, m.sources)
huma.Register(api, huma.Operation{
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindSource), huma.Operation{
OperationID: "put-source", Method: http.MethodPut, Path: "/api/sources/{name}",
Summary: "Add or update a source, its verification scheme and its token", Tags: tags,
}, m.putSource)
huma.Register(api, huma.Operation{
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindSource), huma.Operation{
OperationID: "put-source-key-fields", Method: http.MethodPut, Path: "/api/sources/{name}/key-fields",
Summary: "Set the fields a source's events are grouped by", Tags: tags,
}, m.putKeyFields)
huma.Register(api, huma.Operation{
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindTrigger), huma.Operation{
OperationID: "list-triggers", Method: http.MethodGet, Path: "/api/triggers",
Summary: "List triggers", Tags: tags,
}, m.triggers)
huma.Register(api, huma.Operation{
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindTrigger), huma.Operation{
OperationID: "put-trigger", Method: http.MethodPut, Path: "/api/triggers/{name}",
Summary: "Add or change a trigger", Tags: tags,
}, m.putTrigger)
huma.Register(api, huma.Operation{
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindEventIngest), huma.Operation{
OperationID: "list-groups", Method: http.MethodGet, Path: "/api/groups",
Summary: "List groups of unmatched events", Tags: tags,
}, m.groups)
huma.Register(api, huma.Operation{
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindEventIngest), huma.Operation{
OperationID: "list-events", Method: http.MethodGet, Path: "/api/events",
Summary: "List recent events", Tags: tags,
}, m.recent)
huma.Register(api, huma.Operation{
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindEventIngest), huma.Operation{
OperationID: "get-event", Method: http.MethodGet, Path: "/api/events/{id}",
Summary: "Get an event with its payload and the runs it started", Tags: tags,
}, m.event)
+93 -18
View File
@@ -16,6 +16,7 @@ import (
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"regexp"
"strings"
@@ -89,6 +90,8 @@ type Module struct {
orgID string
store *store.Store
reader sourceReader
inserter eventInserter
delivery governance.DeliveryAuthorizer
sealer Sealer
parse func(ctx context.Context, connector string, body []byte, headers map[string]string) ([]connectors.Event, error)
connectors Connectors
@@ -103,7 +106,7 @@ type Module struct {
// NewModule returns the events module for orgID.
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, sealer Sealer, c Connectors, r Runs, a Answers, l Links, d Deliveries) *Module {
st := store.New(db)
m := &Module{orgID: orgID, store: st, reader: st, sealer: sealer, connectors: c, runs: r, answers: a, links: l, deliveries: d, log: log, poll: time.Second}
m := &Module{orgID: orgID, store: st, reader: st, inserter: st, sealer: sealer, connectors: c, runs: r, answers: a, links: l, deliveries: d, log: log, poll: time.Second}
m.parse = m.parseWith
return m
}
@@ -113,15 +116,26 @@ type sourceReader interface {
Source(ctx context.Context, orgID, name string) (store.Source, error)
}
// eventInserter stores an event, and reports false when its source event id
// was stored before.
type eventInserter interface {
Insert(ctx context.Context, e store.Event) (isNew bool, err error)
}
// UseDeliveryPolicy gives intake the policy that decides, per source and
// sender address, who may deliver. Until it is set every delivery is refused.
func (m *Module) UseDeliveryPolicy(d governance.DeliveryAuthorizer) { m.delivery = d }
// Routes adds the webhook intake. It stays outside the API because each
// source verifies its own deliveries.
func (m *Module) Routes(mux *http.ServeMux) {
mux.HandleFunc("POST /hooks/{source}", m.intake)
}
// intake verifies a delivery, parses it with the source's connector and stores
// each event before responding. A redelivered event violates a uniqueness
// constraint and is counted as a duplicate.
// intake verifies a delivery, checks the source's delivery policy, parses it
// with the source's connector and stores each event before responding. A
// redelivered event violates a uniqueness constraint, is counted as a
// duplicate and is not dispatched again.
func (m *Module) intake(w http.ResponseWriter, r *http.Request) {
src, parsed, body, status, err := m.accept(r)
if err != nil {
@@ -170,6 +184,9 @@ func (m *Module) accept(r *http.Request) (src store.Source, parsed []connectors.
return m.refuse(ctx, src, err)
}
}
if status, err := m.deliveryAllowed(ctx, src, r); err != nil {
return src, nil, nil, status, err
}
parsed, err = m.parse(ctx, src.Connector, body, map[string]string{"Content-Type": r.Header.Get("Content-Type")})
if errors.Is(err, errConnectorDown) {
return src, nil, nil, http.StatusServiceUnavailable, err
@@ -195,6 +212,36 @@ func (m *Module) refuse(ctx context.Context, src store.Source, err error) (store
return src, nil, nil, http.StatusServiceUnavailable, errors.New("couldn't verify the delivery")
}
var (
errDeliveryDenied = errors.New("delivery not permitted")
errDeliveryUnavailable = errors.New("delivery policy unavailable")
)
// deliveryAllowed applies the source's delivery policy to the sender's address.
// A verified delivery still needs it. When the policy chain can't decide the
// delivery is refused with 503, so the sender retries and nothing is stored.
func (m *Module) deliveryAllowed(ctx context.Context, src store.Source, r *http.Request) (int, error) {
if m.delivery == nil {
return http.StatusServiceUnavailable, errDeliveryUnavailable
}
addr, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
addr = r.RemoteAddr
}
// Delivery policies belong to the operating organisation, whatever the
// source's own org id says.
d := m.delivery.AuthorizeDelivery(ctx, governance.DefaultOrgID, src.Name, addr)
switch {
case d.Allowed:
return 0, nil
case errors.Is(d.Err, governance.ErrChainUnavailable):
m.log.WarnContext(ctx, "delivery policy unavailable", "source", src.Name)
return http.StatusServiceUnavailable, errDeliveryUnavailable
}
m.log.WarnContext(ctx, "refused webhook delivery", "source", src.Name, "reason", "delivery policy", "level", d.Level, "policies", d.Policies)
return http.StatusForbidden, errDeliveryDenied
}
// parseWith has a running connector parse a delivery.
func (m *Module) parseWith(ctx context.Context, connector string, body []byte, headers map[string]string) ([]connectors.Event, error) {
conn, ok := m.connectors.Get(connector)
@@ -212,7 +259,7 @@ func (m *Module) save(ctx context.Context, src store.Source, parsed []connectors
if err != nil {
return stored, duplicates, fmt.Errorf("check delivery provenance: %w", err)
}
isNew, err := m.store.Insert(ctx, newRow(m.orgID, src, e, body, own, run))
isNew, err := m.inserter.Insert(ctx, newRow(m.orgID, src, e, body, own, run))
if err != nil {
return stored, duplicates, err
}
@@ -434,7 +481,7 @@ func (m *Module) dispatch(tx *sqlx.Tx, e store.Event) (bool, error) {
if err != nil {
return false, err
}
matched := false
matched, refused := false, false
for _, t := range triggers {
var filter map[string]string
if err := json.Unmarshal(t.Filter, &filter); err != nil {
@@ -443,11 +490,13 @@ func (m *Module) dispatch(tx *sqlx.Tx, e store.Event) (bool, error) {
if !match.Fields(e.Fields, filter) {
continue
}
runID, err := m.runs.Start(ctx, runs.StartRequest{
OrgID: e.OrgID, Workflow: t.Workflow, Key: e.ID.String() + ":" + t.Name, Input: runInput(e),
})
runID, started, err := m.startRun(ctx, e, t)
if err != nil {
return false, fmt.Errorf("start run for trigger %q: %w", t.Name, err)
return false, err
}
if !started {
refused = true
continue
}
if err := store.RecordDispatch(ctx, tx, e.ID, t.Name, runID); err != nil {
return false, err
@@ -455,18 +504,44 @@ func (m *Module) dispatch(tx *sqlx.Tx, e store.Event) (bool, error) {
m.log.InfoContext(ctx, "trigger started run", "event", e.ID, "trigger", t.Name, "run", runID)
matched = true
}
if !matched {
created, err := store.NoteUnmatched(ctx, tx, e)
if err != nil {
return false, err
}
if created {
m.log.InfoContext(ctx, "unmatched events started a group", "source", e.Source, "type", e.Type)
}
if !matched && !refused {
return false, m.noteUnmatched(ctx, tx, e)
}
return matched, nil
}
// noteUnmatched files an event no trigger took into a group for review.
func (m *Module) noteUnmatched(ctx context.Context, tx *sqlx.Tx, e store.Event) error {
created, err := store.NoteUnmatched(ctx, tx, e)
if err != nil {
return err
}
if created {
m.log.InfoContext(ctx, "unmatched events started a group", "source", e.Source, "type", e.Type)
}
return nil
}
// startRun starts the run trigger t asks for, as the workload principal, so
// the start is decided by the same policy chain as any other caller. A refusal
// is final: it reports no run and no error, and the trigger is skipped. A policy
// chain that can't decide returns an error instead, which rolls the dispatch
// back so the event stays queued and is dispatched again.
func (m *Module) startRun(ctx context.Context, e store.Event, t store.Trigger) (runID uuid.UUID, started bool, err error) {
ctx = governance.WithPrincipal(ctx, governance.WorkloadPrincipal(governance.DefaultOrgID))
runID, err = m.runs.Start(ctx, runs.StartRequest{
OrgID: e.OrgID, Workflow: t.Workflow, Key: e.ID.String() + ":" + t.Name, Input: runInput(e),
})
if errors.Is(err, governance.ErrDenied) {
m.log.WarnContext(ctx, "trigger not permitted to start its workflow", "event", e.ID, "trigger", t.Name, "error", err)
return uuid.Nil, false, nil
}
if err != nil {
return uuid.Nil, false, fmt.Errorf("start run for trigger %q: %w", t.Name, err)
}
return runID, true, nil
}
// Origin returns the event and trigger that started a run.
func (m *Module) Origin(ctx context.Context, runID uuid.UUID) (runs.Origin, bool, error) {
o, ok, err := m.store.OriginOf(ctx, m.orgID, runID)
+1 -1
View File
@@ -50,7 +50,7 @@ func (m *Module) tick(ctx context.Context, now time.Time) error {
if err != nil {
return fmt.Errorf("encode tick: %w", err)
}
isNew, err := m.store.Insert(ctx, tickEvent(m.orgID, t.Name, slot, fields))
isNew, err := m.inserter.Insert(ctx, tickEvent(m.orgID, t.Name, slot, fields))
if err != nil {
return err
}
+9 -1
View File
@@ -16,6 +16,7 @@ import (
"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"
)
type fakeSources struct{ src store.Source }
@@ -71,7 +72,7 @@ func TestHMACSourceVerifiesBeforeParsing(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
parsed := false
m := &Module{
orgID: "org", reader: fakeSources{src}, sealer: sealer,
orgID: "org", reader: fakeSources{src}, sealer: sealer, delivery: permitAll{},
log: slog.New(slog.DiscardHandler),
parse: func(context.Context, string, []byte, map[string]string) ([]connectors.Event, error) {
parsed = true
@@ -93,3 +94,10 @@ func TestHMACSourceVerifiesBeforeParsing(t *testing.T) {
})
}
}
// permitAll accepts a delivery from any address.
type permitAll struct{}
func (permitAll) AuthorizeDelivery(context.Context, governance.OrgID, string, string) governance.Decision {
return governance.Allowed()
}