From daa7ccb249aa5d1265b4cd69e9908e030e8ae419 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 25 Oct 2026 21:35:19 +1100 Subject: [PATCH] fix(state): attribute identity events to the subject's single org --- internal/infrastructure/postgres/accounts.go | 2 +- .../infrastructure/postgres/identities.go | 61 ++++++++++++++++--- .../migrations/0063_identity_event_org.sql | 40 ++++++++---- .../postgres/postgresdb/identities.sql.go | 36 +++++++++++ .../postgres/queries/identities.sql | 20 ++++++ 5 files changed, 137 insertions(+), 22 deletions(-) diff --git a/internal/infrastructure/postgres/accounts.go b/internal/infrastructure/postgres/accounts.go index a3ac7c22c..931a04c3f 100644 --- a/internal/infrastructure/postgres/accounts.go +++ b/internal/infrastructure/postgres/accounts.go @@ -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), orgID, 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 } diff --git a/internal/infrastructure/postgres/identities.go b/internal/infrastructure/postgres/identities.go index 4d4df8b81..25701b82f 100644 --- a/internal/infrastructure/postgres/identities.go +++ b/internal/infrastructure/postgres/identities.go @@ -24,25 +24,66 @@ 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. orgID is -// the org the event acts in, recorded on the row so the org's timeline keeps a -// removed member's earlier lifecycle events. -func insertIdentityEvent(ctx context.Context, q *postgresdb.Queries, orgID org.OrgID, 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) { + count, err := q.IdentityAuditOrgCount(ctx, string(id)) + if err != nil { + return "", fmt.Errorf("identity audit org count: %w", err) + } + switch { + case count > 1: + return "", nil + case count == 1: + orgID, err := q.IdentityAuditOrg(ctx, string(id)) + if err != nil { + return "", fmt.Errorf("identity audit org: %w", err) + } + return org.OrgID(orgID), nil + default: + return fallback, 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) } - // New events always name their org. Only historical rows, backfilled before - // an org was recorded, may be NULL. - if orgID == "" { - orgID = org.DefaultOrgID + 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: pgtype.Text{String: string(orgID), Valid: true}, + OrgID: storedOrg, }) } diff --git a/internal/infrastructure/postgres/migrations/0063_identity_event_org.sql b/internal/infrastructure/postgres/migrations/0063_identity_event_org.sql index 1bf6d7b18..f46eb73b7 100644 --- a/internal/infrastructure/postgres/migrations/0063_identity_event_org.sql +++ b/internal/infrastructure/postgres/migrations/0063_identity_event_org.sql @@ -4,23 +4,41 @@ -- 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 membership in effect at an event is the --- latest one created at or before it. An agent belongs to one org, so its --- assignment is the next best answer. A row with neither stays NULL and is --- visible only to an instance administrator: attributing it to the system org --- would show one org's history to every non-admin member of that org. +-- 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 = COALESCE( - (SELECT m.org_id FROM memberships m - WHERE m.identity_id = ie.identity_id AND m.created_at <= ie.at - ORDER BY m.created_at DESC LIMIT 1), - (SELECT a.org_id FROM org_agents a WHERE a.identity_id = ie.identity_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. diff --git a/internal/infrastructure/postgres/postgresdb/identities.sql.go b/internal/infrastructure/postgres/postgresdb/identities.sql.go index 1796af797..7b327952f 100644 --- a/internal/infrastructure/postgres/postgresdb/identities.sql.go +++ b/internal/infrastructure/postgres/postgresdb/identities.sql.go @@ -104,6 +104,42 @@ 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 +` + +// The identity's org, read only when IdentityAuditOrgCount returns one. +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 identityAuditOrgCount = `-- name: IdentityAuditOrgCount :one +SELECT count(DISTINCT org_id)::int AS org_count +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 +` + +// How many distinct orgs one identity belongs to, across memberships and agent +// assignments. Exactly one makes its events attributable to that org; two or +// more mean an event is not attributable to a single org. +func (q *Queries) IdentityAuditOrgCount(ctx context.Context, identityID string) (int32, error) { + row := q.db.QueryRow(ctx, identityAuditOrgCount, identityID) + var org_count int32 + err := row.Scan(&org_count) + return org_count, 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) diff --git a/internal/infrastructure/postgres/queries/identities.sql b/internal/infrastructure/postgres/queries/identities.sql index 75a901302..14c2a4eb1 100644 --- a/internal/infrastructure/postgres/queries/identities.sql +++ b/internal/infrastructure/postgres/queries/identities.sql @@ -44,6 +44,26 @@ INSERT INTO identity_aliases (alias, identity_id) VALUES ($1, $2) ON CONFLICT DO 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: IdentityAuditOrgCount :one +-- How many distinct orgs one identity belongs to, across memberships and agent +-- assignments. Exactly one makes its events attributable to that org; two or +-- more mean an event is not attributable to a single org. +SELECT count(DISTINCT org_id)::int AS org_count +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; + +-- name: IdentityAuditOrg :one +-- The identity's org, read only when IdentityAuditOrgCount returns 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; + -- name: UpdateIdentity :execrows UPDATE identities SET display_name = $2, lifecycle = $3, version = $4, updated_at = $5 WHERE id = $1 AND version = $6;