Files
archie/modules/approvals/approvals.go
T

571 lines
19 KiB
Go

// Package approvals owns an approval request: one judged action waiting for a
// person's answer, and the answer that settles it. A request is made when
// judgement holds an action at propose and wait, and an answer is an event in:
// it wakes the run waiting on that key, which then runs the action only if the
// answer named the exact action that was judged.
//
// The request binds to the decision and its digest, so an approval covers the
// action that was shown and nothing else.
package approvals
import (
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"fmt"
"log/slog"
"maps"
"net/http"
"slices"
"strings"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/samcharles93/archie-core/internal/platform/httpjson"
"github.com/samcharles93/archie-core/modules/approvals/internal/store"
"github.com/samcharles93/archie-core/modules/deliveries"
"github.com/samcharles93/archie-core/modules/judgement"
)
// The states a request can be in. A settled request never changes again.
const (
StatePending = "pending"
StateApproved = "approved"
StateDenied = "denied"
StateExpired = "expired"
)
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")
)
// 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 is one judged action waiting for a person's answer.
type Request struct {
ID uuid.UUID
Kind string
RunID uuid.UUID
// Key is the run's wait key, stored so an answer knows what to wake.
Key string
Decision judgement.Decision
DecisionID uuid.UUID
RequestedAt time.Time
Connector string
Action string
TargetKind string
TargetID string
Level string
Summary string
State string
Deadline time.Time
AnsweredAt time.Time
AnsweredBy string
AnsweredVia string
}
// Answer is what the run wakes with.
type Answer struct {
RequestID uuid.UUID `json:"request_id"`
Approved bool `json:"approved"`
By string `json:"by"`
Via string `json:"via"`
At time.Time `json:"at"`
}
// Approval is the authority this answer gives judgement to run the action.
func (a Answer) Approval(d judgement.Decision) judgement.Approval {
return judgement.Approval{DecisionID: d.ID, Digest: d.Action.Digest, By: a.By, At: a.At}
}
// View is a request as the API shows it.
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"`
// DecisionID is the judged action the request is about.
DecisionID uuid.UUID `json:"decision_id"`
RequestedAt time.Time `json:"requested_at"`
AnsweredBy string `json:"answered_by,omitzero"`
AnsweredVia string `json:"answered_via,omitzero"`
AnsweredAt time.Time `json:"answered_at,omitzero"`
}
// View is r as the API shows it.
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,
DecisionID: r.DecisionID, RequestedAt: r.RequestedAt,
AnsweredBy: r.AnsweredBy, 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 carries a request to every channel someone can answer on.
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 is where answers become autonomy: an approval counts toward raising
// an action class, a denial tightens it, and a raise a person approves
// loosens it.
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 is what the organisation decided about approvals.
type Policy interface {
ApprovalDeadline(ctx context.Context) (time.Duration, error)
RaiseAfter(ctx context.Context) (int, error)
}
// Module owns one organisation's approval requests.
type Module struct {
orgID string
store *store.Store
tell Delivery
wake Signaller
classes Classes
policy Policy
log *slog.Logger
now func() time.Time
}
// NewModule returns the approvals module for orgID. Answers are delivered by
// tell and wake the run through wake, and are counted into classes under
// policy.
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tell Delivery, wake Signaller, classes Classes, policy Policy) *Module {
return &Module{orgID: orgID, store: store.New(db), tell: tell, wake: wake, classes: classes, policy: policy, log: log, now: time.Now}
}
// Ask records a request for d and tells people about it. Asking again for the
// same run and key returns the request that stands, so a replayed step asks
// once.
func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, d judgement.Decision, deadline time.Time) (Request, error) {
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,
Summary: Summary(d), State: StatePending, Deadline: deadline.UTC(),
})
if err != nil {
return Request{}, err
}
r := requestOf(row, d)
if row.State != StatePending {
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.Deadline,
}); err != nil {
return Request{}, fmt.Errorf("send approval request: %w", err)
}
return r, nil
}
// Answer settles request id with a person's decision and wakes the run waiting
// on it. Only a pending request settles: a second answer, or one that arrives
// after the deadline, is refused and wakes nobody.
func (m *Module) Answer(ctx context.Context, id uuid.UUID, by, 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, by, 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: by, 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
}
// The run has what it waited for; the answer's bearing on the class comes
// after, so a failure here is reported without holding the run.
if err := m.learn(ctx, row, answer); err != nil {
return Request{}, err
}
return requestOf(row, judgement.Decision{}), nil
}
// learn counts an answer to an action into its class. An approval that
// completes a run of them earns a raise, which is put to a person.
func (m *Module) learn(ctx context.Context, row store.Request, a Answer) error {
if !a.Approved {
return m.classes.Denied(ctx, row.DecisionID)
}
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)
}
// askRaise puts a raise to a person on every channel. If it can't be asked the
// raise is withdrawn, so the class proposes it again at its next approval.
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 {
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 += " The class had changed since, so its level stays."
}
return m.tell.Told(ctx, deliveries.ApprovalRequest{
RequestID: row.ID, Key: row.Key + ":ask", Title: "Raise answered",
}, text)
}
// raiseSummary is what a person is shown about a raise: the class, the change
// and the approvals that earned it.
func raiseSummary(r *judgement.Raise) string {
c := r.Class
var s strings.Builder
fmt.Fprintf(&s, "%s: %s on %s in %s. Raise from %s to %s.\nEarned by %d approvals in a row:",
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 answers a request from an answer a channel delivered as an event. An
// answer that can't settle it, because it was already answered, has expired
// or names no request, reports false rather than an error: retrying the event
// would never change that.
func (m *Module) Settle(ctx context.Context, id uuid.UUID, by, via string, approved bool) (bool, error) {
_, err := m.Answer(ctx, id, by, 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
}
// Expire settles a request whose deadline passed, so the trail shows why it
// never ran.
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)
if err := m.tell.Told(ctx, deliveries.ApprovalRequest{
RunID: row.RunID, RequestID: row.ID, Key: row.Key + ":ask",
Title: "Approval expired", Body: "The request ran out of time, so nothing was run.",
}, "Expired without an answer."); err != nil {
return err
}
// The escalation goes to every channel. Its key is stable, so an Expire
// retried after a failed delivery sends it once.
return m.tell.Notify(ctx, deliveries.Notification{
RunID: row.RunID, Key: row.Key + ":expired",
Title: "Approval timed out: " + row.Connector + " " + row.Action,
Body: "Nobody answered before the deadline, so " + row.Connector + " " + row.Action + " did not run. " + 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 says what became of the requests made for the decisions in ids,
// for the history of the action class they belong to.
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
}
// Routes adds the approvals API to mux behind guard.
func (m *Module) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler) {
mux.Handle("GET /api/approvals", guard(http.HandlerFunc(m.list)))
mux.Handle("POST /api/approvals/{id}/answer", guard(http.HandlerFunc(m.answer)))
}
// bootstrapAdmin names the identity the bootstrap admin token stands for. It
// is recorded as the approver until identities exist.
const bootstrapAdmin = "admin"
type answerRequest struct {
Approved bool `json:"approved"`
}
func (m *Module) list(w http.ResponseWriter, r *http.Request) {
pending, err := m.Pending(r.Context())
if err != nil {
m.log.ErrorContext(r.Context(), "list approvals", "error", err)
httpjson.Error(w, http.StatusInternalServerError, "couldn't list approvals")
return
}
out := make([]View, 0, len(pending))
for _, p := range pending {
out = append(out, p.View())
}
httpjson.Write(w, http.StatusOK, out)
}
func (m *Module) answer(w http.ResponseWriter, r *http.Request) {
id, err := uuid.Parse(r.PathValue("id"))
if err != nil {
httpjson.Error(w, http.StatusBadRequest, "id is a request id")
return
}
var req answerRequest
if err := httpjson.Read(r, &req); err != nil {
httpjson.Error(w, http.StatusBadRequest, err.Error())
return
}
out, err := m.Answer(r.Context(), id, bootstrapAdmin, "composer", req.Approved)
switch {
case errors.Is(err, ErrNotFound):
httpjson.Error(w, http.StatusNotFound, "no such approval request")
return
case errors.Is(err, ErrAnswered), errors.Is(err, ErrExpired):
httpjson.Error(w, http.StatusConflict, err.Error())
return
case err != nil:
m.log.ErrorContext(r.Context(), "answer approval", "request", id, "error", err)
httpjson.Error(w, http.StatusInternalServerError, "couldn't record the answer")
return
}
httpjson.Write(w, http.StatusOK, out.View())
}
// pending reads a request that is still open and inside its deadline. The
// store settles only a pending row; this refuses the answer before that, with
// the reason.
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
}
// settleable says whether an answer now may settle r. A request settles once:
// a second answer, and one that arrives after the deadline, changes nothing.
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 is what a person is shown about the action they are asked to allow:
// what it does, to what, and what held it back.
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 isn't a flat 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, ", ")
}
// requestOf is a stored row as the module's Request.
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, Summary: row.Summary, State: row.State, Deadline: row.Deadline,
}
if row.AnsweredAt.Valid {
r.AnsweredAt = row.AnsweredAt.Time
}
if row.AnsweredBy.Valid {
r.AnsweredBy = row.AnsweredBy.String
}
if row.AnsweredVia.Valid {
r.AnsweredVia = row.AnsweredVia.String
}
return r
}