Files
archie/internal/store/identities.go
T
sam a7d6f71d5a feat(identity): verify provider tokens and attribute task actions to their actor
Two halves of one boundary: a credential resolves to an identity, and an action
records which identity acted and whose authority it used.

resource server. internal/infrastructure/oidc verifies a provider-issued bearer
token against the provider's published keys, using an OSS OIDC library: archie
compares no signature, validates no claim and rotates no key itself, holds no
client secret and issues no session, so a compromised archie cannot mint an
identity. Audience is required rather than optional -- a token minted for another
service must not authenticate here -- and discovery happens at construction, so an
unreachable provider is a startup failure rather than a request-time surprise.

identity.Authenticate is the single place a credential becomes an identity, and it
refuses in four distinguishable ways: no credential presented, a credential that
did not verify (wrong key, expired, wrong issuer, wrong audience, malformed), a
verified subject with no identity bound to it, and an identity that may not act.
The order is deliberate: verification happens before any field of the token is
used, so nothing an unverified token carries can select an identity. A suspended
identity is refused even though its credential verified, because suspension is
archie's decision and must not depend on the provider withdrawing a token.

The binding is the second bridge beside the legacy-name alias: identity_subjects
keys (issuer, subject) so the same subject string from another issuer is a
different caller, and rebinding moves a subject so two identities can never claim
one provider subject. The contract Authenticate needs is SubjectResolver, narrower
than Repository, so a consumer that only authenticates does not take the whole
identity CRUD surface -- and staterpc.Client, which asserts Repository, does not
need a new RPC to satisfy it.

attribution. taskactions now records two identities per action: the acting
identity and the authorising principal, both on the event row as new columns added
through the existing migration table. The rule that the bug turned on is enforced
by the event kind describing the actor: a person's approval is human_approved, an
agent's is agent_approved, and an action with no verified actor is task_approved,
a task-level event that credits nobody. An agent acting under a person's standing
approval records itself as the actor and that person as the principal, so
"approved by came from me" is answerable from the record rather than asserted.
Scope and actor are separated: scope decides which task a caller may touch and is
never promoted into an actor, because the dashboard's credential is a shared token
and possession of it is not evidence that a person was at the keyboard.

That last point is a deliberate fidelity trade, and the reason the transport is
not wired: the dashboard action path passes no actor yet, so dashboard approvals
are now recorded as task_approved rather than claimed as a human's. Recording
nothing false is the requirement; naming the human verifiably needs the dashboard
to authenticate a token and resolve it, which needs two new state-store RPCs
(ResolveIdentitySubject, BindIdentitySubject) -- the next piece, not a rewrite:
the verifier is a one-method interface, so introspection would be a second
implementation of it.

Verified: task check exit 0; focused runs recorded in the handoff. Opaque
authelia_at_ tokens were inspected rather than assumed and cannot be verified
against public keys; infra is configuring access_token_signed_response_alg RS256
on the archie client, with audience https://archie.catlow.cloud and issuer
https://auth.catlow.cloud.
2026-09-22 14:34:16 +10:00

253 lines
10 KiB
Go

package store
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
const identitiesSchema = `
CREATE TABLE IF NOT EXISTS identities (
id TEXT PRIMARY KEY NOT NULL, kind TEXT NOT NULL, display_name TEXT NOT NULL,
lifecycle TEXT NOT NULL, version INTEGER NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS identity_aliases (
alias TEXT PRIMARY KEY COLLATE NOCASE NOT NULL, identity_id TEXT NOT NULL REFERENCES identities(id)
);
CREATE TABLE IF NOT EXISTS identity_events (
id INTEGER PRIMARY KEY AUTOINCREMENT, identity_id TEXT NOT NULL, event_type TEXT NOT NULL,
from_lifecycle TEXT NOT NULL, to_lifecycle TEXT NOT NULL, display_name TEXT NOT NULL,
actor_id TEXT NOT NULL, source TEXT NOT NULL, request_id TEXT NOT NULL UNIQUE, at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS identity_subjects (
issuer TEXT NOT NULL, subject TEXT NOT NULL, identity_id TEXT NOT NULL REFERENCES identities(id),
bound_at TEXT NOT NULL, PRIMARY KEY (issuer, subject)
);`
const identityTimeLayout = time.RFC3339Nano
func (s *Store) List(ctx context.Context) (_ []identity.Identity, retErr error) {
rows, err := s.db.QueryContext(ctx, `SELECT id, kind, display_name, lifecycle, version, created_at, updated_at FROM identities ORDER BY created_at, id`)
if err != nil {
return nil, err
}
defer func() { retErr = errors.Join(retErr, rows.Close()) }()
var out []identity.Identity
for rows.Next() {
value, err := scanIdentity(rows)
if err != nil {
return nil, err
}
out = append(out, value)
}
return out, rows.Err()
}
func (s *Store) Get(ctx context.Context, id identity.IdentityID) (identity.Identity, error) {
value, err := scanIdentity(s.db.QueryRowContext(ctx, `SELECT id, kind, display_name, lifecycle, version, created_at, updated_at FROM identities WHERE id=?`, id))
if errors.Is(err, sql.ErrNoRows) {
return identity.Identity{}, identity.ErrNotFound
}
return value, err
}
func (s *Store) ResolveLegacyName(ctx context.Context, name string) (identity.Identity, error) {
value, err := scanIdentity(s.db.QueryRowContext(ctx, `SELECT i.id, i.kind, i.display_name, i.lifecycle, i.version, i.created_at, i.updated_at FROM identities i JOIN identity_aliases a ON a.identity_id=i.id WHERE a.alias=?`, strings.TrimSpace(name)))
if errors.Is(err, sql.ErrNoRows) {
return identity.Identity{}, identity.ErrNotFound
}
return value, err
}
func (s *Store) Create(ctx context.Context, value identity.Identity, audit identity.Audit) (identity.Identity, error) {
if err := value.Validate(); err != nil {
return identity.Identity{}, err
}
now := audit.At.UTC()
if now.IsZero() {
now = time.Now().UTC()
}
value.Version, value.CreatedAt, value.UpdatedAt = 1, now, now
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return identity.Identity{}, err
}
defer func() { _ = tx.Rollback() }()
if _, err = tx.ExecContext(ctx, `INSERT INTO identities(id,kind,display_name,lifecycle,version,created_at,updated_at) VALUES(?,?,?,?,?,?,?)`, value.ID, value.Kind, value.DisplayName, value.Lifecycle, value.Version, now.Format(identityTimeLayout), now.Format(identityTimeLayout)); err != nil {
return identity.Identity{}, err
}
if _, err = tx.ExecContext(ctx, `INSERT INTO identity_aliases(alias,identity_id) VALUES(?,?)`, value.DisplayName, value.ID); err != nil {
return identity.Identity{}, err
}
if err = insertIdentityEvent(ctx, tx, value, identity.Event{IdentityID: value.ID, Type: "create", To: value.Lifecycle, DisplayName: value.DisplayName}, audit, now); err != nil {
return identity.Identity{}, err
}
return value, tx.Commit()
}
func (s *Store) Apply(ctx context.Context, id identity.IdentityID, expectedVersion int64, command identity.Command, audit identity.Audit) (identity.Identity, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return identity.Identity{}, err
}
defer func() { _ = tx.Rollback() }()
current, err := scanIdentity(tx.QueryRowContext(ctx, `SELECT id, kind, display_name, lifecycle, version, created_at, updated_at FROM identities WHERE id=?`, id))
if errors.Is(err, sql.ErrNoRows) {
return identity.Identity{}, identity.ErrNotFound
}
if err != nil {
return identity.Identity{}, err
}
if current.Version != expectedVersion {
return identity.Identity{}, identity.ErrConflict
}
next, event, err := identity.Apply(current, command)
if err != nil {
return identity.Identity{}, err
}
now := audit.At.UTC()
if now.IsZero() {
now = time.Now().UTC()
}
next.UpdatedAt = now
result, err := tx.ExecContext(ctx, `UPDATE identities SET display_name=?, lifecycle=?, version=?, updated_at=? WHERE id=? AND version=?`, next.DisplayName, next.Lifecycle, next.Version, now.Format(identityTimeLayout), id, expectedVersion)
if err != nil {
return identity.Identity{}, err
}
changed, _ := result.RowsAffected()
if changed != 1 {
return identity.Identity{}, identity.ErrConflict
}
if command.Type == identity.CommandRename {
if _, err = tx.ExecContext(ctx, `INSERT OR IGNORE INTO identity_aliases(alias,identity_id) VALUES(?,?)`, next.DisplayName, id); err != nil {
return identity.Identity{}, err
}
}
if err = insertIdentityEvent(ctx, tx, next, event, audit, now); err != nil {
return identity.Identity{}, err
}
return next, tx.Commit()
}
// ResolveSubject returns the identity bound to a provider subject, so a
// credential that verified against the provider's keys selects an identity
// archie already knows rather than creating one.
func (s *Store) ResolveSubject(ctx context.Context, subject identity.Subject) (identity.Identity, error) {
value, err := scanIdentity(s.db.QueryRowContext(ctx, `SELECT i.id, i.kind, i.display_name, i.lifecycle, i.version, i.created_at, i.updated_at FROM identities i JOIN identity_subjects b ON b.identity_id=i.id WHERE b.issuer=? AND b.subject=?`, subject.Issuer, subject.Subject))
if errors.Is(err, sql.ErrNoRows) {
return identity.Identity{}, identity.ErrNotFound
}
return value, err
}
// BindSubject binds an identity to the provider subject that asserts it. The
// binding is audited like any other identity mutation: who authorised a caller
// to act as this identity is the question the record has to answer later.
// Rebinding an already-bound subject moves it, because a subject that changed
// hands must resolve to whoever it belongs to now.
func (s *Store) BindSubject(ctx context.Context, id identity.IdentityID, subject identity.Subject, audit identity.Audit) error {
if err := subject.Validate(); err != nil {
return err
}
if audit.ActorID == "" || audit.Source == "" || audit.RequestID == "" {
return fmt.Errorf("%w: audit actor, source, and request ID are required", identity.ErrInvalid)
}
now := audit.At.UTC()
if now.IsZero() {
now = time.Now().UTC()
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
current, err := scanIdentity(tx.QueryRowContext(ctx, `SELECT id, kind, display_name, lifecycle, version, created_at, updated_at FROM identities WHERE id=?`, id))
if errors.Is(err, sql.ErrNoRows) {
return identity.ErrNotFound
}
if err != nil {
return err
}
if _, err = tx.ExecContext(ctx, `INSERT INTO identity_subjects(issuer,subject,identity_id,bound_at) VALUES(?,?,?,?) ON CONFLICT(issuer,subject) DO UPDATE SET identity_id=excluded.identity_id, bound_at=excluded.bound_at`, subject.Issuer, subject.Subject, id, now.Format(identityTimeLayout)); err != nil {
return err
}
if err = insertIdentityEvent(ctx, tx, current, identity.Event{IdentityID: id, Type: "bind_subject", From: current.Lifecycle, To: current.Lifecycle, DisplayName: subject.Subject}, audit, now); err != nil {
return err
}
return tx.Commit()
}
func (s *Store) BootstrapIdentities(ctx context.Context, legacyNames []string) error {
values := append([]struct {
id identity.IdentityID
kind identity.Kind
name string
}{{identity.SystemID, identity.KindSystem, "System"}}, make([]struct {
id identity.IdentityID
kind identity.Kind
name string
}, len(legacyNames))...)
for i, name := range legacyNames {
name = strings.TrimSpace(name)
values[i+1] = struct {
id identity.IdentityID
kind identity.Kind
name string
}{identity.StableID(name), identity.KindBot, name}
}
for _, seed := range values {
if seed.name == "" {
continue
}
value, err := identity.New(seed.id, seed.kind, seed.name)
if err != nil {
return err
}
_, err = s.Create(ctx, value, identity.Audit{ActorID: identity.SystemID, Source: "legacy-config", RequestID: "identity-import:" + string(seed.id)})
if err != nil && !isSQLiteUnique(err) {
return fmt.Errorf("bootstrap identity %q: %w", seed.name, err)
}
if _, aliasErr := s.db.ExecContext(ctx, `INSERT OR IGNORE INTO identity_aliases(alias,identity_id) VALUES(?,?)`, seed.name, seed.id); aliasErr != nil {
return aliasErr
}
if seed.kind != identity.KindSystem {
if _, migrateErr := s.db.ExecContext(ctx, `UPDATE tasks SET identity=? WHERE identity=?`, seed.id, seed.name); migrateErr != nil {
return migrateErr
}
}
}
return nil
}
type identityScanner interface{ Scan(...any) error }
func scanIdentity(row identityScanner) (identity.Identity, error) {
var v identity.Identity
var created, updated string
err := row.Scan(&v.ID, &v.Kind, &v.DisplayName, &v.Lifecycle, &v.Version, &created, &updated)
if err != nil {
return v, err
}
v.CreatedAt, err = time.Parse(identityTimeLayout, created)
if err != nil {
return v, err
}
v.UpdatedAt, err = time.Parse(identityTimeLayout, updated)
return v, err
}
func insertIdentityEvent(ctx context.Context, tx *sql.Tx, value identity.Identity, event 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)
}
_, err := tx.ExecContext(ctx, `INSERT INTO identity_events(identity_id,event_type,from_lifecycle,to_lifecycle,display_name,actor_id,source,request_id,at) VALUES(?,?,?,?,?,?,?,?,?)`, value.ID, event.Type, event.From, event.To, event.DisplayName, audit.ActorID, audit.Source, audit.RequestID, at.Format(identityTimeLayout))
return err
}
func isSQLiteUnique(err error) bool { return strings.Contains(err.Error(), "UNIQUE constraint failed") }