Files
archie/internal/infrastructure/postgres/identities.go
T

487 lines
18 KiB
Go

package postgres
import (
"context"
"errors"
"fmt"
"strings"
"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"
"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 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,
})
}
// 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, 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
}
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.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
}
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
if err := guardLeavingActive(ctx, tx, id, cur.Lifecycle, next.Lifecycle); err != nil {
return identity.Identity{}, err
}
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
}
// guardLeavingActive refuses suspending or retiring an org's last active
// owner, and signs out an identity that may no longer act.
func guardLeavingActive(ctx context.Context, tx pgx.Tx, id identity.IdentityID, from, to identity.Lifecycle) error {
if to == identity.LifecycleActive {
return nil
}
if from == identity.LifecycleActive {
if err := keepActiveOwner(ctx, tx, string(id), ""); err != nil {
return err
}
}
_, err := tx.Exec(ctx, `DELETE FROM account_sessions WHERE identity_id=$1`, string(id))
return err
}
// 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 {
return s.bindSubject(ctx, id, subject, "", nil, audit)
}
// BindPersonalToken binds a personal token's subject with the name and expiry
// its owner chose; a nil expiry never lapses.
func (s *Store) BindPersonalToken(ctx context.Context, id identity.IdentityID, subject identity.Subject, name string, expiresAt *time.Time, audit identity.Audit) error {
return s.bindSubject(ctx, id, subject, name, expiresAt, audit)
}
func (s *Store) bindSubject(ctx context.Context, id identity.IdentityID, subject identity.Subject, name string, expiresAt *time.Time, 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.GetVisibleIdentity(ctx, postgresdb.GetVisibleIdentityParams{ID: string(id), ScopeOrg: memberScope(ctx)})
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,
Name: name, ExpiresAt: timestamptzOf(expiresAt),
}); 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, Name: row.Name, CreatedAt: row.BoundAt, ExpiresAt: timePtr(row.ExpiresAt), LastUsedAt: timePtr(row.LastUsedAt),
})
}
return out, nil
}
// PersonalTokenOf returns one token's lifetime and last use, whoever owns it.
func (s *Store) PersonalTokenOf(ctx context.Context, subject identity.Subject) (identity.PersonalToken, error) {
row, err := postgresdb.New(s.pool).GetIdentitySubjectUse(ctx, postgresdb.GetIdentitySubjectUseParams{Issuer: subject.Issuer, Subject: subject.Subject})
if errors.Is(err, pgx.ErrNoRows) {
return identity.PersonalToken{}, identity.ErrNotFound
}
if err != nil {
return identity.PersonalToken{}, err
}
return identity.PersonalToken{
ID: row.Subject, Name: row.Name, CreatedAt: row.BoundAt, ExpiresAt: timePtr(row.ExpiresAt), LastUsedAt: timePtr(row.LastUsedAt),
}, nil
}
// TouchPersonalToken records when a token last authenticated.
func (s *Store) TouchPersonalToken(ctx context.Context, subject identity.Subject, at time.Time) error {
return postgresdb.New(s.pool).TouchIdentitySubject(ctx, postgresdb.TouchIdentitySubjectParams{
Issuer: subject.Issuer, Subject: subject.Subject, LastUsedAt: timestamptzOf(&at),
})
}
// 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.GetVisibleIdentity(ctx, postgresdb.GetVisibleIdentityParams{ID: string(id), ScopeOrg: memberScope(ctx)})
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
}
func timestamptzOf(t *time.Time) pgtype.Timestamptz {
if t == nil {
return pgtype.Timestamptz{}
}
return pgtype.Timestamptz{Time: *t, Valid: true}
}
func timePtr(t pgtype.Timestamptz) *time.Time {
if !t.Valid {
return nil
}
v := t.Time
return &v
}