From d0d79cbf91e29325be09d77500a787717f399a74 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sat, 28 Nov 2026 00:42:37 +1100 Subject: [PATCH] feat(audit,approvals,deliveries): wire audit producers, ITSM change requests, and fix Dockerfile.archie (#2153) --- Dockerfile.archie | 4 +- internal/app/archie/bundle.go | 17 +++ internal/app/archie/rekey.go | 16 +++ internal/app/archie/run.go | 42 +++++++ .../00021_deliveries_change_requests.sql | 13 +++ modules/approvals/approvals.go | 85 +++++++++++++- modules/approvals/approvals_test.go | 22 ++++ modules/approvals/dashboard.go | 11 ++ modules/audit/audit.go | 24 ++++ modules/connectors/capabilities.go | 17 ++- modules/connectors/catalogue.go | 1 + modules/connectors/installations.go | 1 + modules/connectors/module.go | 18 +++ modules/connectors/packages.go | 2 + modules/connectors/remove.go | 2 + modules/deliveries/access_test.go | 40 +++++++ modules/deliveries/deliveries.go | 109 ++++++++++++++++-- modules/deliveries/internal/store/store.go | 18 +++ modules/events/access_test.go | 77 +++++++++++++ modules/events/events.go | 91 ++++++++++++--- modules/governance/accounts_api.go | 8 ++ modules/governance/governance.go | 22 ++++ modules/governance/store_access.go | 16 ++- modules/governance/store_identities.go | 19 ++- modules/judgement/policies.go | 18 ++- modules/system/system.go | 13 +++ 26 files changed, 671 insertions(+), 35 deletions(-) create mode 100644 internal/platform/pg/migrations/00021_deliveries_change_requests.sql diff --git a/Dockerfile.archie b/Dockerfile.archie index b7ea61498..5483785b6 100644 --- a/Dockerfile.archie +++ b/Dockerfile.archie @@ -4,8 +4,8 @@ # ── dashboard ── FROM node:24-trixie-slim AS ui WORKDIR /src/ui -RUN npm install -g pnpm@10 -COPY ui/package.json ui/pnpm-lock.yaml ./ +RUN corepack enable +COPY ui/package.json ui/pnpm-lock.yaml ui/pnpm-workspace.yaml ./ RUN --mount=type=cache,target=/root/.local/share/pnpm/store \ pnpm install --frozen-lockfile COPY ui/ ./ diff --git a/internal/app/archie/bundle.go b/internal/app/archie/bundle.go index 74ac8be28..c59131cc8 100644 --- a/internal/app/archie/bundle.go +++ b/internal/app/archie/bundle.go @@ -26,6 +26,7 @@ import ( "github.com/samcharles93/archie-core/internal/buildinfo" "github.com/samcharles93/archie-core/internal/platform/pg" "github.com/samcharles93/archie-core/internal/platform/stableid" + "github.com/samcharles93/archie-core/modules/audit" "github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/judgement" "github.com/samcharles93/archie-core/modules/runs" @@ -827,6 +828,22 @@ func applyBundleDB(ctx context.Context, db *sqlx.DB, log *slog.Logger, desired B if err := tx.Commit(); err != nil { return BundleDiff{}, fmt.Errorf("commit bundle: %w", err) } + digest, _ := desired.Digest() + audit.Emit(ctx, audit.NewModule(db, log, orgID), log, audit.Event{ + Category: "promotion", + Action: "bundle.apply", + ActorID: governance.CallerID(ctx), + ResourceKind: "bundle", + ResourceID: digest, + Outcome: "success", + Detail: map[string]any{ + "stage": stage, + "workflows_changed": len(diff.Workflows), + "access_policies_changed": len(diff.AccessPolicies), + "judgement_rules_changed": len(diff.JudgementRules), + "action_types_changed": len(diff.ActionTypes), + }, + }) } logBundleApply(ctx, log, stage, dryRun, diff) diff --git a/internal/app/archie/rekey.go b/internal/app/archie/rekey.go index 2280b0082..f72d1c843 100644 --- a/internal/app/archie/rekey.go +++ b/internal/app/archie/rekey.go @@ -14,8 +14,10 @@ import ( "github.com/samcharles93/archie-core/internal/buildinfo" "github.com/samcharles93/archie-core/internal/platform/pg" "github.com/samcharles93/archie-core/internal/platform/seal" + "github.com/samcharles93/archie-core/modules/audit" "github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/events" + "github.com/samcharles93/archie-core/modules/governance" ) const rekeyLockKey = "archie.rekey.owner" @@ -134,6 +136,20 @@ func Rekey(ctx context.Context, configPath string, rcfg RekeyConfig) error { if err := tx.Commit(); err != nil { return fmt.Errorf("commit rekey transaction: %w", err) } + audit.Emit(ctx, audit.NewModule(db, log, orgID), log, audit.Event{ + Category: "crypto", + Action: "sealing.rekey", + ActorID: string(governance.SystemID), + ActorKind: "system", + ResourceKind: "org", + ResourceID: orgID, + Outcome: "success", + Detail: map[string]any{ + "credentials_rekeyed": creds, + "sources_rekeyed": sources, + "backup_recipients": len(rcfg.NewBackups), + }, + }) log.InfoContext(ctx, "age sealing keys rotated", "credentials_rekeyed", creds, "sources_rekeyed", sources, diff --git a/internal/app/archie/run.go b/internal/app/archie/run.go index c04ec99ce..b764fbebd 100644 --- a/internal/app/archie/run.go +++ b/internal/app/archie/run.go @@ -261,6 +261,7 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB, draining hear.Routes(mux) engine.UseReferrers(hear) judge := newJudgement(db, log, conns, actionTypes, policies, settings, hear) + wireAuditAndChanges(log, auditLog, settings, allow, policies, conns, sys, tell) remember, err := wireMemory(db, log, cfg.StateDir, checks) if err != nil { return nil, err @@ -413,6 +414,47 @@ func newJudgement(db *sqlx.DB, log *slog.Logger, conns *connectors.Module, actio return judge } +func wireAuditAndChanges( + log *slog.Logger, + auditLog *audit.Module, + settings *governance.Module, + allow *approvals.Module, + policies *judgement.Policies, + conns *connectors.Module, + sys *system.Module, + tell *deliveries.Module, +) { + settings.UseAudit(func(ctx context.Context, e governance.AuditRecord) { + audit.Emit(ctx, auditLog, log, audit.Event{ + Category: e.Category, Action: e.Action, ActorID: e.ActorID, ActorKind: e.ActorKind, + ResourceKind: e.ResourceKind, ResourceID: e.ResourceID, Outcome: e.Outcome, Detail: e.Detail, + }) + }) + allow.UseAudit(auditLog) + policies.UseAudit(auditLog) + conns.UseAudit(auditLog) + sys.UseAudit(auditLog) + allow.UseChangeRequests(changeRequests{tell: tell}) +} + +type changeRequests struct { + tell *deliveries.Module +} + +func (c changeRequests) Open(ctx context.Context, r approvals.Request) error { + return c.tell.OpenChangeRequest(ctx, deliveries.ChangeRequest{ + RunID: r.RunID, + RequestID: r.ID, + Key: r.Key, + ShortDescription: "Archie change: " + r.Connector + " " + r.Action, + Description: r.Summary, + }) +} + +func (c changeRequests) Withdraw(ctx context.Context, r approvals.Request) error { + return c.tell.WithdrawChangeRequest(ctx, r.RunID, r.ID, r.Key, "the approval expired") +} + // orgID is the one organisation until hosting is multi-tenant. const orgID = "default" diff --git a/internal/platform/pg/migrations/00021_deliveries_change_requests.sql b/internal/platform/pg/migrations/00021_deliveries_change_requests.sql new file mode 100644 index 000000000..95134cb26 --- /dev/null +++ b/internal/platform/pg/migrations/00021_deliveries_change_requests.sql @@ -0,0 +1,13 @@ +-- +goose Up +ALTER TABLE deliveries.messages + DROP CONSTRAINT IF EXISTS messages_kind_check; +ALTER TABLE deliveries.messages + ADD CONSTRAINT messages_kind_check + CHECK (kind IN ('notification', 'approval_request', 'approval_answer', 'change_request', 'change_request_withdraw')); + +-- +goose Down +ALTER TABLE deliveries.messages + DROP CONSTRAINT IF EXISTS messages_kind_check; +ALTER TABLE deliveries.messages + ADD CONSTRAINT messages_kind_check + CHECK (kind IN ('notification', 'approval_request', 'approval_answer')); diff --git a/modules/approvals/approvals.go b/modules/approvals/approvals.go index 58607acd6..d6bfeb316 100644 --- a/modules/approvals/approvals.go +++ b/modules/approvals/approvals.go @@ -5,6 +5,7 @@ package approvals import ( + "cmp" "context" "database/sql" "encoding/json/jsontext" @@ -22,6 +23,7 @@ import ( "github.com/samcharles93/archie-core/internal/platform/hub" "github.com/samcharles93/archie-core/modules/approvals/internal/store" + "github.com/samcharles93/archie-core/modules/audit" "github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/deliveries" "github.com/samcharles93/archie-core/modules/governance" @@ -273,6 +275,7 @@ type Module struct { authz governance.Authorizer confirm Confirmer changes ChangeRequests + audit audit.Recorder log *slog.Logger now func() time.Time } @@ -285,6 +288,10 @@ func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tell Delivery, wake } } +// UseAudit configures the audit recorder notified on approval requests, decisions, +// refusals, and expirations. +func (m *Module) UseAudit(r audit.Recorder) { m.audit = r } + // UseLive publishes a note on the hub whenever a request moves, so a mounted // view re-reads instead of polling. func (m *Module) UseLive(h *hub.Hub) { @@ -340,15 +347,27 @@ func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, ds []judg if err := m.changes.Open(ctx, r); err != nil { return Request{}, fmt.Errorf("open change request: %w", err) } - return r, nil - } - if err := m.tell.Ask(ctx, deliveries.ApprovalRequest{ + } else if err := m.tell.Ask(ctx, deliveries.ApprovalRequest{ RunID: r.RunID, RequestID: r.ID, Key: r.Key + ":ask", Title: approvalTitle(ds), Body: r.Summary, ExpiresAt: r.StepDeadline, }); err != nil { return Request{}, fmt.Errorf("send approval request: %w", err) } + audit.Emit(ctx, m.audit, m.log, audit.Event{ + Category: "approval", + Action: "approval.request", + ActorID: cmp.Or(r.InitiatorID, string(governance.WorkloadID)), + ResourceKind: "approval", + ResourceID: r.ID.String(), + Outcome: StatePending, + Detail: map[string]any{ + "connector": r.Connector, + "action": r.Action, + "change_request": r.ChangeRequest, + "require_sod": r.RequireSoD, + }, + }) return r, nil } @@ -408,6 +427,19 @@ func (m *Module) answerAs(ctx context.Context, id uuid.UUID, who Answerer, via s if row.State != state { return Request{}, fmt.Errorf("%w: %s", ErrAnswered, row.State) } + action := "approval.deny" + if approved { + action = "approval.approve" + } + audit.Emit(ctx, m.audit, m.log, audit.Event{ + Category: "approval", + Action: action, + ActorID: cmp.Or(who.ID, who.Name, "unknown"), + ActorKind: via, + ResourceKind: "approval", + ResourceID: row.ID.String(), + Outcome: state, + }) answer := Answer{RequestID: row.ID, Approved: approved, By: who.Name, ByID: who.ID, Via: via, At: now} if row.Kind == KindAutonomy { if err := m.answerProposal(ctx, row, answer); err != nil { @@ -525,6 +557,16 @@ func (m *Module) Settle(ctx context.Context, id uuid.UUID, who governance.Subjec if refusal(err) { identity := who.Issuer + ":" + who.Subject m.log.WarnContext(ctx, "approval answer refused", "request", id, "identity", identity, "reason", err.Error()) + audit.Emit(ctx, m.audit, m.log, audit.Event{ + Category: "approval", + Action: "approval.refuse", + ActorID: identity, + ActorKind: via, + ResourceKind: "approval", + ResourceID: id.String(), + Outcome: "denied", + Detail: map[string]any{"reason": err.Error()}, + }) if rerr := m.store.Refuse(ctx, store.Refusal{ ID: uuid.New(), OrgID: m.orgID, RequestID: id, Identity: identity, Via: via, Reason: err.Error(), At: m.now().UTC(), }); rerr != nil { @@ -548,6 +590,34 @@ func (m *Module) Settle(ctx context.Context, id uuid.UUID, who governance.Subjec return false, err } +// SettleChangeRequest settles a pending change-request approval from an +// external ITSM decision event. Missing, already-settled, expired, or +// non-change-request items return (false, nil). +func (m *Module) SettleChangeRequest(ctx context.Context, id uuid.UUID, connector, changeNumber string, approved bool) (bool, error) { + row, err := m.store.ByID(ctx, m.orgID, id) + if errors.Is(err, ErrNotFound) { + return false, nil + } + if err != nil { + return false, err + } + if !row.ChangeRequest || row.State != StatePending { + return false, nil + } + who := Answerer{ + ID: connector + ":" + changeNumber, + Name: strings.TrimSpace(connector + " " + changeNumber), + } + _, err = m.answerAs(ctx, id, who, connector, approved) + switch { + case err == nil: + return true, nil + case errors.Is(err, ErrAnswered), errors.Is(err, ErrExpired), errors.Is(err, ErrNotFound): + return false, nil + } + return false, err +} + // channelAnswerer returns the account that holds the channel credential when // that account may answer row. func (m *Module) channelAnswerer(ctx context.Context, who governance.Subject, row store.Request) (Answerer, error) { @@ -660,6 +730,15 @@ func (m *Module) Expire(ctx context.Context, id uuid.UUID) error { return nil } m.log.InfoContext(ctx, "approval request expired", "request", row.ID, "run", row.RunID) + audit.Emit(ctx, m.audit, m.log, audit.Event{ + Category: "approval", + Action: "approval.expire", + ActorID: "clock", + ActorKind: "system", + ResourceKind: "approval", + ResourceID: row.ID.String(), + Outcome: StateExpired, + }) withdrawn := "" if row.ChangeRequest { if err := m.changes.Withdraw(ctx, requestOf(row, judgement.Decision{})); err != nil { diff --git a/modules/approvals/approvals_test.go b/modules/approvals/approvals_test.go index 7c5d9f6bf..6e7ab4638 100644 --- a/modules/approvals/approvals_test.go +++ b/modules/approvals/approvals_test.go @@ -3,12 +3,14 @@ package approvals import ( "context" "errors" + "log/slog" "testing" "time" "github.com/google/uuid" "github.com/samcharles93/archie-core/modules/approvals/internal/store" + "github.com/samcharles93/archie-core/modules/audit" "github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/judgement" ) @@ -296,3 +298,23 @@ func TestSoDRefusesSelfApproval(t *testing.T) { t.Fatal("requireSoDOf override true returned false") } } + +type recordedAudit []audit.Event + +func (r *recordedAudit) Record(_ context.Context, e audit.Event) error { + *r = append(*r, e) + return nil +} + +func TestUseAuditRecordsRefusals(t *testing.T) { + var rec recordedAudit + m := &Module{log: slog.New(slog.DiscardHandler)} + m.UseAudit(&rec) + audit.Emit(t.Context(), m.audit, m.log, audit.Event{ + Category: "approval", Action: "approval.refuse", ActorID: "alice", + ResourceKind: "approval", ResourceID: uuid.NewString(), Outcome: "denied", + }) + if len(rec) != 1 || rec[0].Action != "approval.refuse" || rec[0].Outcome != "denied" { + t.Fatalf("recorded audit events = %+v", rec) + } +} diff --git a/modules/approvals/dashboard.go b/modules/approvals/dashboard.go index bbd3e03e2..2235512d5 100644 --- a/modules/approvals/dashboard.go +++ b/modules/approvals/dashboard.go @@ -12,6 +12,7 @@ import ( "github.com/samcharles93/archie-core/internal/platform/httpapi" "github.com/samcharles93/archie-core/modules/approvals/internal/store" + "github.com/samcharles93/archie-core/modules/audit" "github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/judgement" @@ -196,6 +197,16 @@ func (m *Module) refuse(ctx context.Context, id uuid.UUID, identity string, reas identity = "shared-token" } m.log.WarnContext(ctx, "approval answer refused", "request", id, "identity", identity, "reason", reason.Error()) + audit.Emit(ctx, m.audit, m.log, audit.Event{ + Category: "approval", + Action: "approval.refuse", + ActorID: identity, + ActorKind: viaDashboard, + ResourceKind: "approval", + ResourceID: id.String(), + Outcome: "denied", + Detail: map[string]any{"reason": reason.Error()}, + }) if err := m.store.Refuse(ctx, store.Refusal{ ID: uuid.New(), OrgID: m.orgID, RequestID: id, Identity: identity, Via: viaDashboard, Reason: reason.Error(), At: m.now().UTC(), }); err != nil { diff --git a/modules/audit/audit.go b/modules/audit/audit.go index d73df8ba1..f39f863a3 100644 --- a/modules/audit/audit.go +++ b/modules/audit/audit.go @@ -10,6 +10,7 @@ import ( "errors" "fmt" "log/slog" + "reflect" "time" "github.com/google/uuid" @@ -75,6 +76,29 @@ type auditStore interface { List(ctx context.Context, f store.Filter) ([]store.EventRow, error) } +// Recorder records immutable security and operational audit events. +type Recorder interface { + Record(ctx context.Context, e Event) error +} + +// Emit forwards e to r when r is configured, logging any persistence error to +// log without failing the caller's operation. +func Emit(ctx context.Context, r Recorder, log *slog.Logger, e Event) { + if r == nil { + return + } + v := reflect.ValueOf(r) + if v.Kind() == reflect.Pointer && v.IsNil() { + return + } + if m, ok := r.(*Module); ok && m.store == nil { + return + } + if err := r.Record(ctx, e); err != nil && log != nil { + log.WarnContext(ctx, "record audit event", "category", e.Category, "action", e.Action, "error", err) + } +} + // Module records and serves one organisation's append-only audit stream. type Module struct { orgID string diff --git a/modules/connectors/capabilities.go b/modules/connectors/capabilities.go index 5ef5d5c6a..f8427ef3c 100644 --- a/modules/connectors/capabilities.go +++ b/modules/connectors/capabilities.go @@ -15,14 +15,17 @@ import ( // the extension contract: a connector that declares one must declare a schema // that accepts what core sends. const ( - DeliveryMessage = "message" - DeliveryChatMessage = "chat_message" + DeliveryMessage = "message" + DeliveryChatMessage = "chat_message" + DeliveryChangeRequest = "change_request" + DeliveryChangeRequestWithdraw = "change_request_withdraw" ) // coreDeliveries lists, for each delivery core sends itself, every payload // shape core may put in it: a message always has a title, and may also carry // a body and, for an approval request, its request id; a chat message always -// has a chat id and text. +// has a chat id and text; change requests carry short_description and +// description; withdrawals carry key and reason. var coreDeliveries = map[string][]jsontext.Value{ DeliveryMessage: { jsontext.Value(`{"title":"a title"}`), @@ -33,13 +36,19 @@ var coreDeliveries = map[string][]jsontext.Value{ DeliveryChatMessage: { jsontext.Value(`{"chat_id":"a chat","text":"a message"}`), }, + DeliveryChangeRequest: { + jsontext.Value(`{"short_description":"a change","description":"details"}`), + }, + DeliveryChangeRequestWithdraw: { + jsontext.Value(`{"key":"req:change_request","reason":"approval expired"}`), + }, } // checkCoreDeliveries refuses a declaration of a delivery core sends itself // whose input schema rejects a payload core sends, so the mismatch surfaces // when the connector loads rather than when a delivery is mid-flight. func checkCoreDeliveries(caps Capabilities) error { - for _, name := range []string{DeliveryMessage, DeliveryChatMessage} { + for _, name := range []string{DeliveryMessage, DeliveryChatMessage, DeliveryChangeRequest, DeliveryChangeRequestWithdraw} { d, ok := caps.Delivery(name) if !ok { continue diff --git a/modules/connectors/catalogue.go b/modules/connectors/catalogue.go index 2c36c1258..f7012ceaa 100644 --- a/modules/connectors/catalogue.go +++ b/modules/connectors/catalogue.go @@ -110,6 +110,7 @@ func (m *Module) saveCatalogueSource(ctx context.Context, src store.Source) (*ht return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the catalogue source") } m.log.InfoContext(ctx, "catalogue source set", "audit", true, "action", "catalogue.source") + m.emitAudit(ctx, "catalogue.source", "catalogue", src.Location, nil) return m.getCatalogueSource(ctx, nil) } diff --git a/modules/connectors/installations.go b/modules/connectors/installations.go index 3d04c103e..c59425a71 100644 --- a/modules/connectors/installations.go +++ b/modules/connectors/installations.go @@ -251,6 +251,7 @@ func (m *Module) saveInstallation(ctx context.Context, auth authority, a store.I } m.log.InfoContext(ctx, "installation saved", "audit", true, "action", "installation.save", "installation", a.ID.String(), "scope", a.Scope, "package", a.PackageName) + m.emitAudit(ctx, "installation.save", "installation", a.ID.String(), map[string]any{"scope": a.Scope, "package": a.PackageName}) view, err := m.viewOf(a, auth.manages(a.Owner())) if err != nil { return nil, huma.NewError(http.StatusInternalServerError, err.Error()) diff --git a/modules/connectors/module.go b/modules/connectors/module.go index 978611716..559a6c66a 100644 --- a/modules/connectors/module.go +++ b/modules/connectors/module.go @@ -20,8 +20,10 @@ import ( "github.com/jmoiron/sqlx" "github.com/samcharles93/archie-core/internal/platform/seal" + "github.com/samcharles93/archie-core/modules/audit" "github.com/samcharles93/archie-core/modules/connectors/internal/catalogue" "github.com/samcharles93/archie-core/modules/connectors/internal/store" + "github.com/samcharles93/archie-core/modules/governance" ) // validName is the shape of a connector name: it appears in logs and URLs. @@ -35,6 +37,7 @@ type Module struct { host *Host store registry sealer *seal.Sealer + audit audit.Recorder log *slog.Logger // sources and fetcher read the catalogue and its artifacts, and pkgMu // serialises changes to a package's versions. @@ -80,6 +83,21 @@ func (m *Module) Use(recheck Recheck) { m.recheck = recheck } +// UseAudit configures the audit recorder notified on extension and catalogue changes. +func (m *Module) UseAudit(r audit.Recorder) { m.audit = r } + +func (m *Module) emitAudit(ctx context.Context, action, resourceKind, resourceID string, detail any) { + audit.Emit(ctx, m.audit, m.log, audit.Event{ + Category: "extensions", + Action: action, + ActorID: governance.CallerID(ctx), + ResourceKind: resourceKind, + ResourceID: resourceID, + Outcome: "success", + Detail: detail, + }) +} + // UseRemotes configures static remote gRPC+mTLS extension endpoints. func (m *Module) UseRemotes(cfg RemoteConfig) error { return m.host.UseRemotes(cfg) diff --git a/modules/connectors/packages.go b/modules/connectors/packages.go index 9341587d7..a73de70a9 100644 --- a/modules/connectors/packages.go +++ b/modules/connectors/packages.go @@ -137,6 +137,7 @@ func (m *Module) register(ctx context.Context, source catalogueSnapshot, entry c } m.log.InfoContext(ctx, "package version registered", "audit", true, "action", "package.register", "package", entry.Name, "version", v.Version, "digest", v.Digest) + m.emitAudit(ctx, "package.register", "package", entry.Name, map[string]any{"version": v.Version, "digest": v.Digest}) return pkg, ver, nil } @@ -183,6 +184,7 @@ func (m *Module) acceptGrants(ctx context.Context, v store.Version, want *grants } m.log.InfoContext(ctx, "package version accepted", "audit", true, "action", "package.accept", "version_id", v.ID.String(), "version", v.Version) + m.emitAudit(ctx, "package.accept", "package_version", v.ID.String(), map[string]any{"version": v.Version}) return accepted, nil } diff --git a/modules/connectors/remove.go b/modules/connectors/remove.go index f1a39977c..5392fb3e7 100644 --- a/modules/connectors/remove.go +++ b/modules/connectors/remove.go @@ -66,6 +66,7 @@ func (m *Module) removeAs(ctx context.Context, in *nameInput, contract string) ( // There is no audit trail module yet, so the removal is a structured log // line. m.log.InfoContext(ctx, "accepted package removed", "audit", true, "action", "package.remove", "contract", contract, "package", name) + m.emitAudit(ctx, "package.remove", "package", name, map[string]any{"contract": contract}) return httpapi.OK(packageState{Name: name, State: "removed"}), nil } @@ -143,6 +144,7 @@ func (m *Module) removeInstallation(ctx context.Context, in *installationInput) } m.log.InfoContext(ctx, "installation removed", "audit", true, "action", "installation.remove", "installation", a.ID.String(), "scope", a.Scope, "package", a.PackageName) + m.emitAudit(ctx, "installation.remove", "installation", a.ID.String(), map[string]any{"scope": a.Scope, "package": a.PackageName}) return httpapi.OK(packageState{Name: a.Name, State: "removed"}), nil } diff --git a/modules/deliveries/access_test.go b/modules/deliveries/access_test.go index d950e1e03..91bc56625 100644 --- a/modules/deliveries/access_test.go +++ b/modules/deliveries/access_test.go @@ -2,6 +2,7 @@ package deliveries import ( "context" + json "encoding/json/v2" "log/slog" "slices" "strings" @@ -105,3 +106,42 @@ func TestDeliveryIsAuthorizedOnEveryAttempt(t *testing.T) { }) } } + +func TestOpenChangeRequestFailsWithoutConnectorAndFormatsPayloads(t *testing.T) { + m := &Module{channels: &channelLookups{}, log: slog.New(slog.DiscardHandler)} + if err := m.OpenChangeRequest(t.Context(), ChangeRequest{ + RunID: uuid.New(), + RequestID: uuid.New(), + Key: "step:1", + ShortDescription: "Restart prod app", + Description: "Verdict summary", + }); err == nil || !strings.Contains(err.Error(), "no running connector") { + t.Fatalf("OpenChangeRequest without connector = %v, want missing connector error", err) + } + + kind, raw, err := deliveryPayload(store.Message{ + Kind: KindChangeRequest, + Title: "Short summary", + Body: "Full action details", + }) + if err != nil || kind != connectors.DeliveryChangeRequest { + t.Fatalf("deliveryPayload(change_request) = (%q, %v)", kind, err) + } + var cr map[string]string + if err := json.Unmarshal(raw, &cr); err != nil || cr["short_description"] != "Short summary" || cr["description"] != "Full action details" { + t.Fatalf("unexpected change_request payload: %s (%v)", raw, err) + } + + kind, raw, err = deliveryPayload(store.Message{ + Kind: KindChangeRequestWithdraw, + Title: "approval timed out", + Body: "step:1:change_request", + }) + if err != nil || kind != connectors.DeliveryChangeRequestWithdraw { + t.Fatalf("deliveryPayload(change_request_withdraw) = (%q, %v)", kind, err) + } + var wd map[string]string + if err := json.Unmarshal(raw, &wd); err != nil || wd["key"] != "step:1:change_request" || wd["reason"] != "approval timed out" { + t.Fatalf("unexpected change_request_withdraw payload: %s (%v)", raw, err) + } +} diff --git a/modules/deliveries/deliveries.go b/modules/deliveries/deliveries.go index 8bdd83424..5886df0ff 100644 --- a/modules/deliveries/deliveries.go +++ b/modules/deliveries/deliveries.go @@ -50,6 +50,10 @@ const ( KindApprovalRequest = "approval_request" // KindApprovalAnswer records what they answered. KindApprovalAnswer = "approval_answer" + // KindChangeRequest opens an external change request for an approval. + KindChangeRequest = "change_request" + // KindChangeRequestWithdraw withdraws an open external change request. + KindChangeRequestWithdraw = "change_request_withdraw" ) // Notification is something a run tells people: what happened, what was done, @@ -76,6 +80,15 @@ type ApprovalRequest struct { ExpiresAt time.Time } +// ChangeRequest is an approval routed through an external ITSM system. +type ChangeRequest struct { + RunID uuid.UUID + RequestID uuid.UUID + Key string + ShortDescription string + Description string +} + // Message is a composer message as the API shows it. Attempts are the delivery // attempts recorded on the connector rows that carry the same message, one per // channel. @@ -194,6 +207,64 @@ func (m *Module) Told(ctx context.Context, a ApprovalRequest, answer string) err }) } +// OpenChangeRequest queues a change_request delivery on every running connector +// that declares it, failing closed when no such connector is running. +func (m *Module) OpenChangeRequest(ctx context.Context, cr ChangeRequest) error { + if cr.Key == "" { + return errors.New("a change request needs a key") + } + targets := m.channels.Delivering(ctx, connectors.DeliveryChangeRequest) + if len(targets) == 0 { + return errors.New("no running connector supports change_request delivery") + } + if _, _, err := m.store.Insert(ctx, store.Message{ + ID: uuid.New(), OrgID: m.orgID, Channel: channelComposer, Kind: KindNotification, + RunID: uuid.NullUUID{UUID: cr.RunID, Valid: cr.RunID != uuid.Nil}, + Title: cr.ShortDescription, Body: cr.Description, Key: cr.Key + ":change_request:opened", Sent: true, + }); err != nil { + return err + } + for _, c := range targets { + if _, _, err := m.store.Insert(ctx, store.Message{ + ID: uuid.New(), OrgID: m.orgID, Channel: c.Name(), Kind: KindChangeRequest, + RunID: uuid.NullUUID{UUID: cr.RunID, Valid: cr.RunID != uuid.Nil}, + RequestID: uuid.NullUUID{UUID: cr.RequestID, Valid: cr.RequestID != uuid.Nil}, + Title: cr.ShortDescription, Body: cr.Description, Key: cr.Key + ":change_request", Sent: false, + }); err != nil { + return err + } + } + return nil +} + +// WithdrawChangeRequest queues a change_request_withdraw delivery on every +// running connector that declares it. +func (m *Module) WithdrawChangeRequest(ctx context.Context, runID, requestID uuid.UUID, key, reason string) error { + if key == "" { + return errors.New("a change request withdrawal needs a key") + } + for _, c := range m.channels.Delivering(ctx, connectors.DeliveryChangeRequestWithdraw) { + if _, _, err := m.store.Insert(ctx, store.Message{ + ID: uuid.New(), OrgID: m.orgID, Channel: c.Name(), Kind: KindChangeRequestWithdraw, + RunID: uuid.NullUUID{UUID: runID, Valid: runID != uuid.Nil}, + RequestID: uuid.NullUUID{UUID: requestID, Valid: requestID != uuid.Nil}, + Title: reason, Body: key + ":change_request", Key: key + ":change_request_withdraw", Sent: false, + }); err != nil { + return err + } + } + return nil +} + +// RequestByExternalID resolves an external change number confirmed on channel +// back to its Archie approval request ID. +func (m *Module) RequestByExternalID(ctx context.Context, channel, externalID string) (uuid.UUID, bool, error) { + if externalID == "" { + return uuid.Nil, false, nil + } + return m.store.RequestByExternalID(ctx, m.orgID, channel, externalID) +} + // send writes msg to the composer, which wakes its readers, and queues it for // every connector that delivers messages. Work sends the queued rows. func (m *Module) send(ctx context.Context, msg store.Message) error { @@ -302,18 +373,38 @@ func (m *Module) sendTo(ctx context.Context, msg store.Message) (string, error) if !ok { return "", fmt.Errorf("connector %q isn't running", msg.Channel) } - input := map[string]string{"title": msg.Title} - if msg.Body != "" { - input["body"] = msg.Body - } - if msg.Kind == KindApprovalRequest && msg.RequestID.Valid { - input["approval_request_id"] = msg.RequestID.UUID.String() - } - raw, err := json.Marshal(input) + deliveryType, raw, err := deliveryPayload(msg) if err != nil { return "", err } - return c.Deliver(ctx, connectors.DeliveryMessage, raw, msg.Key) + return c.Deliver(ctx, deliveryType, raw, msg.Key) +} + +func deliveryPayload(msg store.Message) (deliveryType string, raw []byte, err error) { + switch msg.Kind { + case KindChangeRequest: + raw, err = json.Marshal(map[string]string{ + "short_description": msg.Title, + "description": msg.Body, + }) + return connectors.DeliveryChangeRequest, raw, err + case KindChangeRequestWithdraw: + raw, err = json.Marshal(map[string]string{ + "key": msg.Body, + "reason": msg.Title, + }) + return connectors.DeliveryChangeRequestWithdraw, raw, err + default: + input := map[string]string{"title": msg.Title} + if msg.Body != "" { + input["body"] = msg.Body + } + if msg.Kind == KindApprovalRequest && msg.RequestID.Valid { + input["approval_request_id"] = msg.RequestID.UUID.String() + } + raw, err = json.Marshal(input) + return connectors.DeliveryMessage, raw, err + } } // backoff returns the wait before the next attempt, given the number of diff --git a/modules/deliveries/internal/store/store.go b/modules/deliveries/internal/store/store.go index f4f52de91..4f6eb5480 100644 --- a/modules/deliveries/internal/store/store.go +++ b/modules/deliveries/internal/store/store.go @@ -164,6 +164,24 @@ func (s *Store) SentBy(ctx context.Context, orgID, channel string, ids []string) return run, true, nil } +// RequestByExternalID finds the approval request associated with a confirmed +// change_request delivery matching externalID on channel. +func (s *Store) RequestByExternalID(ctx context.Context, orgID, channel, externalID string) (uuid.UUID, bool, error) { + var id uuid.NullUUID + err := s.db.GetContext(ctx, &id, ` + SELECT request_id FROM deliveries.messages + WHERE org_id = $1 AND channel = $2 AND kind = 'change_request' + AND external_id = $3 AND request_id IS NOT NULL + LIMIT 1`, orgID, channel, externalID) + if errors.Is(err, sql.ErrNoRows) { + return uuid.Nil, false, nil + } + if err != nil { + return uuid.Nil, false, fmt.Errorf("find change request message: %w", err) + } + return id.UUID, id.Valid, nil +} + // Failed records why an attempt failed, along with the attempt that failed. // The lease that Claim set still decides when the next attempt is due. func (s *Store) Failed(ctx context.Context, seq int64, attempt int, reason string, took time.Duration) error { diff --git a/modules/events/access_test.go b/modules/events/access_test.go index 34b0d4453..f986aee97 100644 --- a/modules/events/access_test.go +++ b/modules/events/access_test.go @@ -2,6 +2,7 @@ package events import ( "context" + "database/sql" "errors" "io" "log/slog" @@ -50,8 +51,84 @@ func (noEcho) SentBy(context.Context, string, ...string) (uuid.UUID, bool, error return uuid.Nil, false, nil } +func (noEcho) RequestByExternalID(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 } +type fakeChangeDeliveries struct { + noEcho + byNumber map[string]uuid.UUID +} + +func (f fakeChangeDeliveries) RequestByExternalID(_ context.Context, channel, externalID string) (uuid.UUID, bool, error) { + id, ok := f.byNumber[channel+":"+externalID] + return id, ok, nil +} + +type fakeChangeAnswers struct { + settled []struct { + id uuid.UUID + via string + number string + approved bool + } +} + +func (f *fakeChangeAnswers) Settle(context.Context, uuid.UUID, governance.Subject, string, bool) (bool, error) { + return false, nil +} + +func (f *fakeChangeAnswers) SettleChangeRequest(_ context.Context, id uuid.UUID, connector, changeNumber string, approved bool) (bool, error) { + f.settled = append(f.settled, struct { + id uuid.UUID + via string + number string + approved bool + }{id: id, via: connector, number: changeNumber, approved: approved}) + return true, nil +} + +func TestDispatchSettlesOwnChangeRequestDecisionEvents(t *testing.T) { + reqID := uuid.New() + answers := &fakeChangeAnswers{} + m := &Module{ + reader: oneSource{connector: "servicenow"}, + deliveries: fakeChangeDeliveries{byNumber: map[string]uuid.UUID{"servicenow:CHG0012345": reqID}}, + answers: answers, + log: slog.New(slog.DiscardHandler), + } + evApproved := store.Event{ + ID: uuid.New(), + OrgID: "default", + SourceID: hookSource, + DeclaredEventType: changeApprovedType, + LinkKey: sql.NullString{String: "CHG0012345", Valid: true}, + Own: true, + } + if _, err := m.dispatch(nil, evApproved); err != nil { + t.Fatalf("dispatch approved change event: %v", err) + } + evRejected := evApproved + evRejected.ID = uuid.New() + evRejected.DeclaredEventType = changeRejectedType + evRejected.LinkKey = sql.NullString{} + evRejected.Fields = []byte(`{"number":"CHG0012345"}`) + if _, err := m.dispatch(nil, evRejected); err != nil { + t.Fatalf("dispatch rejected change event: %v", err) + } + if len(answers.settled) != 2 { + t.Fatalf("settled count = %d, want 2", len(answers.settled)) + } + if answers.settled[0].id != reqID || answers.settled[0].via != "servicenow" || answers.settled[0].number != "CHG0012345" || !answers.settled[0].approved { + t.Fatalf("unexpected first settlement: %+v", answers.settled[0]) + } + if answers.settled[1].id != reqID || answers.settled[1].approved { + t.Fatalf("unexpected second settlement: %+v", answers.settled[1]) + } +} + // 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 diff --git a/modules/events/events.go b/modules/events/events.go index 0c30554d5..85c6a54bb 100644 --- a/modules/events/events.go +++ b/modules/events/events.go @@ -60,6 +60,9 @@ type Runs interface { // belonged to no run. type Deliveries interface { SentBy(ctx context.Context, channel string, ids ...string) (run uuid.UUID, found bool, err error) + // RequestByExternalID resolves a confirmed change_request's external ID + // back to its approval request ID. + RequestByExternalID(ctx context.Context, channel, externalID string) (uuid.UUID, bool, error) // Send writes text to one chat on a channel. Send(ctx context.Context, channel, chatID, text, key string) error } @@ -67,6 +70,7 @@ type Deliveries interface { // Answers settles the approval requests answer events name. type Answers interface { Settle(ctx context.Context, id uuid.UUID, who governance.Subject, via string, approved bool) (bool, error) + SettleChangeRequest(ctx context.Context, id uuid.UUID, connector, changeNumber string, approved bool) (bool, error) } // Links binds the channel accounts that account.link events name to the @@ -82,8 +86,10 @@ type Links interface { // Both name the sender as ":" in by, and may name // the chat to reply to in chat_id. const ( - answerType = "approval.answer" - linkType = "account.link" + answerType = "approval.answer" + linkType = "account.link" + changeApprovedType = "change.approved" + changeRejectedType = "change.rejected" ) // listenRetry is how long a listener waits after its stream breaks. @@ -551,6 +557,50 @@ func (m *Module) answer(ctx context.Context, e store.Event) error { return nil } +// settleChange resolves a confirmed change number from change.approved or +// change.rejected back to the pending change-request approval and settles it. +func (m *Module) settleChange(ctx context.Context, e store.Event, approved bool) error { + if !e.SourceID.Valid || m.reader == nil || m.deliveries == nil || m.answers == nil { + return nil + } + src, err := m.reader.Source(ctx, e.OrgID, e.SourceID.UUID) + if err != nil { + m.log.WarnContext(ctx, "change event from an unknown source", "event", e.ID, "source", e.SourceID.UUID, "error", err) + return nil + } + var changeNumber string + if e.LinkKey.Valid { + changeNumber = strings.TrimSpace(e.LinkKey.String) + } + if changeNumber == "" { + var f struct { + Number string `json:"number"` + } + if err := json.Unmarshal(e.Fields, &f); err == nil { + changeNumber = strings.TrimSpace(f.Number) + } + } + if changeNumber == "" { + m.log.WarnContext(ctx, "change event missing link key or change number", "event", e.ID) + return nil + } + reqID, found, err := m.deliveries.RequestByExternalID(ctx, src.Connector, changeNumber) + if err != nil { + return fmt.Errorf("lookup change request %s: %w", changeNumber, err) + } + if !found { + return nil + } + settled, err := m.answers.SettleChangeRequest(ctx, reqID, src.Connector, changeNumber, approved) + if err != nil { + return fmt.Errorf("settle change request %s: %w", reqID, err) + } + if !settled { + m.log.InfoContext(ctx, "change request decision changed nothing", "event", e.ID, "request", reqID, "change", changeNumber) + } + return nil +} + // link binds the channel account that sent a link code to the account that // issued the code, and tells the sender how it went. A code that doesn't work // is not retried. @@ -631,18 +681,8 @@ func (m *Module) reply(ctx context.Context, e store.Event, src store.Source, cha // dispatch never starts a second run. func (m *Module) dispatch(tx *sqlx.Tx, e store.Event) (bool, error) { ctx := context.Background() - if e.Own { - // Archie's own message coming back starts nothing and proposes nothing. - return false, nil - } - switch e.DeclaredEventType { - case answerType: - return false, m.answer(ctx, e) - case linkType: - if err := m.link(ctx, e); err != nil { - return false, err - } - return false, m.redactHandledLink(ctx, tx, e) + if handled, err := m.dispatchBuiltin(ctx, tx, e); handled || err != nil { + return false, err } linked, err := store.Link(ctx, tx, e) if err != nil || linked { @@ -671,6 +711,29 @@ func (m *Module) dispatch(tx *sqlx.Tx, e store.Event) (bool, error) { return matched, nil } +func (m *Module) dispatchBuiltin(ctx context.Context, tx *sqlx.Tx, e store.Event) (bool, error) { + switch e.DeclaredEventType { + case changeApprovedType: + return true, m.settleChange(ctx, e, true) + case changeRejectedType: + return true, m.settleChange(ctx, e, false) + } + if e.Own { + // Archie's own message coming back starts nothing and proposes nothing. + return true, nil + } + switch e.DeclaredEventType { + case answerType: + return true, m.answer(ctx, e) + case linkType: + if err := m.link(ctx, e); err != nil { + return true, err + } + return true, m.redactHandledLink(ctx, tx, e) + } + return false, nil +} + // outcome is the result of evaluating a trigger against an event: notMatched // (its filter didn't match), noRun (it matched but started no run, and the // dispatch records why) or fired (a run started). diff --git a/modules/governance/accounts_api.go b/modules/governance/accounts_api.go index f05717b31..434156815 100644 --- a/modules/governance/accounts_api.go +++ b/modules/governance/accounts_api.go @@ -736,6 +736,10 @@ func (m *Module) finishOIDC(ctx context.Context, in *oidcCallbackInput) (*redire return nil, m.accountError(ctx, err) } m.log.InfoContext(ctx, "account signed in through the identity provider", "identity", value.ID) + m.recordAudit(ctx, AuditRecord{ + Category: "auth", Action: "auth.oidc.login", ActorID: string(value.ID), ActorKind: "user", + ResourceKind: "identity", ResourceID: string(value.ID), Outcome: "success", + }) return &redirectReply{ Location: "/", SetCookie: []http.Cookie{ @@ -810,6 +814,10 @@ func (m *Module) backchannelLogout(ctx context.Context, in *backchannelLogoutInp if err := m.RevokeSessionsBySubject(ctx, sub.Issuer, sub.Subject); err != nil { return nil, m.accountError(ctx, err) } + m.recordAudit(ctx, AuditRecord{ + Category: "auth", Action: "auth.oidc.backchannel_logout", ActorID: sub.Issuer + ":" + sub.Subject, ActorKind: "oidc", + ResourceKind: "session", ResourceID: sub.Issuer + ":" + sub.Subject, Outcome: "success", + }) return &backchannelLogoutReply{CacheControl: "no-store"}, nil } diff --git a/modules/governance/governance.go b/modules/governance/governance.go index e01d027ac..28550dac3 100644 --- a/modules/governance/governance.go +++ b/modules/governance/governance.go @@ -283,6 +283,18 @@ type WorkflowAliases interface { WorkflowsUsingModel(ctx context.Context, orgID, alias string) ([]string, error) } +// AuditRecord describes a security or policy audit event emitted by governance. +type AuditRecord struct { + Category string + Action string + ActorID string + ActorKind string + ResourceKind string + ResourceID string + Outcome string + Detail any +} + // Module serves one organisation's settings. type Module struct { orgID string @@ -294,6 +306,7 @@ type Module struct { oidc *oidcLogin setup *SetupSignal channels ChannelLinks + audit func(context.Context, AuditRecord) // workflows reports the saved workflows that name a model alias. workflows WorkflowAliases @@ -320,6 +333,15 @@ func (m *Module) UseSealer(s *seal.Sealer) { m.sealer = s } // writes are checked against. func (m *Module) UseAuthorizer(a Authorizer) { m.authorizer.Store(&a) } +// UseAudit registers a callback that receives security and policy audit events. +func (m *Module) UseAudit(fn func(context.Context, AuditRecord)) { m.audit = fn } + +func (m *Module) recordAudit(ctx context.Context, r AuditRecord) { + if m != nil && m.audit != nil { + m.audit(ctx, r) + } +} + // authz returns the policy chain, or nil before UseAuthorizer. func (m *Module) authz() Authorizer { if a := m.authorizer.Load(); a != nil { diff --git a/modules/governance/store_access.go b/modules/governance/store_access.go index b7f96a8bf..2e04416f5 100644 --- a/modules/governance/store_access.go +++ b/modules/governance/store_access.go @@ -97,7 +97,16 @@ func (m *Module) PutPolicy(ctx context.Context, p Policy) (int64, error) { }); err != nil { return 0, err } - return m.store.PutAccessPolicy(ctx, policyToRow(p)) + ver, err := m.store.PutAccessPolicy(ctx, policyToRow(p)) + if err != nil { + return 0, err + } + m.recordAudit(ctx, AuditRecord{ + Category: "policy", Action: "policy.access.update", ActorID: CallerID(ctx), + ResourceKind: "access_policy", ResourceID: p.ID, Outcome: "success", + Detail: map[string]any{"level": p.Level, "version": ver}, + }) + return ver, nil } // DeletePolicy removes one stored policy after verifying no org is locked out. @@ -121,6 +130,11 @@ func (m *Module) DeletePolicy(ctx context.Context, p Policy) error { if !found { return ErrPolicyNotFound } + m.recordAudit(ctx, AuditRecord{ + Category: "policy", Action: "policy.access.delete", ActorID: CallerID(ctx), + ResourceKind: "access_policy", ResourceID: p.ID, Outcome: "success", + Detail: map[string]any{"level": p.Level}, + }) return nil } diff --git a/modules/governance/store_identities.go b/modules/governance/store_identities.go index 1f096cf69..50e37a1aa 100644 --- a/modules/governance/store_identities.go +++ b/modules/governance/store_identities.go @@ -445,7 +445,7 @@ func (m *Module) SignInAccount(ctx context.Context, email, password string) (Acc now := time.Now().UTC() token := rand.Text() expires := sessionExpiry(now, settings.SessionMaxLifetimeS) - var breakGlassID string + var breakGlassID, refusedID string row, err := m.store.SignInAccount(ctx, email, sessionHash(token), expires, func(hash string) bool { if hash == "" { _, _ = HashPassword("unknown account dummy password") @@ -455,6 +455,7 @@ func (m *Module) SignInAccount(ctx context.Context, email, password string) (Acc }, func(identityID string, isOrgOwner bool) error { breakGlass, err := allowPasswordSignIn(settings.SSOOnly, isOrgOwner) if err != nil { + refusedID = identityID m.log.WarnContext(ctx, "password sign-in refused: sso_only enabled", "audit", true, "identity", identityID) return err } @@ -464,10 +465,26 @@ func (m *Module) SignInAccount(ctx context.Context, email, password string) (Acc return nil }) if err != nil { + if refusedID != "" { + m.recordAudit(ctx, AuditRecord{ + Category: "auth", Action: "auth.password.login", ActorID: refusedID, ActorKind: "user", + ResourceKind: "identity", ResourceID: refusedID, Outcome: "denied", + Detail: map[string]any{"reason": "sso_only"}, + }) + } return AccountSession{}, mapIdentityErr(err) } if breakGlassID != "" { m.log.WarnContext(ctx, "break-glass local password sign-in used while sso_only is enabled", "audit", true, "identity", breakGlassID) + m.recordAudit(ctx, AuditRecord{ + Category: "auth", Action: "auth.break_glass.login", ActorID: breakGlassID, ActorKind: "user", + ResourceKind: "identity", ResourceID: breakGlassID, Outcome: "success", + }) + } else { + m.recordAudit(ctx, AuditRecord{ + Category: "auth", Action: "auth.password.login", ActorID: row.ID, ActorKind: "user", + ResourceKind: "identity", ResourceID: row.ID, Outcome: "success", + }) } return AccountSession{Identity: identityFromRow(row), Token: token, Expires: expires}, nil } diff --git a/modules/judgement/policies.go b/modules/judgement/policies.go index fec1f7b1a..8883eb22b 100644 --- a/modules/judgement/policies.go +++ b/modules/judgement/policies.go @@ -1,6 +1,7 @@ package judgement import ( + "cmp" "context" _ "embed" // the starter policy sets "encoding/json/jsontext" @@ -22,6 +23,7 @@ import ( "github.com/jmoiron/sqlx" "github.com/samcharles93/archie-core/internal/platform/httpapi" + "github.com/samcharles93/archie-core/modules/audit" "github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/judgement/internal/store" @@ -61,6 +63,7 @@ type policyStore interface { type Policies struct { orgID string store policyStore + audit audit.Recorder log *slog.Logger now func() time.Time } @@ -70,6 +73,9 @@ func NewPolicies(db *sqlx.DB, log *slog.Logger, orgID string) *Policies { return &Policies{orgID: orgID, store: store.New(db), log: log, now: time.Now} } +// UseAudit configures the audit recorder notified on policy updates. +func (p *Policies) UseAudit(r audit.Recorder) { p.audit = r } + var starters = map[string]string{KindHardRules: starterHardRules, KindChangeRequest: starterChangeRequest} // current returns the version of a kind in force, seeding the starter set the @@ -374,9 +380,19 @@ func (p *Policies) Put(ctx context.Context, kind, body, by string) (PolicySetVie if _, err := p.current(ctx, kind); err != nil { return PolicySetView{}, err } - if _, err := p.store.AddPolicy(ctx, store.PolicySet{ID: uuid.New(), OrgID: p.orgID, Kind: kind, Body: body, CreatedBy: by}); err != nil { + saved, err := p.store.AddPolicy(ctx, store.PolicySet{ID: uuid.New(), OrgID: p.orgID, Kind: kind, Body: body, CreatedBy: by}) + if err != nil { return PolicySetView{}, err } + audit.Emit(ctx, p.audit, p.log, audit.Event{ + Category: "policy", + Action: "policy.judgement.update", + ActorID: cmp.Or(by, string(governance.SystemID)), + ResourceKind: "judgement_policy", + ResourceID: kind, + Outcome: "success", + Detail: map[string]any{"version": saved.Version}, + }) return p.View(ctx, kind, 0) } diff --git a/modules/system/system.go b/modules/system/system.go index feb8e60ac..90cca608f 100644 --- a/modules/system/system.go +++ b/modules/system/system.go @@ -16,6 +16,7 @@ import ( "github.com/samcharles93/archie-core/internal/platform/httpapi" "github.com/samcharles93/archie-core/internal/platform/httpjson" + "github.com/samcharles93/archie-core/modules/audit" "github.com/samcharles93/archie-core/modules/governance" ) @@ -36,6 +37,7 @@ type Module struct { bootstrap Bootstrap rotate func(hash string) error sources Sources + audit audit.Recorder log *slog.Logger } @@ -45,6 +47,9 @@ func New(b Bootstrap, rotate func(hash string) error, log *slog.Logger) *Module return &Module{bootstrap: b, rotate: rotate, log: log} } +// UseAudit configures the audit recorder notified on administrative actions. +func (m *Module) UseAudit(r audit.Recorder) { m.audit = r } + // Register adds the system API. func (m *Module) Register(api huma.API) { tags := []string{"System"} @@ -88,6 +93,14 @@ func (m *Module) rotateAdminToken(ctx context.Context, _ *struct{}) (*httpapi.Re m.bootstrap.AdminPrefix, m.bootstrap.AdminSet = hash[:8], true m.mu.Unlock() m.log.InfoContext(ctx, "admin token rotated", "audit", true, "action", "admin.token.rotate") + audit.Emit(ctx, m.audit, m.log, audit.Event{ + Category: "auth", + Action: "admin.token.rotate", + ActorID: governance.CallerID(ctx), + ResourceKind: "instance", + ResourceID: "admin_token", + Outcome: "success", + }) return httpapi.OK(adminToken{Token: token}), nil }