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.
This commit is contained in:
sam committed 2026-11-23 01:00:46 +11:00
1 parent e1ada94d78
commit 60d9b6b7aa
17 files changed
+291 -98

No files matched your search

+29 -16
View File
@@ -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:
+3 -3
View File
@@ -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} {
@@ -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;
+18 -1
View File
@@ -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"`
+13 -12
View File
@@ -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)
+106
View File
@@ -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)
}
})
}
}
+38 -28
View File
@@ -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
}
+1 -1
View File
@@ -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) {
+8 -4
View File
@@ -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 {
+17 -14
View File
@@ -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
+10 -4
View File
@@ -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,
+2 -2
View File
@@ -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",
+18 -5
View File
@@ -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<Denial>[] = [
{ 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());
<template>
<div>
<PageHeader title="Denials">
<PageHeader title="Access decisions">
<Button variant="outline" size="sm" :disabled="loading" @click="store.load()">Refresh</Button>
</PageHeader>
@@ -44,6 +46,14 @@ onMounted(() => void store.load());
<Input v-model="filters.principal" class="w-48" aria-label="Principal" placeholder="Principal" />
<Input v-model="filters.action" class="w-36" aria-label="Action" placeholder="Action" />
<Input v-model="filters.kind" class="w-36" aria-label="Resource kind" placeholder="Resource kind" />
<Select v-model="filters.outcome">
<SelectTrigger class="w-32" aria-label="Outcome"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="any">Any outcome</SelectItem>
<SelectItem value="allowed">Allowed</SelectItem>
<SelectItem value="denied">Denied</SelectItem>
</SelectContent>
</Select>
<Input v-model="filters.since" type="datetime-local" class="w-52" aria-label="From" />
<Input v-model="filters.until" type="datetime-local" class="w-52" aria-label="Until" />
<Button type="submit" size="sm" :disabled="loading">Filter</Button>
@@ -51,22 +61,25 @@ onMounted(() => void store.load());
</form>
<div class="flex flex-col gap-3">
<p v-if="loading && !denials.length" class="flex items-center gap-2 text-label text-fg-muted">
<Spinner />Loading denials…
<Spinner />Loading decisions…
</p>
<Empty v-else-if="!error && !denials.length">
<EmptyHeader><EmptyTitle>No denials recorded</EmptyTitle></EmptyHeader>
<EmptyHeader><EmptyTitle>No decisions recorded</EmptyTitle></EmptyHeader>
</Empty>
<DataTable
v-else-if="!error || denials.length"
:columns="columns"
:rows="denials"
:row-key="(d) => `${d.at}:${d.principal}:${d.action}:${d.kind}:${d.resource}`"
:row-key="(d) => `${d.at}:${d.principal}:${d.action}:${d.kind}:${d.resource}:${d.outcome}`"
storage-key="denials"
>
<template #empty>
<Empty><EmptyHeader><EmptyTitle>No denials recorded</EmptyTitle></EmptyHeader></Empty>
<Empty><EmptyHeader><EmptyTitle>No decisions recorded</EmptyTitle></EmptyHeader></Empty>
</template>
<template #cell-at="{ row }"><Timestamp :at="row.at" /></template>
<template #cell-outcome="{ row }">
<Badge :variant="row.outcome === 'allowed' ? 'ok' : 'danger'">{{ row.outcome === "allowed" ? "Allowed" : "Denied" }}</Badge>
</template>
<template #cell-action="{ row }"><span class="font-mono text-caption">{{ row.action }}</span></template>
<template #cell-principal="{ row }"><span class="font-mono text-caption">{{ row.principal }}</span></template>
<template #cell-resource="{ row }"><span class="font-mono text-caption">{{ denialResource(row) }}</span></template>
+4 -3
View File
@@ -1,11 +1,12 @@
/** Access denials as the dashboard reads them from /api/access/denials:
* one recorded refusal, coalesced per minute into a count. */
/** Access decisions as the dashboard reads them from /api/access/denials:
* one recorded outcome, coalesced per minute into a count. */
export interface Denial {
principal: string;
org: string;
action: string;
kind: string;
resource: string;
outcome: "allowed" | "denied";
level: string;
policies: string[];
at: string;
@@ -14,7 +15,7 @@ export interface Denial {
export interface DenialsResponse {
denials: Denial[];
/** Whether older refusals match beyond this page. */
/** Whether older decisions match beyond this page. */
more: boolean;
}
+1 -1
View File
@@ -1,6 +1,6 @@
export const stores = {
denials: {
unavailable: "Denial records are unavailable.",
unavailable: "Decision records are unavailable.",
},
settings: {
conflict: "Changed elsewhere. Latest values loaded.",
+2 -2
View File
@@ -285,9 +285,9 @@ export const routes: RouteRecordRaw[] = [
component: DenialsPage,
meta: {
section: "org_denials",
label: "Denials",
label: "Access decisions",
navPath: "/org",
description: "Access requests the policy chain refused, newest first.",
description: "Access requests the policy chain allowed or refused, newest first.",
},
},
{
+5 -2
View File
@@ -13,15 +13,17 @@ export interface DenialFilters {
principal: string;
action: string;
kind: string;
/** "any", or one outcome the server records. */
outcome: string;
since: string;
until: string;
}
const noFilters = (): DenialFilters => ({ principal: "", action: "", kind: "", since: "", until: "" });
const noFilters = (): DenialFilters => ({ principal: "", action: "", kind: "", outcome: "any", since: "", until: "" });
const toISO = (local: string): string => (local ? new Date(local).toISOString() : "");
/** The caller's org's recorded access denials, newest first, a page at a time. */
/** The caller's org's recorded access decisions, newest first, a page at a time. */
export const useDenialsStore = defineStore("denials", () => {
const denials = ref<Denial[]>([]);
const filters = reactive<DenialFilters>(noFilters());
@@ -40,6 +42,7 @@ export const useDenialsStore = defineStore("denials", () => {
principal: filters.principal.trim(),
action: filters.action.trim(),
kind: filters.kind.trim(),
outcome: filters.outcome === "any" ? "" : filters.outcome,
since: toISO(filters.since),
until: toISO(filters.until),
limit: PAGE,