// Package store persists approval requests, responses and rejections. package store import ( "context" "database/sql" json "encoding/json/v2" "errors" "fmt" "time" "github.com/google/uuid" "github.com/jmoiron/sqlx" ) // Step is one action a request covers: the decision and digest that bind it, // and what the action does, so the approver can be shown the sequence without // loading the decisions. type Step struct { DecisionID uuid.UUID `json:"decision_id"` Digest string `json:"digest"` Action string `json:"action"` Target string `json:"target"` Level string `json:"level"` } // Steps is the list of actions a request covers, stored as JSON. type Steps []Step // Scan reads the stored list. func (s *Steps) Scan(src any) error { var raw []byte switch v := src.(type) { case nil: *s = nil return nil case []byte: raw = v case string: raw = []byte(v) default: return fmt.Errorf("read request actions: %T", src) } return json.Unmarshal(raw, s) } // Request is the stored record of an action or autonomy proposal approval request. type Request struct { ID uuid.UUID `db:"id"` OrgID string `db:"org_id"` RunID uuid.UUID `db:"run_id"` Key string `db:"key"` // DecisionID identifies the judgement decision or the autonomy proposal. DecisionID uuid.UUID `db:"decision_id"` ActionTypeID uuid.UUID `db:"action_type_id"` Kind string `db:"kind"` Digest string `db:"digest"` // Copy the action details so the request can be read without loading the decision. // Connector holds the connector's immutable package identifier, never // renamed and never given to a different package. Connector string `db:"connector"` // InstallationID and InstallationScope name the installation the action // resolved to. An autonomy proposal has none and records the nil ID at the // instance scope. InstallationID uuid.UUID `db:"installation_id"` InstallationScope string `db:"installation_scope"` Action string `db:"action"` TargetKind string `db:"target_kind"` TargetID string `db:"target_id"` Level string `db:"level"` // Actions are the actions the request covers, in the order they run. A // request for one action lists one. Actions Steps `db:"actions"` // Irreversible is whether approving needs a fresh passkey assertion. Irreversible bool `db:"irreversible"` Summary string `db:"summary"` State string `db:"state"` Deadline time.Time `db:"deadline"` CreatedAt time.Time `db:"created_at"` AnsweredAt sql.NullTime `db:"answered_at"` AnsweredBy sql.NullString `db:"answered_by"` // AnsweredByID is the answering account's identity ID. AnsweredByID sql.NullString `db:"answered_by_id"` AnsweredVia sql.NullString `db:"answered_via"` Step int `db:"step"` StepDeadline sql.NullTime `db:"step_deadline"` // ChangeRequest is whether the request went through a change request // rather than the approvers' channels. ChangeRequest bool `db:"change_request"` // Counted is whether the approval was counted toward loosening its action type. Counted bool `db:"counted"` DiscardedBecause sql.NullString `db:"discarded_because"` } // Store is the approvals module's Postgres store. type Store struct { db *sqlx.DB // changed is told after every write that moves a request, so a mounted // view re-reads instead of polling. changed func() } // New returns a store on db. func New(db *sqlx.DB) *Store { return &Store{db: db} } // UseChange sets the function told after every write that moves a request. func (s *Store) UseChange(changed func()) { s.changed = changed } func (s *Store) change() { if s.changed != nil { s.changed() } } const requestColumns = `id, org_id, run_id, key, decision_id, action_type_id, kind, digest, connector, installation_id, installation_scope, action, target_kind, target_id, level, actions, irreversible, summary, state, deadline, created_at, answered_at, answered_by, answered_by_id, answered_via, step, step_deadline, change_request, counted, discarded_because` // Put inserts r or returns the existing request for the same organisation, // run and key. func (s *Store) Put(ctx context.Context, r Request) (Request, error) { var out Request actions, err := json.Marshal(r.Actions) if err != nil { return Request{}, fmt.Errorf("encode request actions: %w", err) } err = s.db.GetContext(ctx, &out, ` INSERT INTO approvals.requests (id, org_id, run_id, key, decision_id, action_type_id, kind, digest, connector, installation_id, installation_scope, action, target_kind, target_id, level, actions, irreversible, summary, state, deadline, step_deadline, change_request) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16::jsonb, $17, $18, $19, $20, $21, $22) ON CONFLICT (org_id, run_id, key) DO NOTHING RETURNING `+requestColumns, r.ID, r.OrgID, r.RunID, r.Key, r.DecisionID, r.ActionTypeID, r.Kind, r.Digest, r.Connector, r.InstallationID, r.InstallationScope, r.Action, r.TargetKind, r.TargetID, r.Level, string(actions), r.Irreversible, r.Summary, r.State, r.Deadline, r.StepDeadline, r.ChangeRequest) if errors.Is(err, sql.ErrNoRows) { return s.Get(ctx, r.OrgID, r.RunID, r.Key) } if err != nil { return Request{}, fmt.Errorf("put request: %w", err) } s.change() return out, nil } // Get returns the request for one run's key. func (s *Store) Get(ctx context.Context, orgID string, runID uuid.UUID, key string) (Request, error) { var out Request if err := s.db.GetContext(ctx, &out, ` SELECT `+requestColumns+` FROM approvals.requests WHERE org_id = $1 AND run_id = $2 AND key = $3`, orgID, runID, key); err != nil { if errors.Is(err, sql.ErrNoRows) { return Request{}, ErrNotFound } return Request{}, fmt.Errorf("read request: %w", err) } return out, nil } // Answer updates only pending requests. If another response already settled // the request, it returns the stored record unchanged. func (s *Store) Answer(ctx context.Context, orgID string, id uuid.UUID, state, by, byID, via string, at time.Time) (Request, error) { var out Request err := s.db.GetContext(ctx, &out, ` UPDATE approvals.requests SET state = $3, answered_at = $4, answered_by = $5, answered_by_id = nullif($6, ''), answered_via = $7 WHERE org_id = $1 AND id = $2 AND state = 'pending' RETURNING `+requestColumns, orgID, id, state, at, by, byID, via) if errors.Is(err, sql.ErrNoRows) { return s.ByID(ctx, orgID, id) } if err != nil { return Request{}, fmt.Errorf("answer request: %w", err) } s.change() return out, nil } // Escalate advances a pending request to step and sets the deadline to until. // It returns false if the request has already reached that step or is no // longer pending. func (s *Store) Escalate(ctx context.Context, orgID string, id uuid.UUID, step int, until time.Time) (Request, bool, error) { var out Request err := s.db.GetContext(ctx, &out, ` UPDATE approvals.requests SET step = $3, step_deadline = $4 WHERE org_id = $1 AND id = $2 AND state = 'pending' AND step < $3 RETURNING `+requestColumns, orgID, id, step, until) if errors.Is(err, sql.ErrNoRows) { return Request{}, false, nil } if err != nil { return Request{}, false, fmt.Errorf("escalate request: %w", err) } s.change() return out, true, nil } // Discard invalidates an approval only if it has not yet been counted. // It returns false if no record was updated. func (s *Store) Discard(ctx context.Context, orgID string, id uuid.UUID, because string) (Request, bool, error) { var out Request err := s.db.GetContext(ctx, &out, ` UPDATE approvals.requests SET state = 'discarded', discarded_because = $3 WHERE org_id = $1 AND id = $2 AND state = 'approved' AND NOT counted RETURNING `+requestColumns, orgID, id, because) if errors.Is(err, sql.ErrNoRows) { return Request{}, false, nil } if err != nil { return Request{}, false, fmt.Errorf("discard approval: %w", err) } s.change() return out, true, nil } // Count marks a valid action approval as counted. It returns false if no // eligible approval was updated. func (s *Store) Count(ctx context.Context, orgID string, id uuid.UUID) (Request, bool, error) { var out Request err := s.db.GetContext(ctx, &out, ` UPDATE approvals.requests SET counted = true WHERE org_id = $1 AND id = $2 AND state = 'approved' AND NOT counted AND kind = 'action' RETURNING `+requestColumns, orgID, id) if errors.Is(err, sql.ErrNoRows) { return Request{}, false, nil } if err != nil { return Request{}, false, fmt.Errorf("count approval: %w", err) } return out, true, nil } // ByID returns one request. func (s *Store) ByID(ctx context.Context, orgID string, id uuid.UUID) (Request, error) { var out Request if err := s.db.GetContext(ctx, &out, ` SELECT `+requestColumns+` FROM approvals.requests WHERE org_id = $1 AND id = $2`, orgID, id); err != nil { if errors.Is(err, sql.ErrNoRows) { return Request{}, ErrNotFound } return Request{}, fmt.Errorf("read request: %w", err) } return out, nil } // Pending returns the requests still waiting for an answer, oldest first. func (s *Store) Pending(ctx context.Context, orgID string) ([]Request, error) { var out []Request if err := s.db.SelectContext(ctx, &out, ` SELECT `+requestColumns+` FROM approvals.requests WHERE org_id = $1 AND state = 'pending' ORDER BY created_at`, orgID); err != nil { return nil, fmt.Errorf("list pending requests: %w", err) } return out, nil } // ForRun returns a run's requests, oldest first. func (s *Store) ForRun(ctx context.Context, orgID string, runID uuid.UUID) ([]Request, error) { var out []Request if err := s.db.SelectContext(ctx, &out, ` SELECT `+requestColumns+` FROM approvals.requests WHERE org_id = $1 AND run_id = $2 ORDER BY created_at, id`, orgID, runID); err != nil { return nil, fmt.Errorf("list run requests: %w", err) } return out, nil } // ByDecisions returns the requests made for the decisions in ids. func (s *Store) ByDecisions(ctx context.Context, orgID string, ids []uuid.UUID) ([]Request, error) { if len(ids) == 0 { return nil, nil } query, args, err := sqlx.In(` SELECT `+requestColumns+` FROM approvals.requests WHERE org_id = ? AND decision_id IN (?) ORDER BY created_at`, orgID, ids) if err != nil { return nil, fmt.Errorf("list requests by decision: %w", err) } var out []Request if err := s.db.SelectContext(ctx, &out, s.db.Rebind(query), args...); err != nil { return nil, fmt.Errorf("list requests by decision: %w", err) } return out, nil } // Refusal is an answer that was not accepted, and why. type Refusal struct { ID uuid.UUID `db:"id"` OrgID string `db:"org_id"` RequestID uuid.UUID `db:"request_id"` Identity string `db:"identity"` Via string `db:"via"` Reason string `db:"reason"` At time.Time `db:"at"` } // Refuse records an answer that wasn't accepted. func (s *Store) Refuse(ctx context.Context, r Refusal) error { if _, err := s.db.NamedExecContext(ctx, ` INSERT INTO approvals.refusals (id, org_id, request_id, identity, via, reason, at) VALUES (:id, :org_id, :request_id, :identity, :via, :reason, :at)`, r); err != nil { return fmt.Errorf("record refusal: %w", err) } return nil } // ErrNotFound means no request has that id or key. var ErrNotFound = errors.New("no such approval request")