Cancelling a run moved it and the runs it called to cancelled and wrote nothing to either trail, so a stopped run could not say when it stopped or who asked. The stop now returns the runs it stopped and records one cancel entry on each, in the same transaction, naming the principal that asked. The entry is a step named cancel with the caller's identity, so the run detail shows it with the rest of the trail.
788 lines
28 KiB
Go
788 lines
28 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 authorise 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/connectors"
|
|
"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. An autonomy proposal asks whether an action type may act with one
|
|
// level more autonomy; no run waits on it.
|
|
const (
|
|
KindAction = "action"
|
|
KindAutonomy = "autonomy"
|
|
)
|
|
|
|
// Step is one action a request covers, as the approver is shown it: the
|
|
// binding that names it, and what it does.
|
|
type Step = store.Step
|
|
|
|
// Request tracks approval of an action, a sequence of actions, 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
|
|
// Digest is the digest of the action the request was raised for.
|
|
Digest string
|
|
// Actions are the actions the request covers, in the order they run. A
|
|
// request for one action lists one; an autonomy proposal lists none.
|
|
Actions []Step
|
|
ActionTypeID 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 in 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 IDs
|
|
// and action digests the request covers.
|
|
func (a Answer) Approval(d judgement.Decision) judgement.Approval {
|
|
return judgement.Approval{Bindings: []judgement.Binding{judgement.Bind(d)}, By: a.By, ByID: a.ByID, At: a.At}
|
|
}
|
|
|
|
// Approval is the approval a's answer gives for the actions the request
|
|
// covers, in the order the approver saw them.
|
|
func (r Request) Approval(a Answer) judgement.Approval {
|
|
bindings := make([]judgement.Binding, len(r.Actions))
|
|
for i, s := range r.Actions {
|
|
bindings[i] = judgement.Binding{DecisionID: s.DecisionID, Digest: s.Digest}
|
|
}
|
|
return judgement.Approval{Bindings: bindings, By: a.By, ByID: a.ByID, At: a.At}
|
|
}
|
|
|
|
// Covers reports whether the request was raised for d's action.
|
|
func (r Request) Covers(d judgement.Decision) bool {
|
|
if len(r.Actions) == 0 {
|
|
// A request recorded before requests listed their actions names on its
|
|
// own the action it was raised for.
|
|
return r.DecisionID == d.ID && r.Digest == d.Action.Digest
|
|
}
|
|
for _, s := range r.Actions {
|
|
if s.DecisionID == d.ID && s.Digest == d.Action.Digest {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// 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 an autonomy request, the autonomy proposal.
|
|
DecisionID uuid.UUID `json:"decision_id"`
|
|
RequestedAt time.Time `json:"requested_at"`
|
|
// Steps are the actions the request covers, in the order they run. A
|
|
// request for one action lists one.
|
|
Steps []StepView `json:"steps,omitzero"`
|
|
// 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"`
|
|
}
|
|
|
|
// StepView is one action of an approval request, as the API shows it.
|
|
type StepView struct {
|
|
DecisionID uuid.UUID `json:"decision_id"`
|
|
Action string `json:"action"`
|
|
Target string `json:"target"`
|
|
Level string `json:"level"`
|
|
}
|
|
|
|
// View converts a request to its API representation.
|
|
func (r Request) View() View {
|
|
steps := make([]StepView, len(r.Actions))
|
|
for i, s := range r.Actions {
|
|
steps[i] = StepView{DecisionID: s.DecisionID, Action: s.Action, Target: s.Target, Level: s.Level}
|
|
}
|
|
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, Steps: steps,
|
|
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
|
|
}
|
|
|
|
// ActionTypes updates the autonomy level of action types. A denial lowers the
|
|
// level; approvals count towards a proposal to raise it, which a person must
|
|
// approve separately.
|
|
type ActionTypes interface {
|
|
Approved(ctx context.Context, decisionID uuid.UUID, who judgement.Answerer, need int, deadline time.Time) (*judgement.AutonomyProposal, error)
|
|
Denied(ctx context.Context, decisionID uuid.UUID) error
|
|
AnswerProposal(ctx context.Context, id uuid.UUID, who judgement.Answerer, approve bool) (bool, error)
|
|
CancelProposal(ctx context.Context, id uuid.UUID) error
|
|
}
|
|
|
|
// Policy provides the organisation's deadline and approval threshold for autonomy proposals.
|
|
type Policy interface {
|
|
ApprovalDeadline(ctx context.Context) (time.Duration, error)
|
|
ProposeAutonomyAfter(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
|
|
actionTypes ActionTypes
|
|
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, actionTypes ActionTypes, policy Policy, accounts Accounts) *Module {
|
|
return &Module{
|
|
orgID: orgID, store: store.New(db), tell: tell, wake: wake, actionTypes: actionTypes, 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 covers every action in ds, which one person approves
|
|
// in one act. 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, ds []judgement.Decision, path []governance.PathStep) (Request, error) {
|
|
if len(path) == 0 {
|
|
return Request{}, ErrNoPath
|
|
}
|
|
if len(ds) == 0 {
|
|
return Request{}, errors.New("approval request needs an action")
|
|
}
|
|
first := ds[0]
|
|
if first.ActionTypeID == uuid.Nil {
|
|
return Request{}, errors.New("approval request needs an action type id")
|
|
}
|
|
actions := make([]Step, len(ds))
|
|
// The request needs the authority of the strictest action it covers, and a
|
|
// passkey for any action that can't be undone.
|
|
level := first.Level
|
|
var changeRequest, passkey bool
|
|
for i, d := range ds {
|
|
level = max(level, d.Level)
|
|
actions[i] = Step{
|
|
DecisionID: d.ID, Digest: d.Action.Digest, Level: d.Level.String(),
|
|
Action: d.Action.Connector + " " + d.Action.Name, Target: d.Action.Target.Kind + ":" + d.Action.Target.ID,
|
|
}
|
|
changeRequest = changeRequest || d.ChangeRequest
|
|
passkey = passkey || irreversible(d.Action)
|
|
}
|
|
changeRequest = 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: first.ID, ActionTypeID: first.ActionTypeID, Kind: KindAction, Digest: first.Action.Digest, Level: level.String(),
|
|
Connector: first.Action.Connector, Action: first.Action.Name,
|
|
InstallationID: first.Action.Installation.ID, InstallationScope: first.Action.Installation.Scope,
|
|
TargetKind: first.Action.Target.Kind, TargetID: first.Action.Target.ID, Actions: actions, Irreversible: passkey,
|
|
Summary: SummaryOf(ds), 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, first)
|
|
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: approvalTitle(ds),
|
|
Body: r.Summary, ExpiresAt: r.StepDeadline,
|
|
}); err != nil {
|
|
return Request{}, fmt.Errorf("send approval request: %w", err)
|
|
}
|
|
return r, nil
|
|
}
|
|
|
|
// named is how a request's actions are named in a message: the action, or how
|
|
// many were approved together.
|
|
func named(r store.Request) string {
|
|
if len(r.Actions) > 1 {
|
|
return fmt.Sprintf("%d actions", len(r.Actions))
|
|
}
|
|
return r.Connector + " " + r.Action
|
|
}
|
|
|
|
// approvalTitle names what a request asks about: the action, or how many are
|
|
// approved together.
|
|
func approvalTitle(ds []judgement.Decision) string {
|
|
d := ds[0]
|
|
if len(ds) > 1 {
|
|
return fmt.Sprintf("Approval needed: %d actions", len(ds))
|
|
}
|
|
return "Approval needed: " + d.Action.Connector + " " + d.Action.Name
|
|
}
|
|
|
|
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 == KindAutonomy {
|
|
if err := m.answerProposal(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.actionTypes.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.ProposeAutonomyAfter(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("read autonomy proposal count: %w", err)
|
|
}
|
|
wait, err := m.policy.ApprovalDeadline(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("read approval deadline: %w", err)
|
|
}
|
|
proposal, err := m.actionTypes.Approved(ctx, row.DecisionID, judgement.Answerer{ID: a.ByID, Name: a.By}, need, a.At.Add(wait))
|
|
if err != nil || proposal == nil {
|
|
return err
|
|
}
|
|
return m.askProposal(ctx, proposal)
|
|
}
|
|
|
|
func (m *Module) askProposal(ctx context.Context, r *judgement.AutonomyProposal) error {
|
|
actionType := r.ActionType
|
|
var (
|
|
row store.Request
|
|
err error
|
|
)
|
|
if r.ActionTypeID == uuid.Nil {
|
|
err = errors.New("autonomy approval request needs an action type id")
|
|
} else {
|
|
row, err = m.store.Put(ctx, store.Request{
|
|
ID: uuid.New(), OrgID: m.orgID, Key: "autonomy:" + r.ID.String(),
|
|
DecisionID: r.ID, ActionTypeID: r.ActionTypeID, Kind: KindAutonomy, Level: r.From.String(),
|
|
Connector: actionType.Connector, Action: actionType.Action, TargetKind: actionType.TargetKind, TargetID: actionType.Environment,
|
|
InstallationScope: connectors.ScopeInstance,
|
|
Summary: proposalSummary(r), State: StatePending, Deadline: r.Deadline,
|
|
})
|
|
}
|
|
if err == nil {
|
|
err = m.tell.Ask(ctx, deliveries.ApprovalRequest{
|
|
RequestID: row.ID, Key: row.Key + ":ask",
|
|
Title: "Autonomy proposal: " + actionType.Connector + " " + actionType.Action,
|
|
Body: row.Summary, ExpiresAt: row.Deadline,
|
|
})
|
|
}
|
|
if err != nil {
|
|
// Cancel the autonomy proposal so a later approval can trigger another proposal.
|
|
if cerr := m.actionTypes.CancelProposal(ctx, r.ID); cerr != nil {
|
|
err = errors.Join(err, cerr)
|
|
}
|
|
return fmt.Errorf("ask for more autonomy: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// answerProposal applies a person's answer to an autonomy proposal. No run waits on it.
|
|
func (m *Module) answerProposal(ctx context.Context, row store.Request, a Answer) error {
|
|
loosened, err := m.actionTypes.AnswerProposal(ctx, row.DecisionID, judgement.Answerer{ID: a.ByID, Name: a.By}, a.Approved)
|
|
if err != nil {
|
|
return fmt.Errorf("answer autonomy proposal: %w", err)
|
|
}
|
|
text := answerText(a)
|
|
if a.Approved && !loosened {
|
|
text += " This approval did not increase the action type's autonomy level."
|
|
}
|
|
return m.tell.Told(ctx, deliveries.ApprovalRequest{
|
|
RequestID: row.ID, Key: row.Key + ":ask", Title: "Autonomy proposal answered",
|
|
}, text)
|
|
}
|
|
|
|
func proposalSummary(r *judgement.AutonomyProposal) string {
|
|
c := r.ActionType
|
|
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 unauthorised 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 an autonomy proposal
|
|
// 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 == KindAutonomy || 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 type'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: " + named(row),
|
|
Body: "No one responded before the final escalation deadline, so " + named(row) +
|
|
" 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 type 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.AnsweredByID.Valid {
|
|
o.ByID = row.AnsweredByID.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)
|
|
}
|
|
|
|
// SummaryOf shows the approver every action a request covers, in the order
|
|
// they run, and why each one requires approval.
|
|
func SummaryOf(ds []judgement.Decision) string {
|
|
if len(ds) == 1 {
|
|
return Summary(ds[0])
|
|
}
|
|
var s strings.Builder
|
|
fmt.Fprintf(&s, "%d actions, approved together, in this order:", len(ds))
|
|
for i, d := range ds {
|
|
lines := strings.Split(Summary(d), "\n")
|
|
fmt.Fprintf(&s, "\n%d. %s", i+1, lines[0])
|
|
for _, line := range lines[1:] {
|
|
s.WriteString("\n " + line)
|
|
}
|
|
}
|
|
return s.String()
|
|
}
|
|
|
|
// 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, Digest: row.Digest, ActionTypeID: row.ActionTypeID, RequestedAt: row.CreatedAt,
|
|
Connector: row.Connector, Action: row.Action, TargetKind: row.TargetKind, TargetID: row.TargetID,
|
|
Level: row.Level, Actions: row.Actions, 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
|
|
}
|