723 lines
25 KiB
Go
723 lines
25 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"
|
|
"database/sql"
|
|
"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/governance"
|
|
"github.com/samcharles93/archie-core/modules/judgement"
|
|
)
|
|
|
|
// The states a request can be in. A settled request never changes again,
|
|
// except that an approval the action no longer matched is discarded.
|
|
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")
|
|
// ErrUnverified means the answer came from an identity no person holds.
|
|
ErrUnverified = errors.New("that identity isn't held by any person, so its answer is refused")
|
|
// ErrNotApprover means the person may not answer approvals for actions.
|
|
ErrNotApprover = errors.New("that person isn't the default owner, on the escalation path or an authority, so their answer is refused")
|
|
// ErrNotAsked means the request hasn't yet reached that person on its
|
|
// escalation path.
|
|
ErrNotAsked = errors.New("that person hasn't been asked yet, so their answer is refused")
|
|
// ErrNeedsAuthority means the action needs a person with authority, and
|
|
// the answer came from one without.
|
|
ErrNeedsAuthority = errors.New("that action needs a person with authority, so their answer is refused")
|
|
// ErrNoAuthority means the answer to a raise came from a person without
|
|
// authority over policy and ceilings.
|
|
ErrNoAuthority = errors.New("that person holds no authority over policy and ceilings, so their answer to a raise is refused")
|
|
)
|
|
|
|
// 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 is when the request runs out for good: the end of the last
|
|
// escalation step.
|
|
Deadline time.Time
|
|
// Step is the escalation step the request is at, and StepDeadline when it
|
|
// moves on.
|
|
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
|
|
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"`
|
|
// Step is the escalation step the request is at, and StepDeadline when it
|
|
// moves to the next.
|
|
Step int `json:"step"`
|
|
StepDeadline time.Time `json:"step_deadline,omitzero"`
|
|
// 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, Step: r.Step, StepDeadline: r.StepDeadline,
|
|
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)
|
|
}
|
|
|
|
// People says who an identity belongs to. An answer from an identity it
|
|
// doesn't verify is refused.
|
|
type People interface {
|
|
Verify(ctx context.Context, identity string) (governance.Verified, bool, error)
|
|
}
|
|
|
|
// Module owns one organisation's approval requests.
|
|
type Module struct {
|
|
orgID string
|
|
store *store.Store
|
|
tell Delivery
|
|
wake Signaller
|
|
classes Classes
|
|
policy Policy
|
|
people People
|
|
changes ChangeRequests
|
|
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. An answer a channel delivers is accepted only from an identity
|
|
// people verifies.
|
|
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tell Delivery, wake Signaller, classes Classes, policy Policy, people People) *Module {
|
|
return &Module{
|
|
orgID: orgID, store: store.New(db), tell: tell, wake: wake, classes: classes, policy: policy, people: people,
|
|
log: log, now: time.Now,
|
|
}
|
|
}
|
|
|
|
// Ask records a request for d and puts it to the first step of path. It runs
|
|
// out for good when the last step does. Asking again for the same run and key
|
|
// returns the request that stands, so a replayed step asks once. An action
|
|
// judgement's change-request rules pick goes through a change request when a
|
|
// change-request connector is installed, and every other one through the
|
|
// approvers' channels.
|
|
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()
|
|
}
|
|
asked := []string{}
|
|
if path[0].Person != "" {
|
|
asked = append(asked, path[0].Person)
|
|
}
|
|
askedJSON, err := json.Marshal(asked)
|
|
if err != nil {
|
|
return Request{}, fmt.Errorf("encode asked: %w", err)
|
|
}
|
|
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: now.Add(total),
|
|
StepDeadline: sql.NullTime{Time: now.Add(path[0].Deadline()), Valid: true}, Asked: string(askedJSON),
|
|
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
|
|
}
|
|
|
|
// answerAs settles request id with a verified 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) answerAs(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. A denial tightens the class now. An
|
|
// approval counts only once the action is about to run on it, so one that
|
|
// is discarded first counts for nothing.
|
|
if !answer.Approved {
|
|
if err := m.classes.Denied(ctx, row.DecisionID); err != nil {
|
|
return Request{}, err
|
|
}
|
|
}
|
|
return requestOf(row, judgement.Decision{}), nil
|
|
}
|
|
|
|
// learn counts an approval of 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 {
|
|
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,
|
|
// given by identity (such as "telegram:1001"). An answer from an identity no
|
|
// person holds, or from a person who may not answer that kind of request, is
|
|
// refused and the refusal recorded with its reason. An answer that can't
|
|
// settle the request, because it was already answered, has expired or names no
|
|
// request, also reports false rather than an error: retrying the event would
|
|
// never change that.
|
|
func (m *Module) Settle(ctx context.Context, id uuid.UUID, identity, 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
|
|
}
|
|
who, err := m.verify(ctx, identity, row)
|
|
if refusal(err) {
|
|
m.log.WarnContext(ctx, "approval answer refused", "request", id, "identity", identity, "reason", err.Error())
|
|
return false, 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(),
|
|
})
|
|
}
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
_, err = m.answerAs(ctx, id, who.Name+" ("+identity+")", 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
|
|
}
|
|
|
|
// verify says whether identity may answer request row. An action is answered
|
|
// by someone who answers for actions and whom the request has reached on its
|
|
// escalation path, or who holds authority, and an action at the escalate level
|
|
// needs authority. A raise changes policy, so only a person with authority
|
|
// answers it.
|
|
func (m *Module) verify(ctx context.Context, identity string, row store.Request) (governance.Verified, error) {
|
|
who, ok, err := m.people.Verify(ctx, identity)
|
|
if err != nil {
|
|
return governance.Verified{}, fmt.Errorf("verify %s: %w", identity, err)
|
|
}
|
|
if !ok {
|
|
return governance.Verified{}, ErrUnverified
|
|
}
|
|
return who, mayAnswer(who, row)
|
|
}
|
|
|
|
func mayAnswer(who governance.Verified, row store.Request) error {
|
|
switch {
|
|
case row.Kind == KindRaise && !who.Authority:
|
|
return ErrNoAuthority
|
|
case row.Kind == KindRaise:
|
|
return nil
|
|
case !who.Approver && !slices.Contains(askedOf(row), who.ID):
|
|
return ErrNotApprover
|
|
case row.Level == judgement.Escalate.String() && !who.Authority:
|
|
return ErrNeedsAuthority
|
|
case !who.Authority && !slices.Contains(askedOf(row), who.ID):
|
|
return ErrNotAsked
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// askedOf is the ids of the people the request has reached.
|
|
func askedOf(row store.Request) []string {
|
|
var ids []string
|
|
if err := json.Unmarshal([]byte(row.Asked), &ids); err != nil {
|
|
return nil
|
|
}
|
|
return ids
|
|
}
|
|
|
|
// refusal reports whether err is a refused answer rather than a failure.
|
|
func refusal(err error) bool {
|
|
return errors.Is(err, ErrUnverified) || errors.Is(err, ErrNotApprover) || errors.Is(err, ErrNoAuthority) ||
|
|
errors.Is(err, ErrNotAsked) || errors.Is(err, ErrNeedsAuthority)
|
|
}
|
|
|
|
// Expire settles a request whose last escalation step ran out, so the trail
|
|
// shows why it never ran. Nothing is acted on, an open change request is
|
|
// withdrawn, and the report goes to every channel. Expiry says nothing about
|
|
// the action's class, so it is not tightened.
|
|
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 request ran out of time, so nothing was run." + withdrawn,
|
|
}, "Expired without an answer."); err != nil {
|
|
return err
|
|
}
|
|
// The report 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 last escalation step ran out, 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 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. The
|
|
// token guard has already authenticated it, so it counts as a person with
|
|
// authority and skips the people check until real sign-in exists.
|
|
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.answerAs(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,
|
|
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.AnsweredVia.Valid {
|
|
r.AnsweredVia = row.AnsweredVia.String
|
|
}
|
|
return r
|
|
}
|