From 60d9b6b7aa054567f09dc312ebb47fcdadcf6a86 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 23 Nov 2026 01:00:46 +1100 Subject: [PATCH] feat: record access decisions, not just denials - add an outcome column and migration so allowed and denied decisions share one audit trail - fail closed when an allowed decision cannot be recorded - expose outcome filtering in the API and dashboard Route chat through the recording authorizer so its decisions are audited too. --- api/openapi.yaml | 45 +++++--- internal/app/archie/operations.go | 6 +- .../00060_governance_access_decisions.sql | 16 +++ modules/governance/access.go | 19 +++- modules/governance/access_api.go | 25 +++-- modules/governance/decisions_test.go | 106 ++++++++++++++++++ modules/governance/enforce.go | 66 ++++++----- modules/governance/enforce_test.go | 2 +- modules/governance/engine.go | 12 +- modules/governance/internal/store/access.go | 31 ++--- modules/governance/store_access.go | 14 ++- ui/pages/pages.json | 4 +- ui/src/audit/DenialsPage.vue | 23 +++- ui/src/audit/denials.ts | 7 +- ui/src/copy/errors/stores.ts | 2 +- ui/src/router/routes.ts | 4 +- ui/src/stores/denials.ts | 7 +- 17 files changed, 291 insertions(+), 98 deletions(-) create mode 100644 internal/platform/pg/migrations/00060_governance_access_decisions.sql create mode 100644 modules/governance/decisions_test.go diff --git a/api/openapi.yaml b/api/openapi.yaml index f2a4b80c1..6c5608c28 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -1934,6 +1934,8 @@ components: type: string org: type: string + outcome: + type: string policies: items: type: string @@ -1950,6 +1952,7 @@ components: - action - kind - resource + - outcome - level - policies - at @@ -1965,7 +1968,7 @@ components: - array - "null" more: - description: Whether older refusals match beyond this page + description: Whether older decisions match beyond this page type: boolean required: - denials @@ -4219,61 +4222,71 @@ paths: get: operationId: list-access-denials parameters: - - description: Only refusals of this identity + - description: Only decisions about this identity explode: false in: query name: principal schema: - description: Only refusals of this identity + description: Only decisions about this identity type: string - - description: Only refusals of this action + - description: Only decisions about this action explode: false in: query name: action schema: - description: Only refusals of this action + description: Only decisions about this action type: string - - description: Only refusals on this resource kind + - description: Only decisions about this resource kind explode: false in: query name: kind schema: - description: Only refusals on this resource kind + description: Only decisions about this resource kind type: string - - description: Only refusals first recorded at or after this time + - description: "Only decisions with this outcome. Default: every outcome" + explode: false + in: query + name: outcome + schema: + description: "Only decisions with this outcome. Default: every outcome" + enum: + - allowed + - denied + type: string + - description: Only decisions first recorded at or after this time explode: false in: query name: since schema: - description: Only refusals first recorded at or after this time + description: Only decisions first recorded at or after this time format: date-time type: string - - description: Only refusals first recorded before this time + - description: Only decisions first recorded before this time explode: false in: query name: until schema: - description: Only refusals first recorded before this time + description: Only decisions first recorded before this time format: date-time type: string - - description: How many refusals to return + - description: How many decisions to return explode: false in: query name: limit schema: default: 100 - description: How many refusals to return + description: How many decisions to return format: int64 maximum: 1000 minimum: 1 type: integer - - description: How many of the newest matching refusals to skip + - description: How many of the newest matching decisions to skip explode: false in: query name: offset schema: default: 0 - description: How many of the newest matching refusals to skip + description: How many of the newest matching decisions to skip format: int64 minimum: 0 type: integer @@ -4290,7 +4303,7 @@ paths: schema: $ref: "#/components/schemas/ErrorModel" description: Error - summary: List the requests access policies refused + summary: List access policy decisions tags: - Access /api/access/policies: diff --git a/internal/app/archie/operations.go b/internal/app/archie/operations.go index a80c864be..982e3d782 100644 --- a/internal/app/archie/operations.go +++ b/internal/app/archie/operations.go @@ -59,8 +59,8 @@ func (o *operations) Start(ctx context.Context) error { if err != nil { return err } - // Every entry point asks the same chain, and each refusal is stored as a - // denial. + // Every entry point uses the same chain, and every decision, allowed or + // refused, is stored. checked := governance.Recording(access, o.settings, o.log.With("module", "governance")) // A workflow takes its context from the run handle, as a handler takes it // from the request. @@ -96,7 +96,7 @@ func (o *operations) Start(ctx context.Context) error { o.hear.UseDeliveryPolicy(governance.RecordingDelivery(access, o.settings, o.log.With("module", "governance"))) o.hear.UseTrustedProxies(o.settings.TrustedProxies) o.talk.Use(chat.Deps{ - People: o.settings, Access: access, Settings: o.settings, Toolbox: o.conns, Judge: o.judge, + People: o.settings, Access: checked, Settings: o.settings, Toolbox: o.conns, Judge: o.judge, Approver: o.allow, Memory: o.remember, Runs: o.engine, Notifier: o.tell, }) for _, loop := range []func(context.Context){o.engine.Work, o.hear.Work, o.tell.Work, o.talk.Work, o.retryDeletionRecord} { diff --git a/internal/platform/pg/migrations/00060_governance_access_decisions.sql b/internal/platform/pg/migrations/00060_governance_access_decisions.sql new file mode 100644 index 000000000..2df7678af --- /dev/null +++ b/internal/platform/pg/migrations/00060_governance_access_decisions.sql @@ -0,0 +1,16 @@ +-- +goose Up +-- The table that held refusals now holds every authorization decision. A row +-- records one outcome, coalesced per minute with identical requests, so rows +-- that exist already are refusals. +ALTER TABLE governance.access_denials + ADD COLUMN outcome text NOT NULL DEFAULT 'denied' CHECK (outcome IN ('allowed', 'denied')); +DROP INDEX governance.idx_governance_access_denials_dedup; +CREATE UNIQUE INDEX idx_governance_access_denials_dedup + ON governance.access_denials (org_id, principal, action, resource_kind, resource_id, outcome, level, policies, minute_at); + +-- +goose Down +DELETE FROM governance.access_denials WHERE outcome = 'allowed'; +DROP INDEX governance.idx_governance_access_denials_dedup; +CREATE UNIQUE INDEX idx_governance_access_denials_dedup + ON governance.access_denials (org_id, principal, action, resource_kind, resource_id, level, policies, minute_at); +ALTER TABLE governance.access_denials DROP COLUMN outcome; diff --git a/modules/governance/access.go b/modules/governance/access.go index 7cf1e7b99..ed4c84752 100644 --- a/modules/governance/access.go +++ b/modules/governance/access.go @@ -338,6 +338,11 @@ type Decision struct { // Allowed returns a permit decision. func Allowed() Decision { return Decision{Allowed: true} } +// AllowedAt returns a permit decision granted at level by the named policies. +func AllowedAt(level Level, policies []string) Decision { + return Decision{Allowed: true, Level: level, Policies: policies} +} + // Unavailable returns an availability refusal when the policy chain is not loaded. func Unavailable() Decision { return Decision{Level: LevelInstance, Err: ErrChainUnavailable} @@ -353,13 +358,25 @@ type PrincipalSource interface { PrincipalFor(context.Context, IdentityID) (Principal, error) } -// Denial is one recorded access refusal. +// Outcome is the result of an authorization decision. +type Outcome string + +// Decision outcomes. +const ( + OutcomeAllowed Outcome = "allowed" + OutcomeDenied Outcome = "denied" +) + +// Denial is one recorded authorization decision, allowed or denied according +// to Outcome: the principal, action, resource and deciding policies. It never +// holds request credentials. type Denial struct { Principal IdentityID `json:"principal"` Org OrgID `json:"org"` Action Action `json:"action"` Kind ResourceKind `json:"kind"` ResourceID string `json:"resource"` + Outcome Outcome `json:"outcome"` Level Level `json:"level"` Policies []string `json:"policies"` At time.Time `json:"at"` diff --git a/modules/governance/access_api.go b/modules/governance/access_api.go index 48d9c9a12..29b581450 100644 --- a/modules/governance/access_api.go +++ b/modules/governance/access_api.go @@ -21,12 +21,12 @@ type policyAdmin interface { DeletePolicy(context.Context, Policy) error } -// denialSearch reads the recorded refusals. +// denialSearch reads the recorded decisions. type denialSearch interface { SearchDenials(context.Context, DenialQuery) ([]Denial, error) } -// accessAPI serves the access policies and the record of refused requests. +// accessAPI serves the access policies and the record of decisions. type accessAPI struct { policies policyAdmin denials denialSearch @@ -51,18 +51,19 @@ type policyInput struct { } type denialsInput struct { - Principal string `query:"principal" doc:"Only refusals of this identity"` - Action string `query:"action" doc:"Only refusals of this action"` - Kind string `query:"kind" doc:"Only refusals on this resource kind"` - Since time.Time `query:"since" doc:"Only refusals first recorded at or after this time"` - Until time.Time `query:"until" doc:"Only refusals first recorded before this time"` - Limit int `query:"limit" default:"100" minimum:"1" maximum:"1000" doc:"How many refusals to return"` - Offset int `query:"offset" default:"0" minimum:"0" doc:"How many of the newest matching refusals to skip"` + Principal string `query:"principal" doc:"Only decisions about this identity"` + Action string `query:"action" doc:"Only decisions about this action"` + Kind string `query:"kind" doc:"Only decisions about this resource kind"` + Outcome string `query:"outcome" enum:"allowed,denied" doc:"Only decisions with this outcome. Default: every outcome"` + Since time.Time `query:"since" doc:"Only decisions first recorded at or after this time"` + Until time.Time `query:"until" doc:"Only decisions first recorded before this time"` + Limit int `query:"limit" default:"100" minimum:"1" maximum:"1000" doc:"How many decisions to return"` + Offset int `query:"offset" default:"0" minimum:"0" doc:"How many of the newest matching decisions to skip"` } type denialsBody struct { Denials []Denial `json:"denials"` - More bool `json:"more" doc:"Whether older refusals match beyond this page"` + More bool `json:"more" doc:"Whether older decisions match beyond this page"` } func (m *Module) registerPolicies(api huma.API, op func(id, method, path, summary string, status int) huma.Operation) { @@ -74,7 +75,7 @@ func (m *Module) registerPolicies(api huma.API, op func(id, method, path, summar func (m *Module) registerDenials(api huma.API, op func(id, method, path, summary string, status int) huma.Operation) { a := m.access() - httpapi.Register(api, httpapi.Authorized(ActionReadAudit, KindAudit), op("list-access-denials", http.MethodGet, "/api/access/denials", "List the requests access policies refused", 0), a.listDenials) + httpapi.Register(api, httpapi.Authorized(ActionReadAudit, KindAudit), op("list-access-denials", http.MethodGet, "/api/access/denials", "List access policy decisions", 0), a.listDenials) } func (a *accessAPI) listPolicies(ctx context.Context, _ *struct{}) (*httpapi.Reply[policiesBody], error) { @@ -150,7 +151,7 @@ func (a *accessAPI) listDenials(ctx context.Context, in *denialsInput) (*httpapi } found, err := a.denials.SearchDenials(ctx, DenialQuery{ Org: p.Org, Principal: IdentityID(in.Principal), Action: Action(in.Action), Kind: ResourceKind(in.Kind), - Since: in.Since, Until: in.Until, Limit: in.Limit + 1, Offset: in.Offset, + Outcome: Outcome(in.Outcome), Since: in.Since, Until: in.Until, Limit: in.Limit + 1, Offset: in.Offset, }) if err != nil { return nil, a.failed(ctx, "read the denials", err) diff --git a/modules/governance/decisions_test.go b/modules/governance/decisions_test.go new file mode 100644 index 000000000..0303898d5 --- /dev/null +++ b/modules/governance/decisions_test.go @@ -0,0 +1,106 @@ +package governance + +import ( + "context" + "encoding/json/v2" + "errors" + "log/slog" + "reflect" + "strings" + "testing" + "time" +) + +type fixedDelivery struct{ decision Decision } + +func (f fixedDelivery) AuthorizeDelivery(context.Context, OrgID, string, string) Decision { + return f.decision +} + +type fixedAuthorizer struct{ decision Decision } + +func (f fixedAuthorizer) Authorize(context.Context, Principal, Action, Resource, AccessContext) Decision { + return f.decision +} + +type brokenLog struct{} + +func (brokenLog) RecordDenial(context.Context, Denial) error { return errors.New("database down") } + +// TestEveryDecisionIsRecorded guards the audit trail: an allowed decision and a +// refused one are each stored with the principal, action, resource and deciding +// policies, whether the request came through the chain or the delivery +// check. The request's signature is a credential and is never stored. +func TestEveryDecisionIsRecorded(t *testing.T) { + const signature = "sha256=feedface" + quiet := slog.New(slog.DiscardHandler) + workflow := Resource{Kind: KindWorkflow, ID: "triage", Org: DefaultOrgID} + ask := func(ctx context.Context, d Decision, rec DenialRecorder) { + Recording(fixedAuthorizer{d}, rec, quiet).Authorize(ctx, SharedTokenOwner(), ActionRun, workflow, AccessContext{Signature: signature}) + } + deliver := func(ctx context.Context, d Decision, rec DenialRecorder) { + RecordingDelivery(fixedDelivery{d}, rec, quiet).AuthorizeDelivery(ctx, DefaultOrgID, "alerts", "203.0.113.9") + } + chain := Denial{Principal: SystemID, Org: DefaultOrgID, Action: ActionRun, Kind: KindWorkflow, ResourceID: "triage", Level: LevelOrg} + delivery := Denial{Principal: SenderID, Org: DefaultOrgID, Action: ActionDeliver, Kind: KindSource, ResourceID: "alerts", Level: LevelInstance} + with := func(d Denial, outcome Outcome, policy string) Denial { + d.Outcome, d.Policies = outcome, []string{policy} + return d + } + tests := []struct { + name string + run func(context.Context, Decision, DenialRecorder) + in Decision + want Denial + }{ + {"an allowed request", ask, AllowedAt(LevelOrg, []string{"org-owner"}), with(chain, OutcomeAllowed, "org-owner")}, + {"a refused request", ask, DeniedAt(LevelOrg, []string{"org-viewer"}), with(chain, OutcomeDenied, "org-viewer")}, + {"an allowed delivery", deliver, AllowedAt(LevelInstance, []string{"deliver-any"}), with(delivery, OutcomeAllowed, "deliver-any")}, + {"a refused delivery", deliver, DeniedAt(LevelInstance, []string{"deliver-none"}), with(delivery, OutcomeDenied, "deliver-none")}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + log := &denialLog{} + tt.run(t.Context(), tt.in, log) + if len(log.recorded) != 1 { + t.Fatalf("records = %d, want 1", len(log.recorded)) + } + got := log.recorded[0] + stored, err := json.Marshal(got) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(stored), signature) { + t.Fatalf("record %s holds the request signature", stored) + } + got.At, got.Count = time.Time{}, 0 + if !reflect.DeepEqual(got, tt.want) { + t.Fatalf("recorded %+v, want %+v", got, tt.want) + } + }) + } +} + +// TestAllowedDecisionNeedsItsRecord guards the audit guarantee: a request the +// chain allowed is refused as unavailable when its record cannot be written, +// while a refusal stays a refusal. +func TestAllowedDecisionNeedsItsRecord(t *testing.T) { + tests := []struct { + name string + in Decision + allowed bool + wantErr error + }{ + {name: "an allowed request", in: AllowedAt(LevelOrg, []string{"org-owner"}), wantErr: ErrChainUnavailable}, + {name: "a refused request", in: DeniedAt(LevelOrg, nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + a := Recording(fixedAuthorizer{tt.in}, brokenLog{}, slog.New(slog.DiscardHandler)) + d := a.Authorize(t.Context(), SharedTokenOwner(), ActionRun, Resource{Kind: KindWorkflow, Org: DefaultOrgID}, AccessContext{}) + if d.Allowed != tt.allowed || !errors.Is(d.Err, tt.wantErr) { + t.Fatalf("decision = %+v, want allowed %v, error %v", d, tt.allowed, tt.wantErr) + } + }) + } +} diff --git a/modules/governance/enforce.go b/modules/governance/enforce.go index bf33c8f47..c00d75f15 100644 --- a/modules/governance/enforce.go +++ b/modules/governance/enforce.go @@ -55,28 +55,45 @@ func RequireWorkload(ctx context.Context, a Authorizer, action Action, r Resourc type recording struct { Authorizer - denials DenialRecorder + records DenialRecorder log *slog.Logger } -// Recording wraps a so every refusal is stored as a denial, whichever entry -// point asked. A decision that could not be made is not a denial and is not -// stored. -func Recording(a Authorizer, denials DenialRecorder, log *slog.Logger) Authorizer { - return recording{Authorizer: a, denials: denials, log: log} +// Recording wraps a so every decision is stored with its outcome, regardless +// of the entry point. A decision that could not be made is not recorded. +// +// An allowed decision whose record cannot be written is returned as +// ErrChainUnavailable: access that leaves no trace is not granted. A refusal +// stays a refusal when its record fails, and the failure is logged. +func Recording(a Authorizer, records DenialRecorder, log *slog.Logger) Authorizer { + return recording{Authorizer: a, records: records, log: log} } func (r recording) Authorize(ctx context.Context, p Principal, action Action, res Resource, c AccessContext) Decision { d := r.Authorizer.Authorize(ctx, p, action, res, c) - if d.Allowed || errors.Is(d.Err, ErrChainUnavailable) { + return recordDecision(ctx, r.records, r.log, d, Denial{ + Principal: p.IdentityID, Org: p.Org, Action: action, Kind: res.Kind, ResourceID: res.ID, + }) +} + +// recordDecision stores d as the outcome of the request described by rec and +// returns the decision the caller may act on. +func recordDecision(ctx context.Context, records DenialRecorder, log *slog.Logger, d Decision, rec Denial) Decision { + if errors.Is(d.Err, ErrChainUnavailable) { return d } - err := r.denials.RecordDenial(context.WithoutCancel(ctx), Denial{ - Principal: p.IdentityID, Org: p.Org, Action: action, Kind: res.Kind, ResourceID: res.ID, - Level: d.Level, Policies: d.Policies, At: time.Now(), Count: 1, - }) - if err != nil { - r.log.ErrorContext(ctx, "record access denial", "principal", p.IdentityID, "action", action, "kind", res.Kind, "error", err) + rec.Outcome = OutcomeDenied + if d.Allowed { + rec.Outcome = OutcomeAllowed + } + rec.Level, rec.Policies, rec.At, rec.Count = d.Level, d.Policies, time.Now(), 1 + err := records.RecordDenial(context.WithoutCancel(ctx), rec) + if err == nil { + return d + } + log.ErrorContext(ctx, "record access decision", "principal", rec.Principal, "action", rec.Action, "kind", rec.Kind, "outcome", rec.Outcome, "error", err) + if d.Allowed { + return Decision{Level: d.Level, Policies: d.Policies, Err: ErrChainUnavailable} } return d } @@ -114,28 +131,21 @@ func (m *Module) mayUse(ctx context.Context, p Principal, action Action, kind Re type recordingDelivery struct { DeliveryAuthorizer - denials DenialRecorder + records DenialRecorder log *slog.Logger } -// RecordingDelivery wraps a so that every denied delivery is stored as a -// denial, for webhook and listener intake alike. An unavailable decision is -// not a denial and is not stored. -func RecordingDelivery(a DeliveryAuthorizer, denials DenialRecorder, log *slog.Logger) DeliveryAuthorizer { - return recordingDelivery{DeliveryAuthorizer: a, denials: denials, log: log} +// RecordingDelivery wraps a so that every delivery decision is stored with its +// outcome, for webhook and listener intake alike. An allowed delivery whose +// record cannot be written is returned as ErrChainUnavailable, as Recording +// does. +func RecordingDelivery(a DeliveryAuthorizer, records DenialRecorder, log *slog.Logger) DeliveryAuthorizer { + return recordingDelivery{DeliveryAuthorizer: a, records: records, log: log} } func (r recordingDelivery) AuthorizeDelivery(ctx context.Context, orgID OrgID, sourcePath, addr string) Decision { d := r.DeliveryAuthorizer.AuthorizeDelivery(ctx, orgID, sourcePath, addr) - if d.Allowed || errors.Is(d.Err, ErrChainUnavailable) { - return d - } - err := r.denials.RecordDenial(context.WithoutCancel(ctx), Denial{ + return recordDecision(ctx, r.records, r.log, d, Denial{ Principal: SenderID, Org: orgID, Action: ActionDeliver, Kind: KindSource, ResourceID: sourcePath, - Level: d.Level, Policies: d.Policies, At: time.Now(), Count: 1, }) - if err != nil { - r.log.ErrorContext(ctx, "record delivery denial", "source", sourcePath, "error", err) - } - return d } diff --git a/modules/governance/enforce_test.go b/modules/governance/enforce_test.go index 32dbec818..b3cf7f6f7 100644 --- a/modules/governance/enforce_test.go +++ b/modules/governance/enforce_test.go @@ -82,7 +82,7 @@ func TestEnforcementFailsClosedAndRecordsRefusals(t *testing.T) { {name: "a chain that is not loaded", authorizer: pending, who: admin, wantErr: ErrChainUnavailable, wantHTTPDeny: httpapi.ErrUnavailable}, {name: "no authorizer", authorizer: nil, who: admin, wantErr: ErrChainUnavailable, wantHTTPDeny: httpapi.ErrUnavailable}, {name: "a refusal", authorizer: loaded, who: viewer, wantErr: ErrDenied, wantDenials: 1, wantHTTPDeny: httpapi.ErrDenied}, - {name: "a grant", authorizer: loaded, who: admin}, + {name: "a grant", authorizer: loaded, who: admin, wantDenials: 1}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/modules/governance/engine.go b/modules/governance/engine.go index 7a27d9a4d..045ea89b1 100644 --- a/modules/governance/engine.go +++ b/modules/governance/engine.go @@ -204,6 +204,7 @@ func (e *Engine) AuthorizeDelivery(_ context.Context, orgID OrgID, sourcePath, a } func evaluate(levels []*levelSet, entities types.EntityMap, request types.Request) Decision { + var granted Decision for _, lvl := range levels { if !lvl.active() { continue @@ -214,19 +215,22 @@ func evaluate(levels []*levelSet, entities types.EntityMap, request types.Reques return decision } decision, diag := cedar.Authorize(lvl.set, entities, request) - if decision == cedar.Allow { - continue - } ids := make([]string, 0, len(diag.Reasons)) for _, reason := range diag.Reasons { ids = append(ids, string(reason.PolicyID)) } + if decision == cedar.Allow { + granted.Level = lvl.at + granted.Policies = append(granted.Policies, ids...) + continue + } if len(ids) == 0 { ids = lvl.ids } return DeniedAt(lvl.at, ids) } - return Allowed() + granted.Allowed = true + return granted } func (e *Engine) chain(p Principal, r Resource) []*levelSet { diff --git a/modules/governance/internal/store/access.go b/modules/governance/internal/store/access.go index 13d042986..daf07d871 100644 --- a/modules/governance/internal/store/access.go +++ b/modules/governance/internal/store/access.go @@ -57,7 +57,7 @@ type PolicyRow struct { UpdatedAt time.Time `db:"updated_at"` } -// DenialRow is a coalesced access refusal in governance.access_denials. +// DenialRow is a coalesced authorization decision in governance.access_denials. type DenialRow struct { ID int64 `db:"id"` OrgID string `db:"org_id"` @@ -65,6 +65,7 @@ type DenialRow struct { Action string `db:"action"` ResourceKind string `db:"resource_kind"` ResourceID string `db:"resource_id"` + Outcome string `db:"outcome"` Level string `db:"level"` Policies []string `db:"policies"` MinuteAt time.Time `db:"minute_at"` @@ -278,28 +279,28 @@ func (s *Store) ResetInstancePolicies(ctx context.Context) error { }) } -// RecordDenial stores or increments a per-minute coalesced access refusal. +// RecordDenial stores or increments a per-minute coalesced access decision. func (s *Store) RecordDenial(ctx context.Context, d DenialRow) error { policies := d.Policies if policies == nil { policies = []string{} } if _, err := s.db.ExecContext(ctx, ` - INSERT INTO governance.access_denials (org_id, principal, action, resource_kind, resource_id, level, policies) - VALUES ($1, $2, $3, $4, $5, $6, $7) - ON CONFLICT (org_id, principal, action, resource_kind, resource_id, level, policies, minute_at) + INSERT INTO governance.access_denials (org_id, principal, action, resource_kind, resource_id, outcome, level, policies) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + ON CONFLICT (org_id, principal, action, resource_kind, resource_id, outcome, level, policies, minute_at) DO UPDATE SET count = governance.access_denials.count + 1, updated_at = now()`, - d.OrgID, d.Principal, d.Action, d.ResourceKind, d.ResourceID, d.Level, policies); err != nil { + d.OrgID, d.Principal, d.Action, d.ResourceKind, d.ResourceID, d.Outcome, d.Level, policies); err != nil { return fmt.Errorf("record denial: %w", err) } return nil } -// ListDenials returns an org's most recent denials, newest first. +// ListDenials returns an org's most recent decisions, newest first. func (s *Store) ListDenials(ctx context.Context, orgID string, limit int) ([]DenialRow, error) { var out []DenialRow if err := s.db.SelectContext(ctx, &out, ` - SELECT id, org_id, principal, action, resource_kind, resource_id, level, policies, minute_at, count, created_at, updated_at + SELECT id, org_id, principal, action, resource_kind, resource_id, outcome, level, policies, minute_at, count, created_at, updated_at FROM governance.access_denials WHERE org_id = $1 ORDER BY id DESC LIMIT $2`, orgID, limit); err != nil { return nil, fmt.Errorf("list denials: %w", err) } @@ -312,25 +313,27 @@ type DenialFilter struct { Principal string Action string ResourceKind string + Outcome string Since, Until time.Time Limit int Offset int } -// SearchDenials returns an org's denials matching f, newest first. +// SearchDenials returns an org's decisions matching f, newest first. func (s *Store) SearchDenials(ctx context.Context, f DenialFilter) ([]DenialRow, error) { var out []DenialRow if err := s.db.SelectContext(ctx, &out, ` - SELECT id, org_id, principal, action, resource_kind, resource_id, level, policies, minute_at, count, created_at, updated_at + SELECT id, org_id, principal, action, resource_kind, resource_id, outcome, level, policies, minute_at, count, created_at, updated_at FROM governance.access_denials WHERE org_id = $1 AND ($2 = '' OR principal = $2) AND ($3 = '' OR action = $3) AND ($4 = '' OR resource_kind = $4) - AND ($5::timestamptz IS NULL OR created_at >= $5) - AND ($6::timestamptz IS NULL OR created_at < $6) - ORDER BY id DESC LIMIT $7 OFFSET $8`, - f.OrgID, f.Principal, f.Action, f.ResourceKind, nullTime(f.Since), nullTime(f.Until), f.Limit, f.Offset); err != nil { + AND ($5 = '' OR outcome = $5) + AND ($6::timestamptz IS NULL OR created_at >= $6) + AND ($7::timestamptz IS NULL OR created_at < $7) + ORDER BY id DESC LIMIT $8 OFFSET $9`, + f.OrgID, f.Principal, f.Action, f.ResourceKind, f.Outcome, nullTime(f.Since), nullTime(f.Until), f.Limit, f.Offset); err != nil { return nil, fmt.Errorf("search denials: %w", err) } return out, nil diff --git a/modules/governance/store_access.go b/modules/governance/store_access.go index 99f7cbd43..4aa06a28c 100644 --- a/modules/governance/store_access.go +++ b/modules/governance/store_access.go @@ -268,23 +268,27 @@ func (m *Module) ResetInstancePolicies(ctx context.Context) error { return m.store.ResetInstancePolicies(ctx) } -// RecordDenial persists one coalesced access denial. +// RecordDenial persists one coalesced access decision, allowed or denied. func (m *Module) RecordDenial(ctx context.Context, d Denial) error { if d.Org == "" || d.Principal == "" { return fmt.Errorf("%w: org and principal are required", ErrInvalidPolicy) } + if d.Outcome != OutcomeAllowed && d.Outcome != OutcomeDenied { + return fmt.Errorf("%w: unknown outcome %q", ErrInvalidPolicy, d.Outcome) + } return m.store.RecordDenial(ctx, store.DenialRow{ OrgID: string(d.Org), Principal: string(d.Principal), Action: string(d.Action), ResourceKind: string(d.Kind), ResourceID: d.ResourceID, + Outcome: string(d.Outcome), Level: string(d.Level), Policies: d.Policies, }) } -// ListDenials returns an org's most recent denials, newest first. +// ListDenials returns an org's most recent decisions, newest first. func (m *Module) ListDenials(ctx context.Context, orgID OrgID, limit int) ([]Denial, error) { return m.SearchDenials(ctx, DenialQuery{Org: orgID, Limit: limit}) } @@ -295,13 +299,14 @@ type DenialQuery struct { Principal IdentityID Action Action Kind ResourceKind + Outcome Outcome Since time.Time Until time.Time Limit int Offset int } -// SearchDenials returns the denials matching q, newest first, at most +// SearchDenials returns the decisions matching q, newest first, at most // maxDenials per call. func (m *Module) SearchDenials(ctx context.Context, q DenialQuery) ([]Denial, error) { if q.Limit <= 0 { @@ -311,7 +316,7 @@ func (m *Module) SearchDenials(ctx context.Context, q DenialQuery) ([]Denial, er } rows, err := m.store.SearchDenials(ctx, store.DenialFilter{ OrgID: string(q.Org), Principal: string(q.Principal), Action: string(q.Action), - ResourceKind: string(q.Kind), Since: q.Since, Until: q.Until, Limit: q.Limit, Offset: max(q.Offset, 0), + ResourceKind: string(q.Kind), Outcome: string(q.Outcome), Since: q.Since, Until: q.Until, Limit: q.Limit, Offset: max(q.Offset, 0), }) if err != nil { return nil, err @@ -328,6 +333,7 @@ func denialsFromRows(rows []store.DenialRow) []Denial { Action: Action(r.Action), Kind: ResourceKind(r.ResourceKind), ResourceID: r.ResourceID, + Outcome: Outcome(r.Outcome), Level: Level(r.Level), Policies: r.Policies, At: r.CreatedAt, diff --git a/ui/pages/pages.json b/ui/pages/pages.json index 50c77190e..d5ece0537 100644 --- a/ui/pages/pages.json +++ b/ui/pages/pages.json @@ -111,8 +111,8 @@ }, { "path": "/org/denials", - "label": "Denials", - "description": "Access requests the policy chain refused, newest first." + "label": "Access decisions", + "description": "Access requests the policy chain allowed or refused, newest first." }, { "path": "/org/workspaces", diff --git a/ui/src/audit/DenialsPage.vue b/ui/src/audit/DenialsPage.vue index ad9303b88..69a5e3284 100644 --- a/ui/src/audit/DenialsPage.vue +++ b/ui/src/audit/DenialsPage.vue @@ -9,6 +9,7 @@ import { Button } from "@/components/ui/button"; import { DataTable, type DataTableColumn } from "@/components/ui/data-table"; import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty"; import { Input } from "@/components/ui/input"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Section } from "@/components/ui/section"; import { Spinner } from "@/components/ui/spinner"; import { Timestamp } from "@/components/ui/timestamp"; @@ -21,6 +22,7 @@ const { denials, filters, more, loading, error } = storeToRefs(store); const columns: DataTableColumn[] = [ { id: "at", label: "When", fixed: true, width: "9rem", sort: (d) => d.at }, { id: "principal", label: "Principal", fixed: true, width: "auto", class: "whitespace-normal" }, + { id: "outcome", label: "Outcome", width: "7rem" }, { id: "action", label: "Action", width: "12rem" }, { id: "resource", label: "Resource", width: "14rem", class: "whitespace-normal" }, { id: "level", label: "Level", width: "6rem" }, @@ -33,7 +35,7 @@ onMounted(() => void store.load());