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

+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,