Files
archie/modules/approvals/approvals.go
T

432 lines
14 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"
"net/http"
"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")
)
// Request is one judged action waiting for a person's answer.
type Request struct {
ID uuid.UUID
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"`
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, 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
}
// Module owns one organisation's approval requests.
type Module struct {
orgID string
store *store.Store
tell Delivery
wake Signaller
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.
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tell Delivery, wake Signaller) *Module {
return &Module{orgID: orgID, store: store.New(db), tell: tell, wake: wake, 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, 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 err := m.wakeWith(ctx, row, answer); err != nil {
return Request{}, err
}
return requestOf(row, judgement.Decision{}), nil
}
// 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 in the %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
}
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
}
// requestOf is a stored row as the module's Request.
func requestOf(row store.Request, d judgement.Decision) Request {
r := Request{
ID: row.ID, 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
}