Files
archie/internal/infrastructure/postgres/identities.go
T
sam 03b43fc07b Feat/org epic (#1634)
* fix(postgres): scope OpenPRs to the caller's org

A principal-carrying caller read every org's pr_open tasks. The query now
honours the request scope; the daemon's unscoped review scan still sees all
orgs.

Issue: archie-core-kgxw.23

* fix(statestore): serve task logs only to the task's org

ReadTaskLog and StreamTaskLogContent took a task ID and read the file with
no org check. The State Store's task-log reader now confirms the task is
visible under the caller's scope first; unscoped services read as before.

Issue: archie-core-kgxw.24

* fix(postgres): scope ListPolicies to the caller's org

Every org's policy text reached any principal-carrying caller. A scoped read
now sees its own org's policies, plus instance policies when scoped to the
system org. The engines and the lockout guard decide for every org, so they
read the full chain unscoped: the dashboard engine loads without the
request's principal and the guard lifts the caller's scope.

Issue: archie-core-kgxw.25

* fix(postgres): scope identity reads to the caller's org

ListIdentities and GetIdentity (and its alias fallback) returned every
identity to any caller. A caller scoped to an org now sees only that org's
members and assigned agents; the system org and unscoped services still see
the whole instance.

Issue: archie-core-kgxw.26

* fix(postgres): hide instance status from other orgs

ListPresence, ListChannelStatus, ListApplyStatus and GetConfigSnapshot
answered any org principal with instance-wide state. They now return nothing
unless the request is unscoped or scoped to the system org. The dashboard
reads the published config as itself, since its handlers project it for
callers of every org.

Issue: archie-core-kgxw.27

* feat(postgres): assign new agents an org and role at creation

A bot or service account created through the API served no org until the
next State Store boot granted it one. Create now assigns it to the org the
request acts in with the developer role in the same transaction, so it is
authorized immediately.

Issue: archie-core-kgxw.14

* feat(edastore): create event records in a chosen workspace

Sources are created in a workspace of the caller's org, the default one when
none is named; event types and bindings take their source's workspace and
mappings their event type's, the same rule the org backfill applied. The
binding, mapping and event type contracts carry the workspace, the four list
endpoints accept ?workspace=, and the Events page has a workspace selector
that filters every step and picks where a new source goes.

Issue: archie-core-kgxw.11

* feat(webui): authorize a record in its workspace

The API built every access request with no workspace, so workspace
policies and per-workspace roles never applied. A request naming a source,
binding, mapping, event type or task now reads the record's workspace under
the caller's scope and authorizes in it; tasks carry their workspace on the
State Store contract for this.

Issue: archie-core-kgxw.9

* feat(access): expose workspace environment to policies

Policies can test resource.workspace.environment. The workspace attribute
is the workspace entity, which carries its environment; the principal
brings its org's workspaces from the State Store, so the dashboard and the
daemon's run checks describe a resource's workspace without another lookup,
and the daemon now authorizes runs in the task's or binding's workspace.

Issue: archie-core-kgxw.10

* fix(webui): ask read_secret when a source secret is read

Rotating a source's secret returns its value, but the route asked update,
which every developer holds, so no policy could narrow who reads a secret.
It now asks read_secret on the secret, which the shipped roles give admins
and an object policy can narrow further.

Issue: archie-core-kgxw.17

* refactor(org): delete the unused upgrade-incomplete sentinel

Nothing returns org.ErrUpgradeIncomplete: the State Store finishes the org
upgrade before it serves.

Issue: archie-core-kgxw.18
2026-10-12 03:24:04 +11:00

378 lines
13 KiB
Go

package postgres
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
// identityFromRow maps the generated identity row to the domain identity.
func identityFromRow(i postgresdb.Identity) identity.Identity {
return identity.Identity{
ID: identity.IdentityID(i.ID), Kind: identity.Kind(i.Kind),
DisplayName: i.DisplayName, Lifecycle: identity.Lifecycle(i.Lifecycle),
Version: i.Version, CreatedAt: i.CreatedAt, UpdatedAt: i.UpdatedAt,
}
}
// 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 {
if audit.ActorID == "" || audit.Source == "" || audit.RequestID == "" {
return fmt.Errorf("%w: audit actor, source, and request ID are required", identity.ErrInvalid)
}
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,
})
}
// List returns every identity the request's scope may see, oldest first.
func (s *Store) List(ctx context.Context) ([]identity.Identity, error) {
rows, err := s.queries().ListIdentities(ctx, memberScope(ctx))
if err != nil {
return nil, err
}
out := make([]identity.Identity, 0, len(rows))
for _, r := range rows {
out = append(out, identityFromRow(r))
}
return out, nil
}
// Get returns one identity by id, or ErrNotFound when there is none the
// request's scope may see.
func (s *Store) Get(ctx context.Context, id identity.IdentityID) (identity.Identity, error) {
i, err := s.queries().GetVisibleIdentity(ctx, postgresdb.GetVisibleIdentityParams{ID: string(id), ScopeOrg: memberScope(ctx)})
if errors.Is(err, pgx.ErrNoRows) {
return identity.Identity{}, identity.ErrNotFound
}
if err != nil {
return identity.Identity{}, err
}
return identityFromRow(i), nil
}
// ResolveLegacyName resolves a legacy display name through the aliases table.
// Aliases match case-insensitively, mirroring the SQLite schema's COLLATE
// NOCASE.
func (s *Store) ResolveLegacyName(ctx context.Context, name string) (identity.Identity, error) {
i, err := s.queries().ResolveIdentityAlias(ctx, postgresdb.ResolveIdentityAliasParams{Alias: strings.TrimSpace(name), ScopeOrg: memberScope(ctx)})
if errors.Is(err, pgx.ErrNoRows) {
return identity.Identity{}, identity.ErrNotFound
}
if err != nil {
return identity.Identity{}, err
}
return identityFromRow(i), nil
}
// Create inserts a new identity, its display-name alias and its create audit
// event in one transaction. An agent is assigned in the same transaction to
// the org the request acts in, with the shipped developer role, so it is
// authorized as soon as it exists.
func (s *Store) Create(ctx context.Context, value identity.Identity, audit identity.Audit) (identity.Identity, error) {
return s.create(ctx, value, audit, value.Kind.Agent())
}
// create inserts an identity, assigning an agent to the request's org when
// assign is set. Boot seeding does not assign: it runs before a fresh
// install's org exists, and the org upgrade assigns what it seeded.
func (s *Store) create(ctx context.Context, value identity.Identity, audit identity.Audit, assign bool) (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.pool.Begin(ctx)
if err != nil {
return identity.Identity{}, err
}
defer func() { _ = tx.Rollback(ctx) }()
q := postgresdb.New(tx)
if err := q.InsertIdentity(ctx, postgresdb.InsertIdentityParams{
ID: string(value.ID), Kind: string(value.Kind), DisplayName: value.DisplayName,
Lifecycle: string(value.Lifecycle), Version: value.Version, CreatedAt: now, UpdatedAt: now,
}); err != nil {
return identity.Identity{}, err
}
if err := q.InsertIdentityAlias(ctx, postgresdb.InsertIdentityAliasParams{
Alias: value.DisplayName, IdentityID: string(value.ID),
}); err != nil {
return identity.Identity{}, err
}
if err := insertIdentityEvent(ctx, q, value.ID, identity.Event{
IdentityID: value.ID, Type: "create", To: value.Lifecycle, DisplayName: value.DisplayName,
}, audit, now); err != nil {
return identity.Identity{}, err
}
if assign {
if err := assignNewAgent(ctx, q, value.ID, org.OrgFromContext(ctx)); err != nil {
return identity.Identity{}, err
}
}
if err := tx.Commit(ctx); err != nil {
return identity.Identity{}, err
}
return value, nil
}
// assignNewAgent makes a new agent serve orgID with the developer role.
func assignNewAgent(ctx context.Context, q *postgresdb.Queries, id identity.IdentityID, orgID org.OrgID) error {
if err := q.UpsertAgentAssignment(ctx, postgresdb.UpsertAgentAssignmentParams{
IdentityID: string(id), OrgID: string(orgID),
}); err != nil {
return fmt.Errorf("assign agent to org %s: %w", orgID, err)
}
return q.EnsureMembership(ctx, postgresdb.EnsureMembershipParams{
IdentityID: string(id), OrgID: string(orgID), Role: string(org.RoleDeveloper),
})
}
// Apply mutates an identity under an optimistic version guard and records the
// lifecycle event.
func (s *Store) Apply(ctx context.Context, id identity.IdentityID, expectedVersion int64, command identity.Command, audit identity.Audit) (identity.Identity, error) {
tx, err := s.pool.Begin(ctx)
if err != nil {
return identity.Identity{}, err
}
defer func() { _ = tx.Rollback(ctx) }()
q := postgresdb.New(tx)
current, err := q.GetIdentity(ctx, string(id))
if errors.Is(err, pgx.ErrNoRows) {
return identity.Identity{}, identity.ErrNotFound
}
if err != nil {
return identity.Identity{}, err
}
cur := identityFromRow(current)
if cur.Version != expectedVersion {
return identity.Identity{}, identity.ErrConflict
}
next, ev, err := identity.Apply(cur, command)
if err != nil {
return identity.Identity{}, err
}
now := audit.At.UTC()
if now.IsZero() {
now = time.Now().UTC()
}
next.UpdatedAt = now
n, err := q.UpdateIdentity(ctx, postgresdb.UpdateIdentityParams{
ID: string(id), DisplayName: next.DisplayName, Lifecycle: string(next.Lifecycle),
Version: next.Version, UpdatedAt: now, Version_2: expectedVersion,
})
if err != nil {
return identity.Identity{}, err
}
if n != 1 {
return identity.Identity{}, identity.ErrConflict
}
if command.Type == identity.CommandRename {
if err := q.InsertIdentityAliasIgnoreConflict(ctx, postgresdb.InsertIdentityAliasIgnoreConflictParams{
Alias: next.DisplayName, IdentityID: string(id),
}); err != nil {
return identity.Identity{}, err
}
}
if err := insertIdentityEvent(ctx, q, id, ev, audit, now); err != nil {
return identity.Identity{}, err
}
if err := tx.Commit(ctx); err != nil {
return identity.Identity{}, err
}
return next, nil
}
// ResolveSubject returns the identity bound to a provider subject.
func (s *Store) ResolveSubject(ctx context.Context, subject identity.Subject) (identity.Identity, error) {
i, err := s.queries().ResolveIdentitySubject(ctx, postgresdb.ResolveIdentitySubjectParams{
Issuer: subject.Issuer, Subject: subject.Subject,
})
if errors.Is(err, pgx.ErrNoRows) {
return identity.Identity{}, identity.ErrNotFound
}
if err != nil {
return identity.Identity{}, err
}
return identityFromRow(i), nil
}
// ClaimSubject moves a placeholder binding (a person added by email) onto
// the subject the provider asserts. The placeholder is gone afterwards, so a
// second account showing the same address finds nothing to claim.
func (s *Store) ClaimSubject(ctx context.Context, placeholder, subject identity.Subject) (identity.Identity, error) {
if err := subject.Validate(); err != nil {
return identity.Identity{}, err
}
now := time.Now().UTC()
var claimed identity.Identity
err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
q := postgresdb.New(tx)
id, err := q.ClaimIdentitySubject(ctx, postgresdb.ClaimIdentitySubjectParams{
Issuer: placeholder.Issuer, Placeholder: placeholder.Subject, Subject: subject.Subject, BoundAt: now,
})
if errors.Is(err, pgx.ErrNoRows) {
return identity.ErrNotFound
}
if err != nil {
return err
}
row, err := q.GetIdentity(ctx, id)
if err != nil {
return err
}
claimed = identityFromRow(row)
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)
})
return claimed, err
}
// BindSubject binds an identity to the provider subject that asserts it,
// moving any prior binding for that subject.
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.pool.Begin(ctx)
if err != nil {
return err
}
defer func() { _ = tx.Rollback(ctx) }()
q := postgresdb.New(tx)
current, err := q.GetIdentity(ctx, string(id))
if errors.Is(err, pgx.ErrNoRows) {
return identity.ErrNotFound
}
if err != nil {
return err
}
cur := identityFromRow(current)
if err := q.UpsertIdentitySubject(ctx, postgresdb.UpsertIdentitySubjectParams{
Issuer: subject.Issuer, Subject: subject.Subject, IdentityID: string(id), BoundAt: now,
}); err != nil {
return err
}
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
}
return tx.Commit(ctx)
}
var _ identity.PersonalTokenStore = (*Store)(nil)
// SubjectsOf lists an identity's bindings under one issuer, newest first.
func (s *Store) SubjectsOf(ctx context.Context, id identity.IdentityID, issuer string) ([]identity.PersonalToken, error) {
rows, err := postgresdb.New(s.pool).ListIdentitySubjects(ctx, postgresdb.ListIdentitySubjectsParams{IdentityID: string(id), Issuer: issuer})
if err != nil {
return nil, err
}
out := make([]identity.PersonalToken, 0, len(rows))
for _, row := range rows {
out = append(out, identity.PersonalToken{ID: row.Subject, CreatedAt: row.BoundAt})
}
return out, nil
}
// UnbindSubject removes one of an identity's bindings; a binding the
// identity does not hold is ErrNotFound, so no caller can remove another's.
func (s *Store) UnbindSubject(ctx context.Context, id identity.IdentityID, subject identity.Subject, audit identity.Audit) error {
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()
}
return pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
q := postgresdb.New(tx)
current, err := q.GetIdentity(ctx, string(id))
if errors.Is(err, pgx.ErrNoRows) {
return identity.ErrNotFound
}
if err != nil {
return err
}
deleted, err := q.DeleteIdentitySubject(ctx, postgresdb.DeleteIdentitySubjectParams{
IdentityID: string(id), Issuer: subject.Issuer, Subject: subject.Subject,
})
if err != nil {
return err
}
if deleted == 0 {
return identity.ErrNotFound
}
cur := identityFromRow(current)
return insertIdentityEvent(ctx, q, id, identity.Event{
IdentityID: id, Type: "unbind_subject", From: cur.Lifecycle, To: cur.Lifecycle, DisplayName: subject.Subject,
}, audit, now)
})
}
// BootstrapIdentities seeds the system identity and the legacy names, and
// moves tasks carrying a legacy name to its stable id. Invalid names are
// errors.
func (s *Store) BootstrapIdentities(ctx context.Context, legacyNames []string) error {
values := make([]identity.Identity, 0, len(legacyNames)+1)
values = append(values, identity.System())
for _, name := range legacyNames {
value, err := identity.FromLegacyName(name)
if err != nil {
return fmt.Errorf("bootstrap identity %q: %w", name, err)
}
values = append(values, value)
}
for _, value := range values {
_, err := s.create(ctx, value, identity.Audit{
ActorID: identity.SystemID, Source: "legacy-config", RequestID: "identity-import:" + string(value.ID),
}, false)
if err != nil && !isUniqueViolation(err) {
return fmt.Errorf("bootstrap identity %q: %w", value.DisplayName, err)
}
if err := s.queries().InsertIdentityAliasIgnoreConflict(ctx, postgresdb.InsertIdentityAliasIgnoreConflictParams{
Alias: value.DisplayName, IdentityID: string(value.ID),
}); err != nil {
return err
}
if value.Kind != identity.KindSystem {
if err := s.queries().UpdateTaskIdentity(ctx, postgresdb.UpdateTaskIdentityParams{
Identity: string(value.ID), Identity_2: value.DisplayName,
}); err != nil {
return err
}
}
}
return nil
}