feat(state): unified org-scoped audit feed and AuditService

This commit is contained in:
sam committed 2026-10-25 21:37:56 +11:00
commit e2f9388071
26 files changed
+3450 -20

No files matched your search

+1 -1
View File
@@ -101,7 +101,7 @@ func writeAccount(ctx context.Context, tx pgx.Tx, r identity.AccountRegistration
if p, ok := access.PrincipalFromContext(ctx); ok {
actor = p.IdentityID
}
err = insertIdentityEvent(ctx, postgresdb.New(tx), id, identity.Event{Type: "create", To: identity.LifecycleActive, DisplayName: r.DisplayName}, identity.Audit{ActorID: actor, Source: "accounts", RequestID: "account:" + rand.Text()}, now)
err = insertIdentityEventInOrg(ctx, postgresdb.New(tx), orgID, id, identity.Event{Type: "create", To: identity.LifecycleActive, DisplayName: r.DisplayName}, identity.Audit{ActorID: actor, Source: "accounts", RequestID: "account:" + rand.Text()}, now)
if err != nil {
return identity.Identity{}, err
}
@@ -0,0 +1,201 @@
// Audit feed: the read model over every durable trail the State Store owns,
// mapped into internal/domain/audit's row shape. Every entry is redacted here,
// before it crosses the gRPC boundary; undecodable JSON is dropped rather than
// passed through.
package postgres
import (
"cmp"
"context"
"encoding/json"
"fmt"
"slices"
"time"
"github.com/jackc/pgx/v5/pgtype"
"github.com/samcharles93/archie-core/internal/domain/audit"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
"github.com/samcharles93/archie-core/internal/webhookguard"
)
var _ audit.Store = (*Store)(nil)
// auditFieldJSON is one field of a change set on the wire: two JSON values,
// either of which is null when that side of the change is absent.
type auditFieldJSON struct {
Old json.RawMessage `json:"old"`
New json.RawMessage `json:"new"`
}
// ListAudit returns one org-scoped page of the feed. The org comes from the
// request context; a request that names no org reads the system org, which is
// the org an unattributed call acts in.
func (s *Store) ListAudit(ctx context.Context, filter audit.Filter, cursor audit.Cursor, limit int) (audit.Page, error) {
if err := filter.Normalize(); err != nil {
return audit.Page{}, err
}
limit = audit.NormalizeLimit(limit)
orgID := org.DefaultOrgID
if scoped, ok := org.Scope(ctx); ok {
orgID = scoped
}
rows, err := s.queries().ListAudit(ctx, postgresdb.ListAuditParams{
PageLimit: int64(limit + 1),
OrgID: string(orgID),
InstanceAdmin: audit.InstanceAdmin(ctx),
Categories: filter.Categories,
FromAt: auditTime(filter.From),
ToAt: auditTime(filter.To),
Actor: auditText(filter.Actor),
Actions: filter.Actions,
Kinds: filter.Kinds,
TargetKinds: filter.TargetKinds,
TargetIds: filter.TargetIDs,
Severities: filter.Severities,
Outcomes: filter.Outcomes,
Q: auditText(filter.Query),
CursorAt: auditTime(cursor.At),
CursorRank: int32(cursor.Rank),
CursorID: cursor.ID,
})
if err != nil {
return audit.Page{}, fmt.Errorf("list audit: %w", err)
}
page := audit.Page{}
if len(rows) > limit {
page.HasMore = true
rows = rows[:limit]
}
page.Entries = make([]audit.Entry, len(rows))
for i := range rows {
page.Entries[i] = auditEntry(rows[i])
}
if page.HasMore {
last := page.Entries[len(page.Entries)-1]
page.NextCursor = audit.Cursor{
At: last.At, Rank: last.Rank, ID: last.SourceID, FilterHash: filter.Hash(),
}.Encode()
}
return page, nil
}
// AuditHead returns the cheap change token: the newest id of each trail the
// caller can read, and the denial count sum because a coalesced denial bumps
// its count in place without drawing a new id.
func (s *Store) AuditHead(ctx context.Context) (string, error) {
orgID := org.DefaultOrgID
if scoped, ok := org.Scope(ctx); ok {
orgID = scoped
}
row, err := s.queries().AuditHead(ctx, postgresdb.AuditHeadParams{
OrgID: string(orgID),
InstanceAdmin: audit.InstanceAdmin(ctx),
})
if err != nil {
return "", fmt.Errorf("audit head: %w", err)
}
return fmt.Sprintf("%d:%d:%d:%d:%d",
row.SysAuditID, row.IdentityEventID, row.AccessDenialID, row.AccessDenialCount, row.EventID), nil
}
func auditTime(t time.Time) pgtype.Timestamptz {
if t.IsZero() {
return pgtype.Timestamptz{}
}
return pgtype.Timestamptz{Time: t, Valid: true}
}
func auditText(value string) pgtype.Text {
if value == "" {
return pgtype.Text{}
}
return pgtype.Text{String: value, Valid: true}
}
// auditEntry maps one read-model row to the domain entry, redacting every
// free-form part. A field list or data document that cannot be decoded is
// dropped, never forwarded unredacted.
func auditEntry(row postgresdb.ListAuditRow) audit.Entry {
return audit.Entry{
Rank: int(row.SourceRank),
SourceID: row.SourceID,
Category: audit.Category(row.Category),
At: row.At,
Actor: row.Actor,
ActorKind: row.ActorKind,
PrincipalID: row.PrincipalID,
TargetKind: row.TargetKind,
TargetID: row.TargetID,
Kind: row.Kind,
RecordVersion: row.RecordVersion,
RequestID: row.RequestID,
Source: row.Source,
Fields: redactedFields(row.Fields),
Action: row.Action,
Severity: audit.Severity(row.Severity),
Outcome: audit.Outcome(row.Outcome),
Detail: webhookguard.RedactString(row.Detail),
WorkspaceID: row.WorkspaceID,
TaskID: row.TaskID,
Data: redactedData(row.DataText),
}
}
// redactedFields decodes the change set's fields object, redacts each side
// under its own field name, and returns them sorted for a stable view.
func redactedFields(encoded []byte) []audit.Field {
if len(encoded) == 0 {
return nil
}
var raw map[string]auditFieldJSON
if err := json.Unmarshal(encoded, &raw); err != nil {
return nil
}
fields := make([]audit.Field, 0, len(raw))
for name, side := range raw {
fields = append(fields, audit.Field{
Name: name,
Old: redactFieldValue(name, side.Old),
New: redactFieldValue(name, side.New),
})
}
slices.SortFunc(fields, func(a, b audit.Field) int { return cmp.Compare(a.Name, b.Name) })
return fields
}
// redactFieldValue redacts one side of one field. Wrapping it under the field
// name lets the existing redactor apply both its key and value rules, so a
// secret reference survives as a hidden value while the field name stays.
func redactFieldValue(name string, value json.RawMessage) json.RawMessage {
if len(value) == 0 || string(value) == "null" {
return value
}
wrapped, err := json.Marshal(map[string]json.RawMessage{name: value})
if err != nil {
return nil
}
redacted, err := webhookguard.RedactPayload(wrapped)
if err != nil {
return nil
}
var out map[string]json.RawMessage
if err := json.Unmarshal(redacted, &out); err != nil {
return nil
}
return out[name]
}
// redactedData redacts an event's data document, dropping one that cannot be
// decoded. An empty document is absent rather than an empty object.
func redactedData(text string) json.RawMessage {
if text == "" || text == "{}" {
return nil
}
redacted, err := webhookguard.RedactPayload([]byte(text))
if err != nil {
return nil
}
return redacted
}
@@ -0,0 +1,127 @@
package postgres
import (
"encoding/json"
"testing"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
const testJWT = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzYW0ifQ.c2lnbmF0dXJl"
// TestRedactedFields pins the read-time redaction policy: a value under a
// sensitive field name, or one shaped like an unambiguous secret, never
// leaves the adapter; null and absent sides survive; and undecodable JSON
// drops the list instead of passing it through.
func TestRedactedFields(t *testing.T) {
t.Parallel()
tests := []struct {
name string
encoded string
want map[string][2]string
}{
{
name: "secret-reference field is redacted on both sides",
encoded: `{"webhook_secret":{"old":"vault://old","new":"vault://new"}}`,
want: map[string][2]string{"webhook_secret": {`"[redacted]"`, `"[redacted]"`}},
},
{
name: "nested token under a benign field name is redacted",
encoded: `{"settings":{"old":{"bot_token":"abc"},"new":{"bot_token":"def"}}}`,
want: map[string][2]string{"settings": {`{"bot_token":"[redacted]"}`, `{"bot_token":"[redacted]"}`}},
},
{
name: "jwt under a benign field name is redacted by shape",
encoded: `{"webhook":{"old":"` + testJWT + `","new":"` + testJWT + `"}}`,
want: map[string][2]string{"webhook": {`"[redacted]"`, `"[redacted]"`}},
},
{
name: "jwt embedded in a JSON string value is redacted",
encoded: `{"error":{"old":"auth failed for ` + testJWT + `","new":"ok"}}`,
want: map[string][2]string{"error": {`"[redacted]"`, `"ok"`}},
},
{
name: "pem private key is redacted by shape",
encoded: `{"certificate":{"old":"-----BEGIN PRIVATE KEY-----\nsecret\n-----END PRIVATE KEY-----","new":"kept"}}`,
want: map[string][2]string{"certificate": {`"[redacted]"`, `"kept"`}},
},
{
name: "whole-document array row is redacted recursively",
encoded: `{"":{"old":[{"name":"visible","password":"hidden"}],"new":null}}`,
want: map[string][2]string{"": {`[{"name":"visible","password":"[redacted]"}]`, `null`}},
},
{
name: "null and absent sides survive",
encoded: `{"new_field":{"old":null,"new":"on"}}`,
want: map[string][2]string{"new_field": {`null`, `"on"`}},
},
{
name: "non-secret values are unchanged",
encoded: `{"enabled":{"old":false,"new":true}}`,
want: map[string][2]string{"enabled": {`false`, `true`}},
},
{
name: "malformed json drops the list",
encoded: `{"enabled":`,
want: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
fields := redactedFields([]byte(tt.encoded))
if tt.want == nil {
if fields != nil {
t.Fatalf("redactedFields() = %+v, want nil", fields)
}
return
}
if len(fields) != len(tt.want) {
t.Fatalf("redactedFields() = %+v, want %d fields", fields, len(tt.want))
}
for _, field := range fields {
want, ok := tt.want[field.Name]
if !ok {
t.Fatalf("unexpected field %q", field.Name)
}
if string(field.Old) != want[0] || string(field.New) != want[1] {
t.Fatalf("field %q = %s/%s, want %s/%s", field.Name, field.Old, field.New, want[0], want[1])
}
}
})
}
}
func TestRedactedData(t *testing.T) {
t.Parallel()
redacted := redactedData(`{"token":"abc","visible":true}`)
var value map[string]any
if err := json.Unmarshal(redacted, &value); err != nil {
t.Fatalf("redactedData() = %q, not JSON: %v", redacted, err)
}
if value["token"] != "[redacted]" || value["visible"] != true {
t.Fatalf("redactedData() = %v, want the token redacted and visible kept", value)
}
embedded := redactedData(`{"error":"auth failed for ` + testJWT + `"}`)
var nested map[string]any
if err := json.Unmarshal(embedded, &nested); err != nil {
t.Fatalf("redactedData(embedded jwt) = %q, not JSON: %v", embedded, err)
}
if nested["error"] != "[redacted]" {
t.Fatalf("redactedData(embedded jwt) = %v, want the whole value redacted", nested)
}
if got := redactedData(`{"broken":`); got != nil {
t.Fatalf("redactedData(malformed) = %q, want nil", got)
}
if got := redactedData("{}"); got != nil {
t.Fatalf("redactedData(empty object) = %q, want nil", got)
}
}
func TestAuditEntryRedactsDetail(t *testing.T) {
t.Parallel()
entry := auditEntry(postgresdb.ListAuditRow{Detail: "issued " + testJWT})
if entry.Detail != "[redacted]" {
t.Fatalf("entry detail = %q, want the whole value redacted", entry.Detail)
}
}
+50 -8
View File
@@ -8,6 +8,7 @@ import (
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
@@ -23,17 +24,58 @@ func identityFromRow(i postgresdb.Identity) identity.Identity {
}
}
// insertIdentityEvent writes one identity audit event through q, refusing an
// audit that cannot answer who acted and whose authority they used.
func insertIdentityEvent(ctx context.Context, q *postgresdb.Queries, id identity.IdentityID, ev identity.Event, audit identity.Audit, at time.Time) error {
// insertIdentityEvent writes one identity audit event under the subject's own
// org, not the actor's: an org-sys operator suspending an org A member must
// not file that event under org-sys. fallback is used when the identity has no
// org yet, as on a create that has not been assigned one.
func insertIdentityEvent(ctx context.Context, q *postgresdb.Queries, fallback org.OrgID, id identity.IdentityID, ev identity.Event, audit identity.Audit, at time.Time) error {
orgID, err := auditSubjectOrg(ctx, q, fallback, id)
if err != nil {
return err
}
return writeIdentityEvent(ctx, q, orgID, id, ev, audit, at)
}
// insertIdentityEventInOrg records an event under a target org the caller
// already knows, without resolving the subject's orgs. Account signup uses it:
// the account's new org is the target, whoever else the person already belongs
// to.
func insertIdentityEventInOrg(ctx context.Context, q *postgresdb.Queries, orgID org.OrgID, id identity.IdentityID, ev identity.Event, audit identity.Audit, at time.Time) error {
return writeIdentityEvent(ctx, q, orgID, id, ev, audit, at)
}
// auditSubjectOrg is the one definition of an identity event's org. A subject
// in exactly one org is attributed to it whatever org the actor acts in; a
// subject in two or more is deliberately unattributed (NULL), because picking
// one would hide the event from the other org's feed. An identity with no org
// yet uses fallback, the acting org.
func auditSubjectOrg(ctx context.Context, q *postgresdb.Queries, fallback org.OrgID, id identity.IdentityID) (org.OrgID, error) {
single, err := q.IdentityAuditOrg(ctx, string(id))
if errors.Is(err, pgx.ErrNoRows) {
return fallback, nil
}
if err != nil {
return "", fmt.Errorf("identity audit org: %w", err)
}
return org.OrgID(single), nil
}
// writeIdentityEvent records the event under orgID. An empty org is stored as
// NULL, which the audit feed shows only to instance administrators.
func writeIdentityEvent(ctx context.Context, q *postgresdb.Queries, orgID org.OrgID, id identity.IdentityID, ev identity.Event, audit identity.Audit, at time.Time) error {
if audit.ActorID == "" || audit.Source == "" || audit.RequestID == "" {
return fmt.Errorf("%w: audit actor, source, and request ID are required", identity.ErrInvalid)
}
storedOrg := pgtype.Text{}
if orgID != "" {
storedOrg = pgtype.Text{String: string(orgID), Valid: true}
}
return q.InsertIdentityEvent(ctx, postgresdb.InsertIdentityEventParams{
IdentityID: string(id), EventType: string(ev.Type),
FromLifecycle: string(ev.From), ToLifecycle: string(ev.To),
DisplayName: ev.DisplayName, ActorID: string(audit.ActorID),
Source: audit.Source, RequestID: audit.RequestID, At: at,
OrgID: storedOrg,
})
}
@@ -116,7 +158,7 @@ func (s *Store) create(ctx context.Context, value identity.Identity, audit ident
}); err != nil {
return identity.Identity{}, err
}
if err := insertIdentityEvent(ctx, q, value.ID, identity.Event{
if err := insertIdentityEvent(ctx, q, org.OrgFromContext(ctx), value.ID, identity.Event{
IdentityID: value.ID, Type: "create", To: value.Lifecycle, DisplayName: value.DisplayName,
}, audit, now); err != nil {
return identity.Identity{}, err
@@ -195,7 +237,7 @@ func (s *Store) Apply(ctx context.Context, id identity.IdentityID, expectedVersi
return identity.Identity{}, err
}
}
if err := insertIdentityEvent(ctx, q, id, ev, audit, now); err != nil {
if err := insertIdentityEvent(ctx, q, "", id, ev, audit, now); err != nil {
return identity.Identity{}, err
}
if err := tx.Commit(ctx); err != nil {
@@ -258,7 +300,7 @@ func (s *Store) ClaimSubject(ctx context.Context, placeholder, subject identity.
return err
}
claimed = identityFromRow(row)
return insertIdentityEvent(ctx, q, claimed.ID, identity.Event{
return insertIdentityEvent(ctx, q, "", claimed.ID, identity.Event{
IdentityID: claimed.ID, Type: "claim_subject", From: claimed.Lifecycle, To: claimed.Lifecycle, DisplayName: subject.Subject,
}, identity.Audit{ActorID: claimed.ID, Source: "sign-in", RequestID: placeholder.Subject}, now)
})
@@ -300,7 +342,7 @@ func (s *Store) BindSubject(ctx context.Context, id identity.IdentityID, subject
}); err != nil {
return err
}
if err := insertIdentityEvent(ctx, q, id, identity.Event{
if err := insertIdentityEvent(ctx, q, "", id, identity.Event{
IdentityID: id, Type: "bind_subject", From: cur.Lifecycle, To: cur.Lifecycle, DisplayName: subject.Subject,
}, audit, now); err != nil {
return err
@@ -352,7 +394,7 @@ func (s *Store) UnbindSubject(ctx context.Context, id identity.IdentityID, subje
return identity.ErrNotFound
}
cur := identityFromRow(current)
return insertIdentityEvent(ctx, q, id, identity.Event{
return insertIdentityEvent(ctx, q, "", id, identity.Event{
IdentityID: id, Type: "unbind_subject", From: cur.Lifecycle, To: cur.Lifecycle, DisplayName: subject.Subject,
}, audit, now)
})
@@ -0,0 +1,50 @@
-- Identity lifecycle events were instance-level: the feed joined live
-- memberships to decide which org could see them, so removing a member erased
-- their earlier lifecycle rows from that org's timeline. org_id on the event
-- makes the org a first-class, immutable fact recorded when the event happens.
--
-- Historical rows have no recorded org. A membership row carries only the
-- moment it started (no end), so the memberships in effect at an event are
-- those created at or before it. An event is attributed only when exactly one
-- org qualifies: a person in two or more orgs at the time is deliberately left
-- NULL, because picking one would hide the event from the other org's feed.
-- The agent-assignment fallback follows the same exactly-one rule. A row with
-- no qualifying org stays NULL and is visible only to an instance
-- administrator. The write path resolves an identity's orgs with the same
-- definition, so a new multi-org event is NULL by design too.
-- +goose Up
ALTER TABLE identity_events ADD COLUMN org_id text;
ALTER TABLE identity_events ADD CONSTRAINT identity_events_org_nonempty
CHECK (org_id IS NULL OR org_id <> '');
UPDATE identity_events ie SET org_id = CASE
WHEN (
SELECT count(DISTINCT m.org_id) FROM memberships m
WHERE m.identity_id = ie.identity_id AND m.created_at <= ie.at
) = 1 THEN (
SELECT min(m.org_id) FROM memberships m
WHERE m.identity_id = ie.identity_id AND m.created_at <= ie.at
)
WHEN (
SELECT count(DISTINCT m.org_id) FROM memberships m
WHERE m.identity_id = ie.identity_id AND m.created_at <= ie.at
) = 0
AND (
SELECT count(DISTINCT a.org_id) FROM org_agents a
WHERE a.identity_id = ie.identity_id AND a.created_at <= ie.at
) = 1 THEN (
SELECT min(a.org_id) FROM org_agents a
WHERE a.identity_id = ie.identity_id AND a.created_at <= ie.at
)
ELSE NULL
END;
-- Keep the instance-admin read ordered by time as well: its predicate has no
-- org equality, so the org-leading index alone would not serve it.
CREATE INDEX idx_identity_events_org_at ON identity_events (org_id, at DESC, id DESC);
-- +goose Down
DROP INDEX idx_identity_events_org_at;
ALTER TABLE identity_events DROP CONSTRAINT identity_events_org_nonempty;
ALTER TABLE identity_events DROP COLUMN org_id;
@@ -0,0 +1,577 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: audit_feed.sql
package postgresdb
import (
"context"
"time"
"github.com/jackc/pgx/v5/pgtype"
)
const auditHead = `-- name: AuditHead :one
SELECT
(SELECT COALESCE(max(id), 0)::bigint FROM sys_audit WHERE org_id = $1::text) AS sys_audit_id,
(SELECT COALESCE(max(id), 0)::bigint FROM identity_events
WHERE ($2::boolean
OR (org_id IS NOT NULL AND org_id = $1::text))) AS identity_event_id,
(SELECT COALESCE(max(id), 0)::bigint FROM access_denials WHERE org_id = $1::text) AS access_denial_id,
(SELECT COALESCE(sum(count), 0)::bigint FROM access_denials WHERE org_id = $1::text) AS access_denial_count,
(SELECT COALESCE(max(id), 0)::bigint FROM events WHERE org_id = $1::text) AS event_id
`
type AuditHeadParams struct {
OrgID string
InstanceAdmin bool
}
type AuditHeadRow struct {
SysAuditID int64
IdentityEventID int64
AccessDenialID int64
AccessDenialCount int64
EventID int64
}
// A token over the newest id of each trail the caller can read, plus the
// denials' count sum because a coalesced denial bumps its count in place
// without drawing a new id. It carries no rows and no org data.
func (q *Queries) AuditHead(ctx context.Context, arg AuditHeadParams) (AuditHeadRow, error) {
row := q.db.QueryRow(ctx, auditHead, arg.OrgID, arg.InstanceAdmin)
var i AuditHeadRow
err := row.Scan(
&i.SysAuditID,
&i.IdentityEventID,
&i.AccessDenialID,
&i.AccessDenialCount,
&i.EventID,
)
return i, err
}
const listAudit = `-- name: ListAudit :many
WITH sys_changes AS (
SELECT
a.org_id,
a.table_name,
a.record_key,
a.request_id,
a.record_version,
a.at,
a.actor,
a.source,
max(a.id)::bigint AS source_id,
jsonb_object_agg(
a.field,
jsonb_build_object(
'old', CASE WHEN a.old_value IS NULL THEN 'null'::jsonb ELSE a.old_value END,
'new', CASE WHEN a.new_value IS NULL THEN 'null'::jsonb ELSE a.new_value END
)
) AS fields,
bool_and(a.old_value IS NULL) AS all_old_null,
bool_and(a.new_value IS NULL) AS all_new_null,
bool_or(a.field = 'reset') AS is_reset,
count(DISTINCT a.field)::int AS field_count,
bool_or(a.field IN (
'org', 'workspace', 'role', 'org_id',
'mapping', 'binding', 'source', 'event_type',
'install', 'remove', 'credential'
)) AS whole_record_field,
string_agg(DISTINCT a.field, ' ') AS field_names
FROM sys_audit a
WHERE a.org_id = $2::text
AND (
COALESCE(cardinality($3::text[]), 0) = 0
OR (a.table_name = 'resources' AND 'settings' = ANY($3::text[]))
OR (a.table_name = 'access_policies' AND 'access' = ANY($3::text[]))
OR (a.table_name IN ('memberships', 'org_agents') AND 'access' = ANY($3::text[]))
OR (a.table_name IN ('bindings', 'mappings', 'event_types') AND 'automation' = ANY($3::text[]))
OR (
a.table_name NOT IN (
'resources', 'access_policies',
'memberships', 'org_agents',
'bindings', 'mappings', 'event_types'
)
AND 'settings' = ANY($3::text[])
)
)
AND ($4::timestamptz IS NULL OR a.at <= $4::timestamptz)
AND ($5::timestamptz IS NULL OR a.at >= $5::timestamptz)
AND ($6::timestamptz IS NULL OR a.at < $6::timestamptz)
AND ($7::text IS NULL OR a.actor = $7::text)
GROUP BY a.org_id, a.table_name, a.record_key, a.request_id, a.record_version, a.at, a.actor, a.source
)
SELECT org_id, category, source_rank, source_id, at, actor, actor_kind, principal_id, target_kind, target_id, kind, record_version, request_id, source, fields, action, severity, outcome, detail, search_text, workspace_id, task_id, data_text FROM (
SELECT org_id, category, source_rank, source_id, at, actor, actor_kind, principal_id, target_kind, target_id, kind, record_version, request_id, source, fields, action, severity, outcome, detail, search_text, workspace_id, task_id, data_text FROM (
SELECT
g.org_id AS org_id,
CASE g.table_name WHEN 'access_policies' THEN 'access' ELSE 'settings' END AS category,
1 AS source_rank,
g.source_id,
g.at,
g.actor,
''::text AS actor_kind,
''::text AS principal_id,
CASE g.table_name
WHEN 'resources' THEN 'resource'
ELSE 'policy'
END AS target_kind,
CASE g.table_name
WHEN 'resources' THEN
CASE WHEN position('/' IN g.record_key) > 0
THEN split_part(g.record_key, '/', 2)
ELSE g.record_key
END
ELSE g.record_key
END::text AS target_id,
CASE g.table_name
WHEN 'resources' THEN
CASE WHEN position('/' IN g.record_key) > 0
THEN split_part(g.record_key, '/', 2)
ELSE g.record_key
END
ELSE 'access_policy'
END AS kind,
g.record_version,
g.request_id,
g.source,
g.fields,
CASE
WHEN g.table_name = 'access_policies' AND g.is_reset THEN 'reset'
WHEN g.table_name = 'access_policies' AND g.all_new_null AND g.record_version > 0 THEN 'delete'
WHEN g.table_name = 'access_policies' AND g.all_old_null THEN 'create'
WHEN g.table_name = 'resources' AND g.record_version = 1 AND g.all_old_null THEN 'create'
ELSE 'update'
END AS action,
CASE
WHEN g.table_name = 'access_policies' AND g.is_reset THEN 'warning'
WHEN g.table_name = 'access_policies' AND g.all_new_null AND g.record_version > 0 THEN 'warning'
ELSE 'info'
END AS severity,
'success'::text AS outcome,
''::text AS detail,
concat_ws(' ', g.record_key, g.actor, g.source, g.field_names,
CASE g.table_name
WHEN 'resources' THEN
CASE WHEN position('/' IN g.record_key) > 0
THEN split_part(g.record_key, '/', 2)
ELSE g.record_key
END
ELSE 'access_policy'
END) AS search_text,
CASE
WHEN g.table_name = 'access_policies'
AND split_part(g.record_key, '/', 1) IN ('workspace', 'object')
THEN split_part(g.record_key, '/', 3)
ELSE ''
END AS workspace_id,
0::bigint AS task_id,
''::text AS data_text
FROM sys_changes g
WHERE g.table_name IN ('resources', 'access_policies')
) s
WHERE (COALESCE(cardinality($3::text[]), 0) = 0 OR s.category = ANY($3::text[]))
AND (COALESCE(cardinality($8::text[]), 0) = 0 OR s.action = ANY($8::text[]))
AND (COALESCE(cardinality($9::text[]), 0) = 0 OR s.kind = ANY($9::text[]))
AND ($7::text IS NULL OR s.actor = $7::text)
AND (COALESCE(cardinality($10::text[]), 0) = 0 OR s.target_kind = ANY($10::text[]))
AND (COALESCE(cardinality($11::text[]), 0) = 0 OR s.target_id = ANY($11::text[]))
AND (COALESCE(cardinality($12::text[]), 0) = 0 OR s.severity = ANY($12::text[]))
AND (COALESCE(cardinality($13::text[]), 0) = 0 OR s.outcome = ANY($13::text[]))
AND ($14::text IS NULL OR position(lower($14::text) IN lower(s.search_text)) > 0)
AND (
$4::timestamptz IS NULL
OR s.at < $4::timestamptz
OR (s.at = $4::timestamptz AND s.source_rank < $15::int)
OR (s.at = $4::timestamptz AND s.source_rank = $15::int AND s.source_id < $16::bigint)
)
ORDER BY s.at DESC, s.source_rank DESC, s.source_id DESC
LIMIT $1::bigint
) b1
UNION ALL
SELECT org_id, category, source_rank, source_id, at, actor, actor_kind, principal_id, target_kind, target_id, kind, record_version, request_id, source, fields, action, severity, outcome, detail, search_text, workspace_id, task_id, data_text FROM (
SELECT org_id, category, source_rank, source_id, at, actor, actor_kind, principal_id, target_kind, target_id, kind, record_version, request_id, source, fields, action, severity, outcome, detail, search_text, workspace_id, task_id, data_text FROM (
SELECT
$2::text AS org_id,
'identity'::text AS category,
2 AS source_rank,
ie.id::bigint AS source_id,
ie.at,
ie.actor_id AS actor,
''::text AS actor_kind,
''::text AS principal_id,
'identity'::text AS target_kind,
ie.identity_id::text AS target_id,
ie.event_type AS kind,
0::bigint AS record_version,
ie.request_id,
ie.source,
'{}'::jsonb AS fields,
ie.event_type AS action,
CASE WHEN ie.event_type IN ('suspend', 'retire') THEN 'warning' ELSE 'info' END AS severity,
'success'::text AS outcome,
ie.from_lifecycle || ' → ' || ie.to_lifecycle AS detail,
concat_ws(' ', ie.identity_id, ie.event_type, ie.display_name, ie.actor_id, ie.source) AS search_text,
''::text AS workspace_id,
0::bigint AS task_id,
''::text AS data_text
FROM identity_events ie
WHERE ie.event_type IN ('create', 'rename', 'suspend', 'reactivate', 'retire')
AND ($17::boolean
OR (ie.org_id IS NOT NULL AND ie.org_id = $2::text))
AND ($5::timestamptz IS NULL OR ie.at >= $5::timestamptz)
AND ($6::timestamptz IS NULL OR ie.at < $6::timestamptz)
) si
WHERE (COALESCE(cardinality($3::text[]), 0) = 0 OR si.category = ANY($3::text[]))
AND (COALESCE(cardinality($8::text[]), 0) = 0 OR si.action = ANY($8::text[]))
AND (COALESCE(cardinality($9::text[]), 0) = 0 OR si.kind = ANY($9::text[]))
AND ($7::text IS NULL OR si.actor = $7::text)
AND (COALESCE(cardinality($10::text[]), 0) = 0 OR si.target_kind = ANY($10::text[]))
AND (COALESCE(cardinality($11::text[]), 0) = 0 OR si.target_id = ANY($11::text[]))
AND (COALESCE(cardinality($12::text[]), 0) = 0 OR si.severity = ANY($12::text[]))
AND (COALESCE(cardinality($13::text[]), 0) = 0 OR si.outcome = ANY($13::text[]))
AND ($14::text IS NULL OR position(lower($14::text) IN lower(si.search_text)) > 0)
AND (
$4::timestamptz IS NULL
OR si.at < $4::timestamptz
OR (si.at = $4::timestamptz AND si.source_rank < $15::int)
OR (si.at = $4::timestamptz AND si.source_rank = $15::int AND si.source_id < $16::bigint)
)
ORDER BY si.at DESC, si.source_rank DESC, si.source_id DESC
LIMIT $1::bigint
) b2
UNION ALL
SELECT org_id, category, source_rank, source_id, at, actor, actor_kind, principal_id, target_kind, target_id, kind, record_version, request_id, source, fields, action, severity, outcome, detail, search_text, workspace_id, task_id, data_text FROM (
SELECT org_id, category, source_rank, source_id, at, actor, actor_kind, principal_id, target_kind, target_id, kind, record_version, request_id, source, fields, action, severity, outcome, detail, search_text, workspace_id, task_id, data_text FROM (
SELECT
d.org_id,
'access'::text AS category,
3 AS source_rank,
d.id::bigint AS source_id,
d.minute_at AS at,
d.principal AS actor,
''::text AS actor_kind,
d.principal AS principal_id,
d.resource_kind AS target_kind,
d.resource_id::text AS target_id,
'access_denial'::text AS kind,
0::bigint AS record_version,
''::text AS request_id,
'access'::text AS source,
'{}'::jsonb AS fields,
'deny'::text AS action,
'warning'::text AS severity,
'denied'::text AS outcome,
CASE WHEN cardinality(d.policies) > 0 THEN array_to_string(d.policies, ', ') ELSE '' END AS detail,
concat_ws(' ', d.principal, d.action, d.resource_kind, d.resource_id, d.level, array_to_string(d.policies, ' ')) AS search_text,
''::text AS workspace_id,
0::bigint AS task_id,
jsonb_build_object('count', d.count, 'policies', d.policies)::text AS data_text
FROM access_denials d
WHERE d.org_id = $2::text
AND ($5::timestamptz IS NULL OR d.minute_at >= $5::timestamptz)
AND ($6::timestamptz IS NULL OR d.minute_at < $6::timestamptz)
) sd
WHERE (COALESCE(cardinality($3::text[]), 0) = 0 OR sd.category = ANY($3::text[]))
AND (COALESCE(cardinality($8::text[]), 0) = 0 OR sd.action = ANY($8::text[]))
AND (COALESCE(cardinality($9::text[]), 0) = 0 OR sd.kind = ANY($9::text[]))
AND ($7::text IS NULL OR sd.actor = $7::text)
AND (COALESCE(cardinality($10::text[]), 0) = 0 OR sd.target_kind = ANY($10::text[]))
AND (COALESCE(cardinality($11::text[]), 0) = 0 OR sd.target_id = ANY($11::text[]))
AND (COALESCE(cardinality($12::text[]), 0) = 0 OR sd.severity = ANY($12::text[]))
AND (COALESCE(cardinality($13::text[]), 0) = 0 OR sd.outcome = ANY($13::text[]))
AND ($14::text IS NULL OR position(lower($14::text) IN lower(sd.search_text)) > 0)
AND (
$4::timestamptz IS NULL
OR sd.at < $4::timestamptz
OR (sd.at = $4::timestamptz AND sd.source_rank < $15::int)
OR (sd.at = $4::timestamptz AND sd.source_rank = $15::int AND sd.source_id < $16::bigint)
)
ORDER BY sd.at DESC, sd.source_rank DESC, sd.source_id DESC
LIMIT $1::bigint
) b3
UNION ALL
SELECT org_id, category, source_rank, source_id, at, actor, actor_kind, principal_id, target_kind, target_id, kind, record_version, request_id, source, fields, action, severity, outcome, detail, search_text, workspace_id, task_id, data_text FROM (
SELECT org_id, category, source_rank, source_id, at, actor, actor_kind, principal_id, target_kind, target_id, kind, record_version, request_id, source, fields, action, severity, outcome, detail, search_text, workspace_id, task_id, data_text FROM (
SELECT
e.org_id,
CASE
WHEN e.kind = ANY(ARRAY[
'binding_changed', 'binding_started', 'mapping_changed',
'curator_run', 'curator_action', 'curator_error',
'job_run', 'job_error',
'workflow_call_started', 'workflow_call_finished',
'turn_completed', 'work_request_submitted'
]::text[]) THEN 'automation'
ELSE 'runtime'
END AS category,
4 AS source_rank,
e.id::bigint AS source_id,
e.at,
e.actor_id AS actor,
e.actor_kind,
e.principal_id,
CASE WHEN e.task_id > 0 THEN 'task' ELSE '' END AS target_kind,
(CASE WHEN e.task_id > 0 THEN e.task_id::text ELSE '' END)::text AS target_id,
e.kind,
0::bigint AS record_version,
''::text AS request_id,
''::text AS source,
'{}'::jsonb AS fields,
e.kind AS action,
CASE
WHEN e.kind = ANY(ARRAY[
'task_dead', 'pr_rejected',
'operator_rejected', 'agent_rejected', 'task_rejected',
'task_abandoned', 'task_withdrawn', 'step_retried',
'curator_error', 'job_error', 'binding_dispatch_failure'
]::text[]) THEN 'error'
WHEN e.kind = ANY(ARRAY[
'parked', 'task_retried', 'task_cancelled', 'task_stopped',
'alert', 'update_report'
]::text[]) THEN 'warning'
ELSE 'info'
END AS severity,
CASE
WHEN e.kind = ANY(ARRAY[
'task_dead', 'pr_rejected',
'operator_rejected', 'agent_rejected', 'task_rejected',
'task_abandoned', 'task_withdrawn', 'step_retried',
'curator_error', 'job_error', 'binding_dispatch_failure'
]::text[]) THEN 'failure'
ELSE 'success'
END AS outcome,
e.detail,
concat_ws(' ', e.kind, e.actor_id, e.actor_kind, e.repo, e.workflow, e.stage, e.task_id::text) AS search_text,
e.workspace_id,
e.task_id,
e.data AS data_text
FROM events e
WHERE e.org_id = $2::text
AND ($5::timestamptz IS NULL OR e.at >= $5::timestamptz)
AND ($6::timestamptz IS NULL OR e.at < $6::timestamptz)
) se
WHERE (COALESCE(cardinality($3::text[]), 0) = 0 OR se.category = ANY($3::text[]))
AND (COALESCE(cardinality($8::text[]), 0) = 0 OR se.action = ANY($8::text[]))
AND (COALESCE(cardinality($9::text[]), 0) = 0 OR se.kind = ANY($9::text[]))
AND ($7::text IS NULL OR se.actor = $7::text)
AND (COALESCE(cardinality($10::text[]), 0) = 0 OR se.target_kind = ANY($10::text[]))
AND (COALESCE(cardinality($11::text[]), 0) = 0 OR se.target_id = ANY($11::text[]))
AND (COALESCE(cardinality($12::text[]), 0) = 0 OR se.severity = ANY($12::text[]))
AND (COALESCE(cardinality($13::text[]), 0) = 0 OR se.outcome = ANY($13::text[]))
AND ($14::text IS NULL OR position(lower($14::text) IN lower(se.search_text)) > 0)
AND (
$4::timestamptz IS NULL
OR se.at < $4::timestamptz
OR (se.at = $4::timestamptz AND se.source_rank < $15::int)
OR (se.at = $4::timestamptz AND se.source_rank = $15::int AND se.source_id < $16::bigint)
)
ORDER BY se.at DESC, se.source_rank DESC, se.source_id DESC
LIMIT $1::bigint
) b4
UNION ALL
SELECT org_id, category, source_rank, source_id, at, actor, actor_kind, principal_id, target_kind, target_id, kind, record_version, request_id, source, fields, action, severity, outcome, detail, search_text, workspace_id, task_id, data_text FROM (
SELECT org_id, category, source_rank, source_id, at, actor, actor_kind, principal_id, target_kind, target_id, kind, record_version, request_id, source, fields, action, severity, outcome, detail, search_text, workspace_id, task_id, data_text FROM (
SELECT
g.org_id,
CASE
WHEN g.table_name IN ('memberships', 'org_agents') THEN 'access'
WHEN g.table_name IN ('bindings', 'mappings', 'event_types') THEN 'automation'
ELSE 'settings'
END AS category,
5 AS source_rank,
g.source_id,
g.at,
g.actor,
''::text AS actor_kind,
''::text AS principal_id,
g.table_name::text AS target_kind,
g.record_key::text AS target_id,
g.table_name AS kind,
g.record_version,
g.request_id,
g.source,
g.fields,
CASE
WHEN g.field_count = 1 AND g.whole_record_field AND g.all_old_null THEN 'create'
WHEN g.field_count = 1 AND g.whole_record_field AND g.all_new_null THEN 'delete'
ELSE 'update'
END AS action,
CASE
WHEN g.field_count = 1 AND g.whole_record_field AND g.all_new_null
AND NOT g.all_old_null THEN 'warning'
ELSE 'info'
END AS severity,
'success'::text AS outcome,
''::text AS detail,
concat_ws(' ', g.record_key, g.actor, g.source, g.field_names, g.table_name) AS search_text,
''::text AS workspace_id,
0::bigint AS task_id,
''::text AS data_text
FROM sys_changes g
WHERE g.table_name NOT IN ('resources', 'access_policies')
) sg
WHERE (COALESCE(cardinality($3::text[]), 0) = 0 OR sg.category = ANY($3::text[]))
AND (COALESCE(cardinality($8::text[]), 0) = 0 OR sg.action = ANY($8::text[]))
AND (COALESCE(cardinality($9::text[]), 0) = 0 OR sg.kind = ANY($9::text[]))
AND ($7::text IS NULL OR sg.actor = $7::text)
AND (COALESCE(cardinality($10::text[]), 0) = 0 OR sg.target_kind = ANY($10::text[]))
AND (COALESCE(cardinality($11::text[]), 0) = 0 OR sg.target_id = ANY($11::text[]))
AND (COALESCE(cardinality($12::text[]), 0) = 0 OR sg.severity = ANY($12::text[]))
AND (COALESCE(cardinality($13::text[]), 0) = 0 OR sg.outcome = ANY($13::text[]))
AND ($14::text IS NULL OR position(lower($14::text) IN lower(sg.search_text)) > 0)
AND (
$4::timestamptz IS NULL
OR sg.at < $4::timestamptz
OR (sg.at = $4::timestamptz AND sg.source_rank < $15::int)
OR (sg.at = $4::timestamptz AND sg.source_rank = $15::int AND sg.source_id < $16::bigint)
)
ORDER BY sg.at DESC, sg.source_rank DESC, sg.source_id DESC
LIMIT $1::bigint
) merged
ORDER BY merged.at DESC, merged.source_rank DESC, merged.source_id DESC
LIMIT $1::bigint
`
type ListAuditParams struct {
PageLimit int64
OrgID string
Categories []string
CursorAt pgtype.Timestamptz
FromAt pgtype.Timestamptz
ToAt pgtype.Timestamptz
Actor pgtype.Text
Actions []string
Kinds []string
TargetKinds []string
TargetIds []string
Severities []string
Outcomes []string
Q pgtype.Text
CursorRank int32
CursorID int64
InstanceAdmin bool
}
type ListAuditRow struct {
OrgID string
Category string
SourceRank int32
SourceID int64
At time.Time
Actor string
ActorKind string
PrincipalID string
TargetKind string
TargetID string
Kind string
RecordVersion int64
RequestID string
Source string
Fields []byte
Action string
Severity string
Outcome string
Detail string
SearchText string
WorkspaceID string
TaskID int64
DataText string
}
// The audit feed read model: one org-scoped timeline over every durable
// trail the State Store owns. It is a parameterised UNION ALL, not a view,
// because the filters and the keyset cursor must reach each source before
// that source's ORDER BY ... LIMIT; otherwise a page of the merged feed
// groups or scans the whole trail first.
//
// Each branch emits the same row shape. The outer query merges the per-branch
// top-K and takes the page. Ranks are fixed per origin and never reused:
//
// 1 sys_audit resources and access_policies, grouped into change sets
// 2 identity_events lifecycle events
// 3 access_denials, one aggregated denial
// 4 events
// 5 sys_audit coverage tables (orgs, memberships, sources, ...), grouped
//
// search_text is metadata only. It never contains a value, an event's data,
// or policy text: substring search over unredacted values would be a
// token-guessing oracle. The adapter redacts fields, data and detail before
// an entry leaves the process, and fail-closes on undecodable JSON.
//
// Identity lifecycle rows carry the org they happened in, so removing a
// member does not erase their earlier history from that org's feed. Only a
// principal with instance-wide authority sees every org's identity events;
// being confined to the system org is not that authority. A historical row
// with no defensible org stays NULL and is visible only to that authority.
//
// Coverage-table change sets are classified by their whole-record field, not
// by a version: a create is a whole-record field with a null old side, a
// delete the same field with a null new side, and everything else an update.
// A partial add or remove is never a create or delete.
func (q *Queries) ListAudit(ctx context.Context, arg ListAuditParams) ([]ListAuditRow, error) {
rows, err := q.db.Query(ctx, listAudit,
arg.PageLimit,
arg.OrgID,
arg.Categories,
arg.CursorAt,
arg.FromAt,
arg.ToAt,
arg.Actor,
arg.Actions,
arg.Kinds,
arg.TargetKinds,
arg.TargetIds,
arg.Severities,
arg.Outcomes,
arg.Q,
arg.CursorRank,
arg.CursorID,
arg.InstanceAdmin,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListAuditRow
for rows.Next() {
var i ListAuditRow
if err := rows.Scan(
&i.OrgID,
&i.Category,
&i.SourceRank,
&i.SourceID,
&i.At,
&i.Actor,
&i.ActorKind,
&i.PrincipalID,
&i.TargetKind,
&i.TargetID,
&i.Kind,
&i.RecordVersion,
&i.RequestID,
&i.Source,
&i.Fields,
&i.Action,
&i.Severity,
&i.Outcome,
&i.Detail,
&i.SearchText,
&i.WorkspaceID,
&i.TaskID,
&i.DataText,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -104,6 +104,26 @@ func (q *Queries) GetVisibleIdentity(ctx context.Context, arg GetVisibleIdentity
return i, err
}
const identityAuditOrg = `-- name: IdentityAuditOrg :one
SELECT min(org_id)::text AS org_id
FROM (
SELECT m.org_id FROM memberships m WHERE m.identity_id = $1
UNION
SELECT a.org_id FROM org_agents a WHERE a.identity_id = $1
) belonging
HAVING count(DISTINCT org_id) = 1
`
// The identity's org only when it belongs to exactly one, across memberships
// and agent assignments; no row otherwise. One statement, so a concurrent
// membership add cannot make the count and the org disagree.
func (q *Queries) IdentityAuditOrg(ctx context.Context, identityID string) (string, error) {
row := q.db.QueryRow(ctx, identityAuditOrg, identityID)
var org_id string
err := row.Scan(&org_id)
return org_id, err
}
const insertIdentity = `-- name: InsertIdentity :exec
INSERT INTO identities (id, kind, display_name, lifecycle, version, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)
@@ -161,8 +181,8 @@ func (q *Queries) InsertIdentityAliasIgnoreConflict(ctx context.Context, arg Ins
}
const insertIdentityEvent = `-- name: InsertIdentityEvent :exec
INSERT INTO identity_events (identity_id, event_type, from_lifecycle, to_lifecycle, display_name, actor_id, source, request_id, at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
INSERT INTO identity_events (identity_id, event_type, from_lifecycle, to_lifecycle, display_name, actor_id, source, request_id, at, org_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
`
type InsertIdentityEventParams struct {
@@ -175,6 +195,7 @@ type InsertIdentityEventParams struct {
Source string
RequestID string
At time.Time
OrgID pgtype.Text
}
func (q *Queries) InsertIdentityEvent(ctx context.Context, arg InsertIdentityEventParams) error {
@@ -188,6 +209,7 @@ func (q *Queries) InsertIdentityEvent(ctx context.Context, arg InsertIdentityEve
arg.Source,
arg.RequestID,
arg.At,
arg.OrgID,
)
return err
}
@@ -258,6 +258,7 @@ type IdentityEvent struct {
Source string
RequestID string
At time.Time
OrgID pgtype.Text
}
type IdentitySubject struct {
@@ -0,0 +1,426 @@
-- The audit feed read model: one org-scoped timeline over every durable
-- trail the State Store owns. It is a parameterised UNION ALL, not a view,
-- because the filters and the keyset cursor must reach each source before
-- that source's ORDER BY ... LIMIT; otherwise a page of the merged feed
-- groups or scans the whole trail first.
--
-- Each branch emits the same row shape. The outer query merges the per-branch
-- top-K and takes the page. Ranks are fixed per origin and never reused:
-- 1 sys_audit resources and access_policies, grouped into change sets
-- 2 identity_events lifecycle events
-- 3 access_denials, one aggregated denial
-- 4 events
-- 5 sys_audit coverage tables (orgs, memberships, sources, ...), grouped
--
-- search_text is metadata only. It never contains a value, an event's data,
-- or policy text: substring search over unredacted values would be a
-- token-guessing oracle. The adapter redacts fields, data and detail before
-- an entry leaves the process, and fail-closes on undecodable JSON.
--
-- Identity lifecycle rows carry the org they happened in, so removing a
-- member does not erase their earlier history from that org's feed. Only a
-- principal with instance-wide authority sees every org's identity events;
-- being confined to the system org is not that authority. A historical row
-- with no defensible org stays NULL and is visible only to that authority.
--
-- Coverage-table change sets are classified by their whole-record field, not
-- by a version: a create is a whole-record field with a null old side, a
-- delete the same field with a null new side, and everything else an update.
-- A partial add or remove is never a create or delete.
-- name: ListAudit :many
WITH sys_changes AS (
SELECT
a.org_id,
a.table_name,
a.record_key,
a.request_id,
a.record_version,
a.at,
a.actor,
a.source,
max(a.id)::bigint AS source_id,
jsonb_object_agg(
a.field,
jsonb_build_object(
'old', CASE WHEN a.old_value IS NULL THEN 'null'::jsonb ELSE a.old_value END,
'new', CASE WHEN a.new_value IS NULL THEN 'null'::jsonb ELSE a.new_value END
)
) AS fields,
bool_and(a.old_value IS NULL) AS all_old_null,
bool_and(a.new_value IS NULL) AS all_new_null,
bool_or(a.field = 'reset') AS is_reset,
count(DISTINCT a.field)::int AS field_count,
bool_or(a.field IN (
'org', 'workspace', 'role', 'org_id',
'mapping', 'binding', 'source', 'event_type',
'install', 'remove', 'credential'
)) AS whole_record_field,
string_agg(DISTINCT a.field, ' ') AS field_names
FROM sys_audit a
WHERE a.org_id = sqlc.arg(org_id)::text
AND (
COALESCE(cardinality(sqlc.arg(categories)::text[]), 0) = 0
OR (a.table_name = 'resources' AND 'settings' = ANY(sqlc.arg(categories)::text[]))
OR (a.table_name = 'access_policies' AND 'access' = ANY(sqlc.arg(categories)::text[]))
OR (a.table_name IN ('memberships', 'org_agents') AND 'access' = ANY(sqlc.arg(categories)::text[]))
OR (a.table_name IN ('bindings', 'mappings', 'event_types') AND 'automation' = ANY(sqlc.arg(categories)::text[]))
OR (
a.table_name NOT IN (
'resources', 'access_policies',
'memberships', 'org_agents',
'bindings', 'mappings', 'event_types'
)
AND 'settings' = ANY(sqlc.arg(categories)::text[])
)
)
AND (sqlc.narg(cursor_at)::timestamptz IS NULL OR a.at <= sqlc.narg(cursor_at)::timestamptz)
AND (sqlc.narg(from_at)::timestamptz IS NULL OR a.at >= sqlc.narg(from_at)::timestamptz)
AND (sqlc.narg(to_at)::timestamptz IS NULL OR a.at < sqlc.narg(to_at)::timestamptz)
AND (sqlc.narg(actor)::text IS NULL OR a.actor = sqlc.narg(actor)::text)
GROUP BY a.org_id, a.table_name, a.record_key, a.request_id, a.record_version, a.at, a.actor, a.source
)
SELECT * FROM (
SELECT * FROM (
SELECT
g.org_id AS org_id,
CASE g.table_name WHEN 'access_policies' THEN 'access' ELSE 'settings' END AS category,
1 AS source_rank,
g.source_id,
g.at,
g.actor,
''::text AS actor_kind,
''::text AS principal_id,
CASE g.table_name
WHEN 'resources' THEN 'resource'
ELSE 'policy'
END AS target_kind,
CASE g.table_name
WHEN 'resources' THEN
CASE WHEN position('/' IN g.record_key) > 0
THEN split_part(g.record_key, '/', 2)
ELSE g.record_key
END
ELSE g.record_key
END::text AS target_id,
CASE g.table_name
WHEN 'resources' THEN
CASE WHEN position('/' IN g.record_key) > 0
THEN split_part(g.record_key, '/', 2)
ELSE g.record_key
END
ELSE 'access_policy'
END AS kind,
g.record_version,
g.request_id,
g.source,
g.fields,
CASE
WHEN g.table_name = 'access_policies' AND g.is_reset THEN 'reset'
WHEN g.table_name = 'access_policies' AND g.all_new_null AND g.record_version > 0 THEN 'delete'
WHEN g.table_name = 'access_policies' AND g.all_old_null THEN 'create'
WHEN g.table_name = 'resources' AND g.record_version = 1 AND g.all_old_null THEN 'create'
ELSE 'update'
END AS action,
CASE
WHEN g.table_name = 'access_policies' AND g.is_reset THEN 'warning'
WHEN g.table_name = 'access_policies' AND g.all_new_null AND g.record_version > 0 THEN 'warning'
ELSE 'info'
END AS severity,
'success'::text AS outcome,
''::text AS detail,
concat_ws(' ', g.record_key, g.actor, g.source, g.field_names,
CASE g.table_name
WHEN 'resources' THEN
CASE WHEN position('/' IN g.record_key) > 0
THEN split_part(g.record_key, '/', 2)
ELSE g.record_key
END
ELSE 'access_policy'
END) AS search_text,
CASE
WHEN g.table_name = 'access_policies'
AND split_part(g.record_key, '/', 1) IN ('workspace', 'object')
THEN split_part(g.record_key, '/', 3)
ELSE ''
END AS workspace_id,
0::bigint AS task_id,
''::text AS data_text
FROM sys_changes g
WHERE g.table_name IN ('resources', 'access_policies')
) s
WHERE (COALESCE(cardinality(sqlc.arg(categories)::text[]), 0) = 0 OR s.category = ANY(sqlc.arg(categories)::text[]))
AND (COALESCE(cardinality(sqlc.arg(actions)::text[]), 0) = 0 OR s.action = ANY(sqlc.arg(actions)::text[]))
AND (COALESCE(cardinality(sqlc.arg(kinds)::text[]), 0) = 0 OR s.kind = ANY(sqlc.arg(kinds)::text[]))
AND (sqlc.narg(actor)::text IS NULL OR s.actor = sqlc.narg(actor)::text)
AND (COALESCE(cardinality(sqlc.arg(target_kinds)::text[]), 0) = 0 OR s.target_kind = ANY(sqlc.arg(target_kinds)::text[]))
AND (COALESCE(cardinality(sqlc.arg(target_ids)::text[]), 0) = 0 OR s.target_id = ANY(sqlc.arg(target_ids)::text[]))
AND (COALESCE(cardinality(sqlc.arg(severities)::text[]), 0) = 0 OR s.severity = ANY(sqlc.arg(severities)::text[]))
AND (COALESCE(cardinality(sqlc.arg(outcomes)::text[]), 0) = 0 OR s.outcome = ANY(sqlc.arg(outcomes)::text[]))
AND (sqlc.narg(q)::text IS NULL OR position(lower(sqlc.narg(q)::text) IN lower(s.search_text)) > 0)
AND (
sqlc.narg(cursor_at)::timestamptz IS NULL
OR s.at < sqlc.narg(cursor_at)::timestamptz
OR (s.at = sqlc.narg(cursor_at)::timestamptz AND s.source_rank < sqlc.arg(cursor_rank)::int)
OR (s.at = sqlc.narg(cursor_at)::timestamptz AND s.source_rank = sqlc.arg(cursor_rank)::int AND s.source_id < sqlc.arg(cursor_id)::bigint)
)
ORDER BY s.at DESC, s.source_rank DESC, s.source_id DESC
LIMIT sqlc.arg(page_limit)::bigint
) b1
UNION ALL
SELECT * FROM (
SELECT * FROM (
SELECT
sqlc.arg(org_id)::text AS org_id,
'identity'::text AS category,
2 AS source_rank,
ie.id::bigint AS source_id,
ie.at,
ie.actor_id AS actor,
''::text AS actor_kind,
''::text AS principal_id,
'identity'::text AS target_kind,
ie.identity_id::text AS target_id,
ie.event_type AS kind,
0::bigint AS record_version,
ie.request_id,
ie.source,
'{}'::jsonb AS fields,
ie.event_type AS action,
CASE WHEN ie.event_type IN ('suspend', 'retire') THEN 'warning' ELSE 'info' END AS severity,
'success'::text AS outcome,
ie.from_lifecycle || ' → ' || ie.to_lifecycle AS detail,
concat_ws(' ', ie.identity_id, ie.event_type, ie.display_name, ie.actor_id, ie.source) AS search_text,
''::text AS workspace_id,
0::bigint AS task_id,
''::text AS data_text
FROM identity_events ie
WHERE ie.event_type IN ('create', 'rename', 'suspend', 'reactivate', 'retire')
AND (sqlc.arg(instance_admin)::boolean
OR (ie.org_id IS NOT NULL AND ie.org_id = sqlc.arg(org_id)::text))
AND (sqlc.narg(from_at)::timestamptz IS NULL OR ie.at >= sqlc.narg(from_at)::timestamptz)
AND (sqlc.narg(to_at)::timestamptz IS NULL OR ie.at < sqlc.narg(to_at)::timestamptz)
) si
WHERE (COALESCE(cardinality(sqlc.arg(categories)::text[]), 0) = 0 OR si.category = ANY(sqlc.arg(categories)::text[]))
AND (COALESCE(cardinality(sqlc.arg(actions)::text[]), 0) = 0 OR si.action = ANY(sqlc.arg(actions)::text[]))
AND (COALESCE(cardinality(sqlc.arg(kinds)::text[]), 0) = 0 OR si.kind = ANY(sqlc.arg(kinds)::text[]))
AND (sqlc.narg(actor)::text IS NULL OR si.actor = sqlc.narg(actor)::text)
AND (COALESCE(cardinality(sqlc.arg(target_kinds)::text[]), 0) = 0 OR si.target_kind = ANY(sqlc.arg(target_kinds)::text[]))
AND (COALESCE(cardinality(sqlc.arg(target_ids)::text[]), 0) = 0 OR si.target_id = ANY(sqlc.arg(target_ids)::text[]))
AND (COALESCE(cardinality(sqlc.arg(severities)::text[]), 0) = 0 OR si.severity = ANY(sqlc.arg(severities)::text[]))
AND (COALESCE(cardinality(sqlc.arg(outcomes)::text[]), 0) = 0 OR si.outcome = ANY(sqlc.arg(outcomes)::text[]))
AND (sqlc.narg(q)::text IS NULL OR position(lower(sqlc.narg(q)::text) IN lower(si.search_text)) > 0)
AND (
sqlc.narg(cursor_at)::timestamptz IS NULL
OR si.at < sqlc.narg(cursor_at)::timestamptz
OR (si.at = sqlc.narg(cursor_at)::timestamptz AND si.source_rank < sqlc.arg(cursor_rank)::int)
OR (si.at = sqlc.narg(cursor_at)::timestamptz AND si.source_rank = sqlc.arg(cursor_rank)::int AND si.source_id < sqlc.arg(cursor_id)::bigint)
)
ORDER BY si.at DESC, si.source_rank DESC, si.source_id DESC
LIMIT sqlc.arg(page_limit)::bigint
) b2
UNION ALL
SELECT * FROM (
SELECT * FROM (
SELECT
d.org_id,
'access'::text AS category,
3 AS source_rank,
d.id::bigint AS source_id,
d.minute_at AS at,
d.principal AS actor,
''::text AS actor_kind,
d.principal AS principal_id,
d.resource_kind AS target_kind,
d.resource_id::text AS target_id,
'access_denial'::text AS kind,
0::bigint AS record_version,
''::text AS request_id,
'access'::text AS source,
'{}'::jsonb AS fields,
'deny'::text AS action,
'warning'::text AS severity,
'denied'::text AS outcome,
CASE WHEN cardinality(d.policies) > 0 THEN array_to_string(d.policies, ', ') ELSE '' END AS detail,
concat_ws(' ', d.principal, d.action, d.resource_kind, d.resource_id, d.level, array_to_string(d.policies, ' ')) AS search_text,
''::text AS workspace_id,
0::bigint AS task_id,
jsonb_build_object('count', d.count, 'policies', d.policies)::text AS data_text
FROM access_denials d
WHERE d.org_id = sqlc.arg(org_id)::text
AND (sqlc.narg(from_at)::timestamptz IS NULL OR d.minute_at >= sqlc.narg(from_at)::timestamptz)
AND (sqlc.narg(to_at)::timestamptz IS NULL OR d.minute_at < sqlc.narg(to_at)::timestamptz)
) sd
WHERE (COALESCE(cardinality(sqlc.arg(categories)::text[]), 0) = 0 OR sd.category = ANY(sqlc.arg(categories)::text[]))
AND (COALESCE(cardinality(sqlc.arg(actions)::text[]), 0) = 0 OR sd.action = ANY(sqlc.arg(actions)::text[]))
AND (COALESCE(cardinality(sqlc.arg(kinds)::text[]), 0) = 0 OR sd.kind = ANY(sqlc.arg(kinds)::text[]))
AND (sqlc.narg(actor)::text IS NULL OR sd.actor = sqlc.narg(actor)::text)
AND (COALESCE(cardinality(sqlc.arg(target_kinds)::text[]), 0) = 0 OR sd.target_kind = ANY(sqlc.arg(target_kinds)::text[]))
AND (COALESCE(cardinality(sqlc.arg(target_ids)::text[]), 0) = 0 OR sd.target_id = ANY(sqlc.arg(target_ids)::text[]))
AND (COALESCE(cardinality(sqlc.arg(severities)::text[]), 0) = 0 OR sd.severity = ANY(sqlc.arg(severities)::text[]))
AND (COALESCE(cardinality(sqlc.arg(outcomes)::text[]), 0) = 0 OR sd.outcome = ANY(sqlc.arg(outcomes)::text[]))
AND (sqlc.narg(q)::text IS NULL OR position(lower(sqlc.narg(q)::text) IN lower(sd.search_text)) > 0)
AND (
sqlc.narg(cursor_at)::timestamptz IS NULL
OR sd.at < sqlc.narg(cursor_at)::timestamptz
OR (sd.at = sqlc.narg(cursor_at)::timestamptz AND sd.source_rank < sqlc.arg(cursor_rank)::int)
OR (sd.at = sqlc.narg(cursor_at)::timestamptz AND sd.source_rank = sqlc.arg(cursor_rank)::int AND sd.source_id < sqlc.arg(cursor_id)::bigint)
)
ORDER BY sd.at DESC, sd.source_rank DESC, sd.source_id DESC
LIMIT sqlc.arg(page_limit)::bigint
) b3
UNION ALL
SELECT * FROM (
SELECT * FROM (
SELECT
e.org_id,
CASE
WHEN e.kind = ANY(ARRAY[
'binding_changed', 'binding_started', 'mapping_changed',
'curator_run', 'curator_action', 'curator_error',
'job_run', 'job_error',
'workflow_call_started', 'workflow_call_finished',
'turn_completed', 'work_request_submitted'
]::text[]) THEN 'automation'
ELSE 'runtime'
END AS category,
4 AS source_rank,
e.id::bigint AS source_id,
e.at,
e.actor_id AS actor,
e.actor_kind,
e.principal_id,
CASE WHEN e.task_id > 0 THEN 'task' ELSE '' END AS target_kind,
(CASE WHEN e.task_id > 0 THEN e.task_id::text ELSE '' END)::text AS target_id,
e.kind,
0::bigint AS record_version,
''::text AS request_id,
''::text AS source,
'{}'::jsonb AS fields,
e.kind AS action,
CASE
WHEN e.kind = ANY(ARRAY[
'task_dead', 'pr_rejected',
'operator_rejected', 'agent_rejected', 'task_rejected',
'task_abandoned', 'task_withdrawn', 'step_retried',
'curator_error', 'job_error', 'binding_dispatch_failure'
]::text[]) THEN 'error'
WHEN e.kind = ANY(ARRAY[
'parked', 'task_retried', 'task_cancelled', 'task_stopped',
'alert', 'update_report'
]::text[]) THEN 'warning'
ELSE 'info'
END AS severity,
CASE
WHEN e.kind = ANY(ARRAY[
'task_dead', 'pr_rejected',
'operator_rejected', 'agent_rejected', 'task_rejected',
'task_abandoned', 'task_withdrawn', 'step_retried',
'curator_error', 'job_error', 'binding_dispatch_failure'
]::text[]) THEN 'failure'
ELSE 'success'
END AS outcome,
e.detail,
concat_ws(' ', e.kind, e.actor_id, e.actor_kind, e.repo, e.workflow, e.stage, e.task_id::text) AS search_text,
e.workspace_id,
e.task_id,
e.data AS data_text
FROM events e
WHERE e.org_id = sqlc.arg(org_id)::text
AND (sqlc.narg(from_at)::timestamptz IS NULL OR e.at >= sqlc.narg(from_at)::timestamptz)
AND (sqlc.narg(to_at)::timestamptz IS NULL OR e.at < sqlc.narg(to_at)::timestamptz)
) se
WHERE (COALESCE(cardinality(sqlc.arg(categories)::text[]), 0) = 0 OR se.category = ANY(sqlc.arg(categories)::text[]))
AND (COALESCE(cardinality(sqlc.arg(actions)::text[]), 0) = 0 OR se.action = ANY(sqlc.arg(actions)::text[]))
AND (COALESCE(cardinality(sqlc.arg(kinds)::text[]), 0) = 0 OR se.kind = ANY(sqlc.arg(kinds)::text[]))
AND (sqlc.narg(actor)::text IS NULL OR se.actor = sqlc.narg(actor)::text)
AND (COALESCE(cardinality(sqlc.arg(target_kinds)::text[]), 0) = 0 OR se.target_kind = ANY(sqlc.arg(target_kinds)::text[]))
AND (COALESCE(cardinality(sqlc.arg(target_ids)::text[]), 0) = 0 OR se.target_id = ANY(sqlc.arg(target_ids)::text[]))
AND (COALESCE(cardinality(sqlc.arg(severities)::text[]), 0) = 0 OR se.severity = ANY(sqlc.arg(severities)::text[]))
AND (COALESCE(cardinality(sqlc.arg(outcomes)::text[]), 0) = 0 OR se.outcome = ANY(sqlc.arg(outcomes)::text[]))
AND (sqlc.narg(q)::text IS NULL OR position(lower(sqlc.narg(q)::text) IN lower(se.search_text)) > 0)
AND (
sqlc.narg(cursor_at)::timestamptz IS NULL
OR se.at < sqlc.narg(cursor_at)::timestamptz
OR (se.at = sqlc.narg(cursor_at)::timestamptz AND se.source_rank < sqlc.arg(cursor_rank)::int)
OR (se.at = sqlc.narg(cursor_at)::timestamptz AND se.source_rank = sqlc.arg(cursor_rank)::int AND se.source_id < sqlc.arg(cursor_id)::bigint)
)
ORDER BY se.at DESC, se.source_rank DESC, se.source_id DESC
LIMIT sqlc.arg(page_limit)::bigint
) b4
UNION ALL
SELECT * FROM (
SELECT * FROM (
SELECT
g.org_id,
CASE
WHEN g.table_name IN ('memberships', 'org_agents') THEN 'access'
WHEN g.table_name IN ('bindings', 'mappings', 'event_types') THEN 'automation'
ELSE 'settings'
END AS category,
5 AS source_rank,
g.source_id,
g.at,
g.actor,
''::text AS actor_kind,
''::text AS principal_id,
g.table_name::text AS target_kind,
g.record_key::text AS target_id,
g.table_name AS kind,
g.record_version,
g.request_id,
g.source,
g.fields,
CASE
WHEN g.field_count = 1 AND g.whole_record_field AND g.all_old_null THEN 'create'
WHEN g.field_count = 1 AND g.whole_record_field AND g.all_new_null THEN 'delete'
ELSE 'update'
END AS action,
CASE
WHEN g.field_count = 1 AND g.whole_record_field AND g.all_new_null
AND NOT g.all_old_null THEN 'warning'
ELSE 'info'
END AS severity,
'success'::text AS outcome,
''::text AS detail,
concat_ws(' ', g.record_key, g.actor, g.source, g.field_names, g.table_name) AS search_text,
''::text AS workspace_id,
0::bigint AS task_id,
''::text AS data_text
FROM sys_changes g
WHERE g.table_name NOT IN ('resources', 'access_policies')
) sg
WHERE (COALESCE(cardinality(sqlc.arg(categories)::text[]), 0) = 0 OR sg.category = ANY(sqlc.arg(categories)::text[]))
AND (COALESCE(cardinality(sqlc.arg(actions)::text[]), 0) = 0 OR sg.action = ANY(sqlc.arg(actions)::text[]))
AND (COALESCE(cardinality(sqlc.arg(kinds)::text[]), 0) = 0 OR sg.kind = ANY(sqlc.arg(kinds)::text[]))
AND (sqlc.narg(actor)::text IS NULL OR sg.actor = sqlc.narg(actor)::text)
AND (COALESCE(cardinality(sqlc.arg(target_kinds)::text[]), 0) = 0 OR sg.target_kind = ANY(sqlc.arg(target_kinds)::text[]))
AND (COALESCE(cardinality(sqlc.arg(target_ids)::text[]), 0) = 0 OR sg.target_id = ANY(sqlc.arg(target_ids)::text[]))
AND (COALESCE(cardinality(sqlc.arg(severities)::text[]), 0) = 0 OR sg.severity = ANY(sqlc.arg(severities)::text[]))
AND (COALESCE(cardinality(sqlc.arg(outcomes)::text[]), 0) = 0 OR sg.outcome = ANY(sqlc.arg(outcomes)::text[]))
AND (sqlc.narg(q)::text IS NULL OR position(lower(sqlc.narg(q)::text) IN lower(sg.search_text)) > 0)
AND (
sqlc.narg(cursor_at)::timestamptz IS NULL
OR sg.at < sqlc.narg(cursor_at)::timestamptz
OR (sg.at = sqlc.narg(cursor_at)::timestamptz AND sg.source_rank < sqlc.arg(cursor_rank)::int)
OR (sg.at = sqlc.narg(cursor_at)::timestamptz AND sg.source_rank = sqlc.arg(cursor_rank)::int AND sg.source_id < sqlc.arg(cursor_id)::bigint)
)
ORDER BY sg.at DESC, sg.source_rank DESC, sg.source_id DESC
LIMIT sqlc.arg(page_limit)::bigint
) merged
ORDER BY merged.at DESC, merged.source_rank DESC, merged.source_id DESC
LIMIT sqlc.arg(page_limit)::bigint;
-- name: AuditHead :one
-- A token over the newest id of each trail the caller can read, plus the
-- denials' count sum because a coalesced denial bumps its count in place
-- without drawing a new id. It carries no rows and no org data.
SELECT
(SELECT COALESCE(max(id), 0)::bigint FROM sys_audit WHERE org_id = sqlc.arg(org_id)::text) AS sys_audit_id,
(SELECT COALESCE(max(id), 0)::bigint FROM identity_events
WHERE (sqlc.arg(instance_admin)::boolean
OR (org_id IS NOT NULL AND org_id = sqlc.arg(org_id)::text))) AS identity_event_id,
(SELECT COALESCE(max(id), 0)::bigint FROM access_denials WHERE org_id = sqlc.arg(org_id)::text) AS access_denial_id,
(SELECT COALESCE(sum(count), 0)::bigint FROM access_denials WHERE org_id = sqlc.arg(org_id)::text) AS access_denial_count,
(SELECT COALESCE(max(id), 0)::bigint FROM events WHERE org_id = sqlc.arg(org_id)::text) AS event_id;
@@ -41,8 +41,20 @@ INSERT INTO identity_aliases (alias, identity_id) VALUES ($1, $2);
INSERT INTO identity_aliases (alias, identity_id) VALUES ($1, $2) ON CONFLICT DO NOTHING;
-- name: InsertIdentityEvent :exec
INSERT INTO identity_events (identity_id, event_type, from_lifecycle, to_lifecycle, display_name, actor_id, source, request_id, at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9);
INSERT INTO identity_events (identity_id, event_type, from_lifecycle, to_lifecycle, display_name, actor_id, source, request_id, at, org_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10);
-- name: IdentityAuditOrg :one
-- The identity's org only when it belongs to exactly one, across memberships
-- and agent assignments; no row otherwise. One statement, so a concurrent
-- membership add cannot make the count and the org disagree.
SELECT min(org_id)::text AS org_id
FROM (
SELECT m.org_id FROM memberships m WHERE m.identity_id = $1
UNION
SELECT a.org_id FROM org_agents a WHERE a.identity_id = $1
) belonging
HAVING count(DISTINCT org_id) = 1;
-- name: UpdateIdentity :execrows
UPDATE identities SET display_name = $2, lifecycle = $3, version = $4, updated_at = $5