Files
sam 8c267b6edd feat: record skipped dispatches and approver ids
- store trigger dispatches as started or skipped, with a JSON reason surfaced in the API and UI
- persist the answering account's identity id beside its display name for approvals and judgements
- save connector acceptances and their declarations in one transaction so a refused change stores nothing
2026-11-22 23:24:30 +11:00

663 lines
23 KiB
Go

// Package approvals manages requests for human approval and records responses.
// A response to an action request resumes the waiting run. The request binds
// the approval to the decision ID and action digest so it cannot authorize a
// different action.
package approvals
import (
"context"
"database/sql"
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"fmt"
"log/slog"
"maps"
"slices"
"strings"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/samcharles93/archie-core/modules/approvals/internal/store"
"github.com/samcharles93/archie-core/modules/deliveries"
"github.com/samcharles93/archie-core/modules/governance"
"github.com/samcharles93/archie-core/modules/judgement"
)
// A settled request cannot be answered again. An approved request may still
// be discarded before the approval is counted.
const (
StatePending = "pending"
StateApproved = "approved"
StateDenied = "denied"
StateExpired = "expired"
StateDiscarded = "discarded"
)
var (
// ErrNotFound means no request has that id.
ErrNotFound = store.ErrNotFound
// ErrAnswered means the request was already settled.
ErrAnswered = errors.New("that request was already answered")
// ErrExpired means the answer arrived after the request's deadline.
ErrExpired = errors.New("that request has expired")
// ErrUnlinked means the answer came from a channel account that no
// account has linked.
ErrUnlinked = errors.New("that channel account isn't linked to an account, so its answer is refused")
// ErrNotApprover means the account's role doesn't let it answer this
// request.
ErrNotApprover = errors.New("that account isn't allowed to approve this request, so its answer is refused")
// ErrNeedsFreshAuthentication means approving this action needs a passkey
// assertion made for this request, and the answer carried none.
ErrNeedsFreshAuthentication = errors.New("that action can't be undone, so approving it needs a fresh passkey confirmation")
// ErrNotSignedIn means the answer came from no signed-in person: the
// bootstrap admin token is not a person who may approve.
ErrNotSignedIn = errors.New("only a signed-in person can answer an approval")
)
// The kinds of request. A raise asks whether an action class may act with one
// level more autonomy; no run waits on it.
const (
KindAction = "action"
KindRaise = "raise"
)
// Request tracks approval of an action or a proposed increase in autonomy.
type Request struct {
ID uuid.UUID
Kind string
RunID uuid.UUID
// Key identifies the run wait that receives the response.
Key string
Decision judgement.Decision
DecisionID uuid.UUID
RequestedAt time.Time
Connector string
Action string
TargetKind string
TargetID string
Level string
// Irreversible is whether the action can't be undone. Approving it needs
// a fresh passkey assertion from the dashboard.
Irreversible bool
Summary string
State string
// Deadline applies to the whole request, not just the current escalation step.
Deadline time.Time
// Step and StepDeadline track the current escalation step and its deadline.
Step int
StepDeadline time.Time
// ChangeRequest is whether the request went through a change request
// rather than the approvers' channels.
ChangeRequest bool
AnsweredAt time.Time
AnsweredBy string
// AnsweredByID is the answering account's identity ID. It is empty when
// the request expired without an answer.
AnsweredByID string
AnsweredVia string
}
// Answerer is the account that answered. Display names are not unique, so
// the ID distinguishes accounts with the same name.
type Answerer struct {
ID string
Name string
}
// Answer records the decision and who made it.
type Answer struct {
RequestID uuid.UUID `json:"request_id"`
Approved bool `json:"approved"`
By string `json:"by"`
// ByID is the identity ID of the account named by By.
ByID string `json:"by_id,omitzero"`
Via string `json:"via"`
At time.Time `json:"at"`
}
// Approval binds the approver's identity and response time to the decision ID
// and action digest.
func (a Answer) Approval(d judgement.Decision) judgement.Approval {
return judgement.Approval{DecisionID: d.ID, Digest: d.Action.Digest, By: a.By, ByID: a.ByID, At: a.At}
}
// View is the API representation of an approval request.
type View struct {
ID uuid.UUID `json:"id"`
Kind string `json:"kind"`
RunID uuid.UUID `json:"run_id"`
Action string `json:"action"`
Target string `json:"target"`
Level string `json:"level"`
Summary string `json:"summary"`
State string `json:"state"`
Deadline time.Time `json:"deadline"`
// Step and StepDeadline describe the current escalation step.
Step int `json:"step"`
StepDeadline time.Time `json:"step_deadline,omitzero"`
// DecisionID identifies the judgement decision or, for a raise request, the proposed raise.
DecisionID uuid.UUID `json:"decision_id"`
RequestedAt time.Time `json:"requested_at"`
// AnsweredBy is the answering account's display name.
AnsweredBy string `json:"answered_by,omitzero"`
// AnsweredByID is the answering account's identity ID.
AnsweredByID string `json:"answered_by_id,omitzero"`
AnsweredVia string `json:"answered_via,omitzero"`
AnsweredAt time.Time `json:"answered_at,omitzero"`
}
// View converts a request to its API representation.
func (r Request) View() View {
return View{
ID: r.ID, Kind: r.Kind, RunID: r.RunID, Action: r.Connector + " " + r.Action,
Target: r.TargetKind + ":" + r.TargetID, Level: r.Level,
Summary: r.Summary, State: r.State, Deadline: r.Deadline, Step: r.Step, StepDeadline: r.StepDeadline,
DecisionID: r.DecisionID, RequestedAt: r.RequestedAt,
AnsweredBy: r.AnsweredBy, AnsweredByID: r.AnsweredByID, AnsweredVia: r.AnsweredVia, AnsweredAt: r.AnsweredAt,
}
}
// Signaller wakes a run waiting on a key.
type Signaller interface {
Signal(ctx context.Context, id uuid.UUID, key string, payload jsontext.Value) error
}
// Delivery sends approval requests and publishes responses and notifications.
type Delivery interface {
Ask(ctx context.Context, a deliveries.ApprovalRequest) error
Told(ctx context.Context, a deliveries.ApprovalRequest, answer string) error
Notify(ctx context.Context, n deliveries.Notification) error
}
// Classes updates action-class autonomy. Denials reduce autonomy; approvals
// count towards an increase that a person must approve separately.
type Classes interface {
Approved(ctx context.Context, decisionID uuid.UUID, by string, need int, deadline time.Time) (*judgement.Raise, error)
Denied(ctx context.Context, decisionID uuid.UUID) error
AnswerRaise(ctx context.Context, id uuid.UUID, by string, approve bool) (bool, error)
CancelRaise(ctx context.Context, id uuid.UUID) error
}
// Policy provides the organisation's deadline and approval threshold for raises.
type Policy interface {
ApprovalDeadline(ctx context.Context) (time.Duration, error)
RaiseAfter(ctx context.Context) (int, error)
}
// Accounts resolves who answered: the account a channel credential is linked
// to, and the principal the access policies judge.
type Accounts interface {
ResolveSubject(ctx context.Context, s governance.Subject) (governance.Identity, error)
PrincipalFor(ctx context.Context, id governance.IdentityID) (governance.Principal, error)
Get(ctx context.Context, id governance.IdentityID) (governance.Identity, error)
}
// Module owns one organisation's approval requests.
type Module struct {
orgID string
store *store.Store
tell Delivery
wake Signaller
classes Classes
policy Policy
accounts Accounts
authz governance.Authorizer
confirm Confirmer
changes ChangeRequests
log *slog.Logger
now func() time.Time
}
// NewModule creates the approvals module for orgID.
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tell Delivery, wake Signaller, classes Classes, policy Policy, accounts Accounts) *Module {
return &Module{
orgID: orgID, store: store.New(db), tell: tell, wake: wake, classes: classes, policy: policy, accounts: accounts,
log: log, now: time.Now,
}
}
// Ask reuses the request for the same run and key so retries do not create
// duplicate requests. It uses a change-request connector when judgement
// requires a change request and a connector is configured. Otherwise, it
// sends the request to the approval channels with the first step's deadline.
func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, d judgement.Decision, path []governance.PathStep) (Request, error) {
if len(path) == 0 {
return Request{}, ErrNoPath
}
changeRequest := d.ChangeRequest && m.changes != nil
now := m.now().UTC()
var total time.Duration
for _, st := range path {
total += st.Deadline()
}
row, err := m.store.Put(ctx, store.Request{
ID: uuid.New(), OrgID: m.orgID, RunID: runID, Key: key,
DecisionID: d.ID, Kind: KindAction, Digest: d.Action.Digest, Level: d.Level.String(),
Connector: d.Action.Connector, Action: d.Action.Name,
TargetKind: d.Action.Target.Kind, TargetID: d.Action.Target.ID, Irreversible: irreversible(d.Action),
Summary: Summary(d), State: StatePending, Deadline: now.Add(total),
StepDeadline: sql.NullTime{Time: now.Add(path[0].Deadline()), Valid: true},
ChangeRequest: changeRequest,
})
if err != nil {
return Request{}, err
}
r := requestOf(row, d)
if row.State != StatePending {
return r, nil
}
if row.ChangeRequest {
if err := m.changes.Open(ctx, r); err != nil {
return Request{}, fmt.Errorf("open change request: %w", err)
}
return r, nil
}
if err := m.tell.Ask(ctx, deliveries.ApprovalRequest{
RunID: r.RunID, RequestID: r.ID, Key: r.Key + ":ask",
Title: "Approval needed: " + d.Action.Connector + " " + d.Action.Name,
Body: r.Summary, ExpiresAt: r.StepDeadline,
}); err != nil {
return Request{}, fmt.Errorf("send approval request: %w", err)
}
return r, nil
}
func (m *Module) answerAs(ctx context.Context, id uuid.UUID, who Answerer, via string, approved bool) (Request, error) {
now := m.now().UTC()
if _, err := m.pending(ctx, id, now); err != nil {
return Request{}, err
}
state := StateDenied
if approved {
state = StateApproved
}
row, err := m.store.Answer(ctx, m.orgID, id, state, who.Name, who.ID, via, now)
if err != nil {
return Request{}, err
}
if row.State != state {
return Request{}, fmt.Errorf("%w: %s", ErrAnswered, row.State)
}
answer := Answer{RequestID: row.ID, Approved: approved, By: who.Name, ByID: who.ID, Via: via, At: now}
if row.Kind == KindRaise {
if err := m.answerRaise(ctx, row, answer); err != nil {
return Request{}, err
}
return requestOf(row, judgement.Decision{}), nil
}
if err := m.wakeWith(ctx, row, answer); err != nil {
return Request{}, err
}
// Count denials immediately. Defer counting approvals until execution
// is imminent so discarded approvals do not increase autonomy.
if !answer.Approved {
if err := m.classes.Denied(ctx, row.DecisionID); err != nil {
return Request{}, err
}
}
return requestOf(row, judgement.Decision{}), nil
}
func (m *Module) learn(ctx context.Context, row store.Request, a Answer) error {
need, err := m.policy.RaiseAfter(ctx)
if err != nil {
return fmt.Errorf("read raise count: %w", err)
}
wait, err := m.policy.ApprovalDeadline(ctx)
if err != nil {
return fmt.Errorf("read approval deadline: %w", err)
}
raise, err := m.classes.Approved(ctx, row.DecisionID, a.By, need, a.At.Add(wait))
if err != nil || raise == nil {
return err
}
return m.askRaise(ctx, raise)
}
func (m *Module) askRaise(ctx context.Context, r *judgement.Raise) error {
class := r.Class
row, err := m.store.Put(ctx, store.Request{
ID: uuid.New(), OrgID: m.orgID, Key: "raise:" + r.ID.String(),
DecisionID: r.ID, Kind: KindRaise, Level: r.From.String(),
Connector: class.Connector, Action: class.Action, TargetKind: class.TargetKind, TargetID: class.Environment,
Summary: raiseSummary(r), State: StatePending, Deadline: r.Deadline,
})
if err == nil {
err = m.tell.Ask(ctx, deliveries.ApprovalRequest{
RequestID: row.ID, Key: row.Key + ":ask",
Title: "Raise autonomy: " + class.Connector + " " + class.Action,
Body: row.Summary, ExpiresAt: row.Deadline,
})
}
if err != nil {
// Cancel the raise so a later approval can trigger another proposal.
if cerr := m.classes.CancelRaise(ctx, r.ID); cerr != nil {
err = errors.Join(err, cerr)
}
return fmt.Errorf("ask to raise a class: %w", err)
}
return nil
}
// answerRaise applies a person's answer to a raise. No run waits on it.
func (m *Module) answerRaise(ctx context.Context, row store.Request, a Answer) error {
raised, err := m.classes.AnswerRaise(ctx, row.DecisionID, a.By, a.Approved)
if err != nil {
return fmt.Errorf("answer raise: %w", err)
}
text := answerText(a)
if a.Approved && !raised {
text += " This approval did not increase the action class's autonomy level."
}
return m.tell.Told(ctx, deliveries.ApprovalRequest{
RequestID: row.ID, Key: row.Key + ":ask", Title: "Raise answered",
}, text)
}
func raiseSummary(r *judgement.Raise) string {
c := r.Class
var s strings.Builder
fmt.Fprintf(&s, "%s: %s on %s in %s. Proposed autonomy increase: %s to %s.\nConsecutive approvals (%d):",
c.Connector, c.Action, c.TargetKind, c.Environment, r.From, r.To, len(r.Evidence))
for _, e := range r.Evidence {
fmt.Fprintf(&s, "\n- %s, %s", e.By, e.At.UTC().Format("2006-01-02 15:04 UTC"))
}
return s.String()
}
// Settle processes a response from a channel account, such as the Telegram
// user 1001 on the "telegram" connector. It records why it rejected an
// unlinked or unauthorized response. It returns false without an error for
// recorded rejections and for requests that are missing, expired or already
// answered, since retrying won't help. An unlinked account returns
// ErrUnlinked so the caller can tell it how to link.
func (m *Module) Settle(ctx context.Context, id uuid.UUID, who governance.Subject, via string, approved bool) (bool, error) {
row, err := m.store.ByID(ctx, m.orgID, id)
if errors.Is(err, ErrNotFound) {
return false, nil
}
if err != nil {
return false, err
}
answerer, err := m.channelAnswerer(ctx, who, row)
if refusal(err) {
identity := who.Issuer + ":" + who.Subject
m.log.WarnContext(ctx, "approval answer refused", "request", id, "identity", identity, "reason", err.Error())
if rerr := m.store.Refuse(ctx, store.Refusal{
ID: uuid.New(), OrgID: m.orgID, RequestID: id, Identity: identity, Via: via, Reason: err.Error(), At: m.now().UTC(),
}); rerr != nil {
return false, rerr
}
if errors.Is(err, ErrUnlinked) {
return false, err
}
return false, nil
}
if err != nil {
return false, err
}
_, err = m.answerAs(ctx, id, answerer, via, approved)
switch {
case err == nil:
return true, nil
case errors.Is(err, ErrAnswered), errors.Is(err, ErrExpired), errors.Is(err, ErrNotFound):
return false, nil
}
return false, err
}
// channelAnswerer returns the account that holds the channel credential when
// that account may answer row.
func (m *Module) channelAnswerer(ctx context.Context, who governance.Subject, row store.Request) (Answerer, error) {
account, err := m.accounts.ResolveSubject(ctx, who)
if errors.Is(err, governance.ErrIdentityNotFound) {
return Answerer{}, ErrUnlinked
}
if err != nil {
return Answerer{}, fmt.Errorf("resolve %s:%s: %w", who.Issuer, who.Subject, err)
}
if account.Kind != governance.KindUser || !account.CanAct() {
return Answerer{}, ErrNotApprover
}
p, err := m.accounts.PrincipalFor(ctx, account.ID)
if err != nil {
return Answerer{}, fmt.Errorf("read access of %s: %w", account.ID, err)
}
p.Kind = account.Kind
if err := m.mayAnswer(ctx, p, row); err != nil {
return Answerer{}, err
}
return Answerer{ID: string(account.ID), Name: account.DisplayName}, nil
}
// mayAnswer applies the access policies to an answer, as to any other
// permission: approving needs the approve action on the request, and a raise
// or an escalated action, which change what the organisation lets Archie do,
// also need the policy-management action.
func (m *Module) mayAnswer(ctx context.Context, p governance.Principal, row store.Request) error {
if m.authz == nil {
return ErrNotApprover
}
actions := []governance.Action{governance.ActionApprove}
if row.Kind == KindRaise || row.Level == judgement.Escalate.String() {
actions = append(actions, governance.ActionManagePolicies)
}
res := governance.Resource{Kind: governance.KindApproval, ID: row.ID.String(), Org: governance.DefaultOrgID, State: row.State}
for _, a := range actions {
d := m.authz.Authorize(ctx, p, a, res, governance.AccessContext{})
if d.Err != nil {
return fmt.Errorf("check access: %w", d.Err)
}
if !d.Allowed {
return ErrNotApprover
}
}
return nil
}
// refusal distinguishes a rejected response from an operational error.
func refusal(err error) bool {
return errors.Is(err, ErrUnlinked) || errors.Is(err, ErrNotApprover) ||
errors.Is(err, ErrNeedsFreshAuthentication) || errors.Is(err, ErrNotSignedIn)
}
// Expire records a timeout without reducing the action class's autonomy:
// receiving no response is not a denial.
func (m *Module) Expire(ctx context.Context, id uuid.UUID) error {
row, err := m.store.Answer(ctx, m.orgID, id, StateExpired, "deadline", "", "clock", m.now().UTC())
if err != nil {
if errors.Is(err, ErrNotFound) {
return nil
}
return err
}
if row.State != StateExpired {
return nil
}
m.log.InfoContext(ctx, "approval request expired", "request", row.ID, "run", row.RunID)
withdrawn := ""
if row.ChangeRequest {
if err := m.changes.Withdraw(ctx, requestOf(row, judgement.Decision{})); err != nil {
return fmt.Errorf("withdraw change request: %w", err)
}
withdrawn = " Its change request was withdrawn."
}
if err := m.tell.Told(ctx, deliveries.ApprovalRequest{
RunID: row.RunID, RequestID: row.ID, Key: row.Key + ":ask",
Title: "Approval expired", Body: "The approval request expired without a response. The action did not run." + withdrawn,
}, "Expired without an answer."); err != nil {
return err
}
// Use a stable key so retrying the expiry does not duplicate the notification.
return m.tell.Notify(ctx, deliveries.Notification{
RunID: row.RunID, Key: row.Key + ":expired",
Title: "Approval timed out: " + row.Connector + " " + row.Action,
Body: "No one responded before the final escalation deadline, so " + row.Connector + " " + row.Action +
" did not run." + withdrawn + " " + row.Summary,
})
}
// Pending returns the requests waiting for an answer, oldest first.
func (m *Module) Pending(ctx context.Context) ([]Request, error) {
rows, err := m.store.Pending(ctx, m.orgID)
if err != nil {
return nil, err
}
out := make([]Request, 0, len(rows))
for _, row := range rows {
out = append(out, requestOf(row, judgement.Decision{}))
}
return out, nil
}
// ForRun returns a run's requests in the order they were made.
func (m *Module) ForRun(ctx context.Context, runID uuid.UUID) ([]Request, error) {
rows, err := m.store.ForRun(ctx, m.orgID, runID)
if err != nil {
return nil, err
}
out := make([]Request, 0, len(rows))
for _, row := range rows {
out = append(out, requestOf(row, judgement.Decision{}))
}
return out, nil
}
// Outcomes returns approval outcomes by decision ID for the action class history.
func (m *Module) Outcomes(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]judgement.Outcome, error) {
rows, err := m.store.ByDecisions(ctx, m.orgID, ids)
if err != nil {
return nil, err
}
out := make(map[uuid.UUID]judgement.Outcome, len(rows))
for _, row := range rows {
o := judgement.Outcome{State: row.State}
if row.AnsweredBy.Valid {
o.By = row.AnsweredBy.String
}
if row.AnsweredAt.Valid {
o.At = row.AnsweredAt.Time
}
out[row.DecisionID] = o
}
return out, nil
}
func (m *Module) pending(ctx context.Context, id uuid.UUID, now time.Time) (store.Request, error) {
row, err := m.store.ByID(ctx, m.orgID, id)
if err != nil {
return store.Request{}, err
}
if err := settleable(row, now); err != nil {
return store.Request{}, err
}
return row, nil
}
func settleable(r store.Request, now time.Time) error {
switch {
case r.State != StatePending:
return fmt.Errorf("%w: %s", ErrAnswered, r.State)
case !now.Before(r.Deadline):
return ErrExpired
}
return nil
}
func (m *Module) wakeWith(ctx context.Context, row store.Request, answer Answer) error {
payload, err := json.Marshal(answer)
if err != nil {
return fmt.Errorf("encode answer: %w", err)
}
if err := m.wake.Signal(ctx, row.RunID, row.Key, payload); err != nil {
return fmt.Errorf("wake run %s: %w", row.RunID, err)
}
return m.tell.Told(ctx, deliveries.ApprovalRequest{
RunID: row.RunID, RequestID: row.ID, Key: row.Key + ":ask",
Title: "Approval answered", Body: answerText(answer),
}, answerText(answer))
}
func answerText(a Answer) string {
verb := "Denied"
if a.Approved {
verb = "Approved"
}
return fmt.Sprintf("%s by %s via %s.", verb, a.By, a.Via)
}
// Summary shows the approver the action, its target and why it requires approval.
func Summary(d judgement.Decision) string {
s := fmt.Sprintf("%s: %s on %s %q.", d.Action.Connector, d.Action.Name, d.Action.Target.Kind, d.Action.Target.ID)
if d.Action.Effect.Summary != "" {
s += " " + d.Action.Effect.Summary
}
// The exact input is what is approved, so the person sees every value.
if in := inputLine(d.Action.Input); in != "" {
s += "\nWith: " + in
}
var held strings.Builder
for _, v := range d.Verdicts {
if v.Advisory || v.Ceiling != d.Level {
continue
}
for _, f := range v.Findings {
fmt.Fprintf(&held, "\n- %s: %s", v.Guard, f.Text)
}
if v.Failed != "" {
fmt.Fprintf(&held, "\n- %s: couldn't judge: %s", v.Guard, v.Failed)
}
}
if held.String() != "" {
s += "\nHeld because:" + held.String()
}
return s
}
// inputLine renders an action's input as "key=value" pairs in key order, or
// the raw JSON when it is not a nonempty object.
func inputLine(input jsontext.Value) string {
var fields map[string]jsontext.Value
if err := json.Unmarshal(input, &fields); err != nil || len(fields) == 0 {
return strings.TrimSpace(string(input))
}
parts := make([]string, 0, len(fields))
for _, k := range slices.Sorted(maps.Keys(fields)) {
v := string(fields[k])
var text string
if json.Unmarshal(fields[k], &text) == nil {
v = text
}
parts = append(parts, k+"="+v)
}
return strings.Join(parts, ", ")
}
func requestOf(row store.Request, d judgement.Decision) Request {
r := Request{
ID: row.ID, Kind: row.Kind, RunID: row.RunID, Key: row.Key, Decision: d, DecisionID: row.DecisionID, RequestedAt: row.CreatedAt,
Connector: row.Connector, Action: row.Action, TargetKind: row.TargetKind, TargetID: row.TargetID,
Level: row.Level, Irreversible: row.Irreversible, Summary: row.Summary, State: row.State, Deadline: row.Deadline,
Step: row.Step, ChangeRequest: row.ChangeRequest,
}
if row.StepDeadline.Valid {
r.StepDeadline = row.StepDeadline.Time
}
if row.AnsweredAt.Valid {
r.AnsweredAt = row.AnsweredAt.Time
}
if row.AnsweredBy.Valid {
r.AnsweredBy = row.AnsweredBy.String
}
if row.AnsweredByID.Valid {
r.AnsweredByID = row.AnsweredByID.String
}
if row.AnsweredVia.Valid {
r.AnsweredVia = row.AnsweredVia.String
}
return r
}