Files
archie/modules/governance/internal/store/identities.go
T
sam 0218e4ec89 feat(governance): move identity, org and Cedar access engine into governance (#2017)
Copied from internal/domain/identity, internal/domain/org, internal/domain/access, internal/infrastructure/access and internal/infrastructure/postgres.
2026-11-18 02:09:29 +11:00

389 lines
14 KiB
Go

package store
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
"github.com/jmoiron/sqlx"
)
// IdentityRow is a persistent actor in governance.identities.
type IdentityRow struct {
ID string `db:"id"`
Kind string `db:"kind"`
DisplayName string `db:"display_name"`
Lifecycle string `db:"lifecycle"`
Version int64 `db:"version"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
}
// IdentityEventRow is an audit event in governance.identity_events.
type IdentityEventRow struct {
IdentityID string `db:"identity_id"`
EventType string `db:"event_type"`
FromLifecycle string `db:"from_lifecycle"`
ToLifecycle string `db:"to_lifecycle"`
DisplayName string `db:"display_name"`
ActorID string `db:"actor_id"`
Source string `db:"source"`
RequestID string `db:"request_id"`
At time.Time `db:"at"`
OrgID sql.NullString `db:"org_id"`
}
// SubjectRow is a provider or personal-token subject binding in governance.identity_subjects.
type SubjectRow struct {
Issuer string `db:"issuer"`
Subject string `db:"subject"`
IdentityID string `db:"identity_id"`
BoundAt time.Time `db:"bound_at"`
Name string `db:"name"`
ExpiresAt sql.NullTime `db:"expires_at"`
LastUsedAt sql.NullTime `db:"last_used_at"`
}
const identityCols = `id, kind, display_name, lifecycle, version, created_at, updated_at`
func auditSubjectOrg(ctx context.Context, tx *sqlx.Tx, fallbackOrg, identityID string) (sql.NullString, error) {
var single string
err := tx.GetContext(ctx, &single, `
SELECT min(org_id)::text AS org_id
FROM (
SELECT m.org_id FROM governance.memberships m WHERE m.identity_id = $1
UNION
SELECT a.org_id FROM governance.org_agents a WHERE a.identity_id = $1
) belonging
HAVING count(DISTINCT org_id) = 1`, identityID)
switch {
case err == nil && single != "":
return sql.NullString{String: single, Valid: true}, nil
case errors.Is(err, sql.ErrNoRows) || err == nil:
if fallbackOrg == "" {
return sql.NullString{}, nil
}
return sql.NullString{String: fallbackOrg, Valid: true}, nil
default:
return sql.NullString{}, fmt.Errorf("identity audit org: %w", err)
}
}
func insertIdentityEvent(ctx context.Context, tx *sqlx.Tx, ev IdentityEventRow) error {
_, err := tx.ExecContext(ctx, `
INSERT INTO governance.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)`,
ev.IdentityID, ev.EventType, ev.FromLifecycle, ev.ToLifecycle, ev.DisplayName,
ev.ActorID, ev.Source, ev.RequestID, ev.At, ev.OrgID)
return err
}
func getVisibleIdentityTx(ctx context.Context, q sqlx.ExtContext, id string, scopeOrg *string) (IdentityRow, error) {
var out IdentityRow
err := sqlx.GetContext(ctx, q, &out, `
SELECT `+identityCols+` FROM governance.identities
WHERE id = $1 AND ($2::text IS NULL
OR EXISTS (SELECT 1 FROM governance.memberships m WHERE m.identity_id = governance.identities.id AND m.org_id = $2::text)
OR EXISTS (SELECT 1 FROM governance.org_agents a WHERE a.identity_id = governance.identities.id AND a.org_id = $2::text))`,
id, scopeOrg)
if errors.Is(err, sql.ErrNoRows) {
return IdentityRow{}, ErrNotFound
}
return out, err
}
// ListIdentities returns identities visible to scopeOrg (or all when nil).
func (s *Store) ListIdentities(ctx context.Context, scopeOrg *string) ([]IdentityRow, error) {
var out []IdentityRow
if err := s.db.SelectContext(ctx, &out, `
SELECT `+identityCols+` FROM governance.identities
WHERE ($1::text IS NULL
OR EXISTS (SELECT 1 FROM governance.memberships m WHERE m.identity_id = governance.identities.id AND m.org_id = $1::text)
OR EXISTS (SELECT 1 FROM governance.org_agents a WHERE a.identity_id = governance.identities.id AND a.org_id = $1::text))
ORDER BY created_at, id`, scopeOrg); err != nil {
return nil, fmt.Errorf("list identities: %w", err)
}
return out, nil
}
// GetIdentity returns one identity by ID without org filtering.
func (s *Store) GetIdentity(ctx context.Context, id string) (IdentityRow, error) {
var out IdentityRow
err := s.db.GetContext(ctx, &out, `SELECT `+identityCols+` FROM governance.identities WHERE id = $1`, id)
if errors.Is(err, sql.ErrNoRows) {
return IdentityRow{}, ErrNotFound
}
return out, err
}
// GetVisibleIdentity returns one identity if visible to scopeOrg.
func (s *Store) GetVisibleIdentity(ctx context.Context, id string, scopeOrg *string) (IdentityRow, error) {
return getVisibleIdentityTx(ctx, s.db, id, scopeOrg)
}
// ResolveIdentityAlias resolves a display-name alias case-insensitively within scopeOrg.
func (s *Store) ResolveIdentityAlias(ctx context.Context, alias string, scopeOrg *string) (IdentityRow, error) {
var out IdentityRow
err := s.db.GetContext(ctx, &out, `
SELECT i.id, i.kind, i.display_name, i.lifecycle, i.version, i.created_at, i.updated_at
FROM governance.identities i
JOIN governance.identity_aliases a ON a.identity_id = i.id
WHERE lower(a.alias) = lower($1) AND ($2::text IS NULL
OR EXISTS (SELECT 1 FROM governance.memberships m WHERE m.identity_id = i.id AND m.org_id = $2::text)
OR EXISTS (SELECT 1 FROM governance.org_agents a WHERE a.identity_id = i.id AND a.org_id = $2::text))`,
alias, scopeOrg)
if errors.Is(err, sql.ErrNoRows) {
return IdentityRow{}, ErrNotFound
}
return out, err
}
// CreateIdentity inserts an identity, its alias, its create event, and optionally assigns an agent.
func (s *Store) CreateIdentity(ctx context.Context, row IdentityRow, ev IdentityEventRow, fallbackOrg string, assignAgent bool) error {
return s.withTx(ctx, func(tx *sqlx.Tx) error {
if _, err := tx.ExecContext(ctx, `
INSERT INTO governance.identities (id, kind, display_name, lifecycle, version, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
row.ID, row.Kind, row.DisplayName, row.Lifecycle, row.Version, row.CreatedAt, row.UpdatedAt); err != nil {
if isUniqueViolation(err) {
return ErrAlreadyExists
}
return err
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO governance.identity_aliases (alias, identity_id) VALUES ($1, $2)`,
row.DisplayName, row.ID); err != nil {
return err
}
orgID, err := auditSubjectOrg(ctx, tx, fallbackOrg, row.ID)
if err != nil {
return err
}
ev.OrgID = orgID
if err := insertIdentityEvent(ctx, tx, ev); err != nil {
return err
}
if !assignAgent {
return nil
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO governance.org_agents (identity_id, org_id) VALUES ($1, $2)
ON CONFLICT (identity_id) DO UPDATE SET org_id = EXCLUDED.org_id`, row.ID, fallbackOrg); err != nil {
return err
}
_, err = tx.ExecContext(ctx, `
INSERT INTO governance.memberships (identity_id, org_id, role)
VALUES ($1, $2, 'developer')
ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO UPDATE SET role = EXCLUDED.role`,
row.ID, fallbackOrg)
return err
})
}
// ApplyIdentityTransition mutates an identity under an optimistic version guard.
func (s *Store) ApplyIdentityTransition(
ctx context.Context,
id string,
expectedVersion int64,
scopeOrg *string,
transition func(IdentityRow) (IdentityRow, IdentityEventRow, error),
) (IdentityRow, error) {
var out IdentityRow
err := s.withTx(ctx, func(tx *sqlx.Tx) error {
cur, err := getVisibleIdentityTx(ctx, tx, id, scopeOrg)
if err != nil {
return err
}
if cur.Version != expectedVersion {
return ErrAlreadyExists
}
next, ev, err := transition(cur)
if err != nil {
return err
}
if err := guardLeavingActive(ctx, tx, id, cur.Lifecycle, next.Lifecycle); err != nil {
return err
}
res, err := tx.ExecContext(ctx, `
UPDATE governance.identities
SET display_name = $2, lifecycle = $3, version = $4, updated_at = $5
WHERE id = $1 AND version = $6`,
id, next.DisplayName, next.Lifecycle, next.Version, next.UpdatedAt, expectedVersion)
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil || n != 1 {
return ErrAlreadyExists
}
if ev.EventType == "rename" {
if _, err := tx.ExecContext(ctx, `
INSERT INTO governance.identity_aliases (alias, identity_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
next.DisplayName, id); err != nil {
return err
}
}
orgID, err := auditSubjectOrg(ctx, tx, "", id)
if err != nil {
return err
}
ev.OrgID = orgID
if err := insertIdentityEvent(ctx, tx, ev); err != nil {
return err
}
out = next
return nil
})
return out, err
}
func guardLeavingActive(ctx context.Context, tx *sqlx.Tx, id, from, to string) error {
if to == "active" {
return nil
}
if from == "active" {
if err := keepActiveOwner(ctx, tx, id, ""); err != nil {
return err
}
}
_, err := tx.ExecContext(ctx, `DELETE FROM governance.account_sessions WHERE identity_id = $1`, id)
return err
}
// ResolveIdentitySubject returns the identity bound to a provider subject.
func (s *Store) ResolveIdentitySubject(ctx context.Context, issuer, subject string) (IdentityRow, error) {
var out IdentityRow
err := s.db.GetContext(ctx, &out, `
SELECT i.id, i.kind, i.display_name, i.lifecycle, i.version, i.created_at, i.updated_at
FROM governance.identities i
JOIN governance.identity_subjects b ON b.identity_id = i.id
WHERE b.issuer = $1 AND b.subject = $2`, issuer, subject)
if errors.Is(err, sql.ErrNoRows) {
return IdentityRow{}, ErrNotFound
}
return out, err
}
// ClaimIdentitySubject moves a placeholder subject binding onto a verified subject.
func (s *Store) ClaimIdentitySubject(ctx context.Context, issuer, placeholder, subject, reqID string, boundAt time.Time) (IdentityRow, error) {
var claimed IdentityRow
err := s.withTx(ctx, func(tx *sqlx.Tx) error {
var id string
err := tx.GetContext(ctx, &id, `
UPDATE governance.identity_subjects SET subject = $3, bound_at = $4
WHERE issuer = $1 AND subject = $2
RETURNING identity_id`, issuer, placeholder, subject, boundAt)
if errors.Is(err, sql.ErrNoRows) {
return ErrNotFound
}
if err != nil {
return err
}
if err := tx.GetContext(ctx, &claimed, `SELECT `+identityCols+` FROM governance.identities WHERE id = $1`, id); err != nil {
return err
}
orgID, err := auditSubjectOrg(ctx, tx, "", claimed.ID)
if err != nil {
return err
}
return insertIdentityEvent(ctx, tx, IdentityEventRow{
IdentityID: claimed.ID, EventType: "claim_subject",
FromLifecycle: claimed.Lifecycle, ToLifecycle: claimed.Lifecycle,
DisplayName: subject, ActorID: claimed.ID, Source: "sign-in",
RequestID: reqID, At: boundAt, OrgID: orgID,
})
})
return claimed, err
}
// UpsertIdentitySubject binds a subject or personal token to an identity.
func (s *Store) UpsertIdentitySubject(ctx context.Context, id string, scopeOrg *string, sub SubjectRow, ev IdentityEventRow) error {
return s.withTx(ctx, func(tx *sqlx.Tx) error {
cur, err := getVisibleIdentityTx(ctx, tx, id, scopeOrg)
if err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO governance.identity_subjects (issuer, subject, identity_id, bound_at, name, expires_at)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (issuer, subject) DO UPDATE
SET identity_id = EXCLUDED.identity_id, bound_at = EXCLUDED.bound_at,
name = EXCLUDED.name, expires_at = EXCLUDED.expires_at`,
sub.Issuer, sub.Subject, id, sub.BoundAt, sub.Name, sub.ExpiresAt); err != nil {
return err
}
orgID, err := auditSubjectOrg(ctx, tx, "", id)
if err != nil {
return err
}
ev.IdentityID, ev.FromLifecycle, ev.ToLifecycle, ev.OrgID = id, cur.Lifecycle, cur.Lifecycle, orgID
return insertIdentityEvent(ctx, tx, ev)
})
}
// ListIdentitySubjects lists an identity's subject bindings for issuer, newest first.
func (s *Store) ListIdentitySubjects(ctx context.Context, id, issuer string) ([]SubjectRow, error) {
var out []SubjectRow
if err := s.db.SelectContext(ctx, &out, `
SELECT issuer, subject, identity_id, bound_at, name, expires_at, last_used_at
FROM governance.identity_subjects
WHERE identity_id = $1 AND issuer = $2
ORDER BY bound_at DESC`, id, issuer); err != nil {
return nil, fmt.Errorf("list identity subjects: %w", err)
}
return out, nil
}
// GetIdentitySubject returns one subject binding row.
func (s *Store) GetIdentitySubject(ctx context.Context, issuer, subject string) (SubjectRow, error) {
var out SubjectRow
err := s.db.GetContext(ctx, &out, `
SELECT issuer, subject, identity_id, bound_at, name, expires_at, last_used_at
FROM governance.identity_subjects
WHERE issuer = $1 AND subject = $2`, issuer, subject)
if errors.Is(err, sql.ErrNoRows) {
return SubjectRow{}, ErrNotFound
}
return out, err
}
// TouchIdentitySubject updates last_used_at on a subject binding.
func (s *Store) TouchIdentitySubject(ctx context.Context, issuer, subject string, at time.Time) error {
_, err := s.db.ExecContext(ctx, `
UPDATE governance.identity_subjects SET last_used_at = $3 WHERE issuer = $1 AND subject = $2`,
issuer, subject, at)
return err
}
// DeleteIdentitySubject unbinds a subject or personal token from an identity.
func (s *Store) DeleteIdentitySubject(ctx context.Context, id string, scopeOrg *string, issuer, subject string, ev IdentityEventRow) error {
return s.withTx(ctx, func(tx *sqlx.Tx) error {
cur, err := getVisibleIdentityTx(ctx, tx, id, scopeOrg)
if err != nil {
return err
}
res, err := tx.ExecContext(ctx, `
DELETE FROM governance.identity_subjects WHERE identity_id = $1 AND issuer = $2 AND subject = $3`,
id, issuer, subject)
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil || n == 0 {
if err != nil {
return err
}
return ErrNotFound
}
orgID, err := auditSubjectOrg(ctx, tx, "", id)
if err != nil {
return err
}
ev.IdentityID, ev.FromLifecycle, ev.ToLifecycle, ev.OrgID = id, cur.Lifecycle, cur.Lifecycle, orgID
return insertIdentityEvent(ctx, tx, ev)
})
}