Files
archie/modules/proposals/api.go
T
sam 911152c9d1 merge: proposals module (#1995)
# Conflicts:
#	internal/platform/pg/migrations/00008_drafts.sql
#	modules/drafts/drafts.go
#	modules/drafts/internal/store/store.go
2026-11-24 03:11:07 +11:00

488 lines
18 KiB
Go

package proposals
import (
"context"
"encoding/json/jsontext"
"errors"
"net/http"
"time"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
"github.com/samcharles93/archie-core/modules/approvals"
"github.com/samcharles93/archie-core/modules/governance"
"github.com/samcharles93/archie-core/modules/judgement"
"github.com/samcharles93/archie-core/modules/proposals/internal/store"
"github.com/samcharles93/archie-core/modules/runs"
)
// Register adds the proposals API.
func (m *Module) Register(api huma.API) {
tags := []string{"Proposals"}
httpapi.Register(api, httpapi.Authorized(governance.ActionRead, governance.KindProposal), huma.Operation{
OperationID: "list-proposals", Method: http.MethodGet, Path: "/api/proposals",
Summary: "List proposals", Tags: tags,
}, m.list)
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionCreate, governance.KindProposal), huma.Operation{
OperationID: "propose", Method: http.MethodPost, Path: "/api/proposals",
Summary: "Propose a change, judging the actions it will take", Tags: tags,
}, m.propose)
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionCreate, governance.KindProposal), huma.Operation{
OperationID: "propose-for-group", Method: http.MethodPost, Path: "/api/groups/{id}/proposal",
Summary: "Propose a trigger and workflow for a group of unmatched events", Tags: tags,
}, m.proposeForGroup)
httpapi.Register(api, httpapi.Authorized(governance.ActionRead, governance.KindProposal), huma.Operation{
OperationID: "get-proposal", Method: http.MethodGet, Path: "/api/proposals/{id}",
Summary: "Get a proposal", Tags: tags,
}, m.getProposal)
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindProposal), huma.Operation{
OperationID: "edit-proposal", Method: http.MethodPut, Path: "/api/proposals/{id}",
Summary: "Change a trigger proposal's name, workflow and policy", Tags: tags,
}, m.editProposal)
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRun, governance.KindWorkflow), huma.Operation{
OperationID: "dry-run-proposal", Method: http.MethodPost, Path: "/api/proposals/{id}/dry-run",
Summary: "Replay a stored event against a trigger proposal's workflow and policy in a dry run", Tags: tags,
}, m.dryRunProposal)
httpapi.Register(api, httpapi.Authorized(governance.ActionApprove, governance.KindProposal), huma.Operation{
OperationID: "approve-proposal", Method: http.MethodPost, Path: "/api/proposals/{id}/approve",
Summary: "Approve a proposal and its actions as the signed-in person, which applies it", Tags: tags,
}, m.approve)
httpapi.Register(api, httpapi.Authorized(governance.ActionApprove, governance.KindProposal), huma.Operation{
OperationID: "begin-proposal-confirmation", Method: http.MethodPost, Path: "/api/proposals/{id}/confirmation",
Summary: "Start the passkey confirmation that approving an irreversible action needs", Tags: tags,
}, m.beginConfirmation)
httpapi.Register(api, httpapi.Authorized(governance.ActionApprove, governance.KindProposal), huma.Operation{
OperationID: "reject-proposal", Method: http.MethodPost, Path: "/api/proposals/{id}/reject",
Summary: "Reject a proposal and record why", Tags: tags,
}, m.reject)
}
// View is the API representation of a proposal.
type View struct {
ID uuid.UUID `json:"id"`
Kind string `json:"kind" enum:"root_cause_fix,trigger,workflow_change,ceiling_raise,policy_change"`
State string `json:"state" enum:"pending,approved,rejected,published,superseded,withdrawn"`
// Needs is who must approve: the owner, or a person with authority over
// policies.
Needs string `json:"needs" enum:"owner,authority"`
Title string `json:"title"`
Summary string `json:"summary"`
Evidence jsontext.Value `json:"evidence"`
// Change is what approving the proposal writes. A trigger proposal reports
// it as Trigger instead.
Change jsontext.Value `json:"change,omitzero"`
Trigger *Trigger `json:"trigger,omitzero"`
TargetKind string `json:"target_kind"`
TargetID string `json:"target_id,omitzero"`
// Actions are the actions the proposal takes once approved, in order, each
// with the judgement shown when it was proposed.
Actions []ActionView `json:"actions"`
PromptedBy []uuid.UUID `json:"prompted_by"`
RunID *uuid.UUID `json:"run_id,omitzero"`
ProposedByID string `json:"proposed_by_id"`
CreatedAt time.Time `json:"created_at"`
// AnsweredByID is the answering account's identity ID.
AnsweredByID string `json:"answered_by_id,omitzero"`
AnsweredAt *time.Time `json:"answered_at,omitzero"`
AnswerReason string `json:"answer_reason,omitzero"`
PublishedAt *time.Time `json:"published_at,omitzero"`
}
// Trigger is the trigger a trigger proposal adds.
type Trigger struct {
GroupID uuid.UUID `json:"group_id"`
Name string `json:"name"`
SourceID uuid.UUID `json:"source_id"`
EventType string `json:"event_type"`
Filter jsontext.Value `json:"filter"`
// Workflow is the workflow document the trigger would start.
Workflow string `json:"workflow"`
PolicyKind string `json:"policy_kind" enum:"hard_rules,change_request"`
// Policy is Cedar policy text added to the set in force when approved.
Policy string `json:"policy"`
// DryRun reports the latest dry run since the proposal was last edited.
DryRun *runs.DryReport `json:"dry_run,omitzero"`
DryEventID *uuid.UUID `json:"dry_event_id,omitzero"`
InstalledVersion *int `json:"installed_version,omitzero"`
}
// ActionView is a proposed action and the judgement it was shown with.
type ActionView struct {
Seq int `json:"seq"`
Connector string `json:"connector"`
Action string `json:"action"`
TargetKind string `json:"target_kind"`
TargetID string `json:"target_id"`
Input jsontext.Value `json:"input"`
DecisionID uuid.UUID `json:"decision_id"`
// Level is how far judgement lets the action run.
Level string `json:"level,omitzero"`
Reason string `json:"reason,omitzero"`
RefusedBy string `json:"refused_by,omitzero"`
Verdicts []judgement.Verdict `json:"verdicts,omitzero"`
// State is how the action ended once the proposal was approved: pending
// until its run takes it.
State string `json:"state" enum:"pending,ran,failed,unknown,refused,skipped"`
Outcome string `json:"outcome,omitzero"`
SettledAt *time.Time `json:"settled_at,omitzero"`
}
func (m *Module) get(ctx context.Context, id uuid.UUID) (View, error) {
p, actions, decisions, err := m.load(ctx, id)
if err != nil {
return View{}, err
}
return m.view(ctx, p, actions, decisions)
}
func (m *Module) view(ctx context.Context, p store.Proposal, actions []store.Action, decisions []judgement.Decision) (View, error) {
v := View{
ID: p.ID, Kind: p.Kind, State: p.State, Needs: p.Needs, Title: p.Title, Summary: p.Summary,
Evidence: p.Evidence, TargetKind: p.TargetKind, TargetID: p.TargetID, PromptedBy: []uuid.UUID{},
ProposedByID: p.ProposedByID, CreatedAt: p.CreatedAt, AnswerReason: p.AnswerReason,
Actions: make([]ActionView, 0, len(actions)),
}
if err := unmarshalIDs(p.PromptedBy, &v.PromptedBy); err != nil {
return View{}, err
}
if p.RunID.Valid {
v.RunID = &p.RunID.UUID
}
if p.AnsweredByID.Valid {
v.AnsweredByID = p.AnsweredByID.String
}
if p.AnsweredAt.Valid {
v.AnsweredAt = &p.AnsweredAt.Time
}
if p.PublishedAt.Valid {
v.PublishedAt = &p.PublishedAt.Time
}
if p.Kind == KindTrigger {
t, err := m.triggerView(ctx, p)
if err != nil {
return View{}, err
}
v.Trigger = &t
} else {
v.Change = p.Change
}
byID := make(map[uuid.UUID]judgement.Decision, len(decisions))
for _, d := range decisions {
byID[d.ID] = d
}
for _, a := range actions {
av := ActionView{
Seq: a.Seq, Connector: a.Connector, Action: a.Action, TargetKind: a.TargetKind, TargetID: a.TargetID,
Input: a.Input, DecisionID: a.DecisionID, State: a.State, Outcome: a.Outcome,
}
if a.SettledAt.Valid {
av.SettledAt = &a.SettledAt.Time
}
if d, ok := byID[a.DecisionID]; ok {
av.Level, av.Reason, av.RefusedBy, av.Verdicts = d.Level.String(), d.Reason, d.RefusedBy, d.Verdicts
}
v.Actions = append(v.Actions, av)
}
return v, nil
}
func (m *Module) triggerView(ctx context.Context, p store.Proposal) (Trigger, error) {
c, err := readTrigger(p)
if err != nil {
return Trigger{}, err
}
filter, err := evidenceOf(c.Filter)
if err != nil {
return Trigger{}, err
}
t := Trigger{
GroupID: c.GroupID, Name: c.Name, SourceID: c.SourceID, EventType: c.EventType, Filter: filter,
Workflow: c.Workflow, PolicyKind: c.PolicyKind, Policy: c.Policy, DryEventID: c.DryEventID,
InstalledVersion: c.InstalledVersion,
}
if c.DryRunID != nil {
rep, ok, err := m.workflows.DryReport(ctx, m.orgID, *c.DryRunID)
if err != nil {
return Trigger{}, errors.Join(errors.New("read dry run"), err)
}
if ok {
t.DryRun = &rep
}
}
return t, nil
}
type idInput struct {
ID string `path:"id" format:"uuid"`
}
type listInput struct {
State string `query:"state" enum:"pending,approved,rejected,published,superseded,withdrawn" doc:"Only proposals in this state"`
}
func (m *Module) list(ctx context.Context, in *listInput) (*httpapi.Reply[[]View], error) {
rows, err := m.store.List(ctx, m.orgID, in.State)
if err != nil {
return nil, m.fail(ctx, "list proposals", err)
}
out := make([]View, 0, len(rows))
for _, p := range rows {
actions, err := m.store.Actions(ctx, p.ID)
if err != nil {
return nil, m.fail(ctx, "read proposal", err)
}
v, err := m.view(ctx, p, actions, nil)
if err != nil {
return nil, m.fail(ctx, "read proposal", err)
}
out = append(out, v)
}
return httpapi.OK(out), nil
}
type proposeInput struct {
Body struct {
Kind string `json:"kind" enum:"root_cause_fix,workflow_change,policy_change"`
Title string `json:"title"`
Summary string `json:"summary"`
Evidence jsontext.Value `json:"evidence,omitzero"`
Change jsontext.Value `json:"change" doc:"What approving writes: {cause} for a root-cause fix, {name, workflow} for a workflow change, {policy_kind, policy} for a policy change"`
TargetKind string `json:"target_kind"`
TargetID string `json:"target_id,omitzero"`
Actions []struct {
Connector string `json:"connector"`
Action string `json:"action"`
Input jsontext.Value `json:"input,omitzero"`
} `json:"actions,omitzero" doc:"The actions to take once approved, judged now and shown with the proposal"`
}
}
func (m *Module) propose(ctx context.Context, in *proposeInput) (*httpapi.Reply[View], error) {
b := in.Body
n := NewProposal{
Kind: b.Kind, Title: b.Title, Summary: b.Summary, Evidence: b.Evidence, Change: b.Change,
TargetKind: b.TargetKind, TargetID: b.TargetID,
}
for _, a := range b.Actions {
n.Actions = append(n.Actions, NewAction{Connector: a.Connector, Action: a.Action, Input: a.Input})
}
v, err := m.Propose(ctx, n)
if err != nil {
return nil, m.problem(ctx, "propose", err)
}
return httpapi.OK(v), nil
}
func (m *Module) proposeForGroup(ctx context.Context, in *idInput) (*httpapi.Reply[View], error) {
id, err := uuid.Parse(in.ID)
if err != nil {
return nil, huma.Error400BadRequest("ID must be a UUID")
}
g, found, err := m.groups.Group(ctx, id)
switch {
case err != nil:
return nil, m.fail(ctx, "read group", err)
case !found:
return nil, huma.Error404NotFound("no such group")
}
p, err := m.proposeTrigger(ctx, g)
if err != nil {
return nil, m.problem(ctx, "propose a trigger", err)
}
return m.respond(ctx, p.ID)
}
func (m *Module) getProposal(ctx context.Context, in *idInput) (*httpapi.Reply[View], error) {
id, err := parseID(in.ID)
if err != nil {
return nil, err
}
return m.respond(ctx, id)
}
type editInput struct {
ID string `path:"id" format:"uuid"`
Body struct {
Name string `json:"name"`
Workflow string `json:"workflow" doc:"The workflow document"`
PolicyKind string `json:"policy_kind" enum:"hard_rules,change_request"`
Policy string `json:"policy,omitzero" doc:"Cedar policy text added when the proposal is approved"`
}
}
func (m *Module) editProposal(ctx context.Context, in *editInput) (*httpapi.Reply[View], error) {
p, err := m.pendingTrigger(ctx, in.ID)
if err != nil {
return nil, err
}
req := in.Body
if err := m.check(ctx, req.Name, req.Workflow, req.PolicyKind, req.Policy); err != nil {
return nil, invalid(err)
}
if err := m.edit(ctx, p, req.Name, req.Workflow, req.PolicyKind, req.Policy); err != nil {
return nil, m.problem(ctx, "edit proposal", err)
}
return m.respond(ctx, p.ID)
}
type dryRunInput struct {
ID string `path:"id" format:"uuid"`
Body *struct {
EventID uuid.UUID `json:"event_id,omitzero" doc:"The stored event to replay; the newest by default"`
}
}
func (m *Module) dryRunProposal(ctx context.Context, in *dryRunInput) (*httpapi.Reply[View], error) {
p, err := m.pendingTrigger(ctx, in.ID)
if err != nil {
return nil, err
}
var eventID uuid.UUID
if in.Body != nil {
eventID = in.Body.EventID
}
if err := m.dryRun(ctx, p, eventID); err != nil {
return nil, m.problem(ctx, "dry run", err)
}
return m.respond(ctx, p.ID)
}
type approveInput struct {
ID string `path:"id" format:"uuid"`
Body *struct {
// Assertion is the passkey assertion that approving an action that
// can't be undone needs.
Assertion *approvals.Assertion `json:"assertion,omitzero"`
}
}
func (m *Module) approve(ctx context.Context, in *approveInput) (*httpapi.Reply[View], error) {
id, err := parseID(in.ID)
if err != nil {
return nil, err
}
var assertion *approvals.Assertion
if in.Body != nil {
assertion = in.Body.Assertion
}
v, err := m.Approve(ctx, id, assertion)
if err != nil {
return nil, m.problem(ctx, "approve", err)
}
return httpapi.OK(v), nil
}
func (m *Module) beginConfirmation(ctx context.Context, in *idInput) (*httpapi.Reply[approvals.Confirmation], error) {
id, err := parseID(in.ID)
if err != nil {
return nil, err
}
ceremony, err := m.Confirmation(ctx, id)
switch {
case errors.Is(err, governance.ErrNoPasskey):
return nil, huma.Error409Conflict("Add a passkey to your account to approve this proposal.")
case err != nil:
return nil, m.problem(ctx, "start the confirmation", err)
}
return httpapi.OK(approvals.Confirmation{Token: ceremony.Token, Options: jsontext.Value(ceremony.Options)}), nil
}
type rejectInput struct {
ID string `path:"id" format:"uuid"`
Body struct {
Reason string `json:"reason" doc:"Why the proposal is turned down; it is kept with the proposal"`
}
}
func (m *Module) reject(ctx context.Context, in *rejectInput) (*httpapi.Reply[View], error) {
id, err := parseID(in.ID)
if err != nil {
return nil, err
}
v, err := m.Reject(ctx, id, in.Body.Reason)
if err != nil {
return nil, m.problem(ctx, "reject", err)
}
return httpapi.OK(v), nil
}
func parseID(raw string) (uuid.UUID, error) {
id, err := uuid.Parse(raw)
if err != nil {
return uuid.Nil, huma.Error400BadRequest("ID must be a UUID")
}
return id, nil
}
// pendingTrigger returns a trigger proposal that can still be edited.
func (m *Module) pendingTrigger(ctx context.Context, rawID string) (store.Proposal, error) {
id, err := parseID(rawID)
if err != nil {
return store.Proposal{}, err
}
p, err := m.store.ByID(ctx, m.orgID, id)
switch {
case errors.Is(err, store.ErrNotFound):
return store.Proposal{}, huma.Error404NotFound("no such proposal")
case err != nil:
return store.Proposal{}, m.fail(ctx, "read proposal", err)
case p.Kind != KindTrigger:
return store.Proposal{}, huma.Error409Conflict("only a trigger proposal has a workflow to edit or test")
case p.State != StatePending:
return store.Proposal{}, huma.Error409Conflict("a proposal that was answered can't be changed")
}
return p, nil
}
func (m *Module) respond(ctx context.Context, id uuid.UUID) (*httpapi.Reply[View], error) {
v, err := m.get(ctx, id)
if err != nil {
return nil, m.problem(ctx, "read proposal", err)
}
return httpapi.OK(v), nil
}
func invalid(err error) error {
var problem *runs.InvalidError
switch {
case errors.As(err, &problem):
return runs.Problems(problem)
case errors.Is(err, judgement.ErrInvalidPolicy):
return huma.Error400BadRequest(err.Error(), &huma.ErrorDetail{Location: "policy", Message: err.Error()})
default:
return huma.Error500InternalServerError("couldn't check the proposal")
}
}
// problem turns an error into the response for the person who caused it, and
// logs the ones that are the server's own.
func (m *Module) problem(ctx context.Context, what string, err error) error {
var invalidDoc *runs.InvalidError
switch {
case errors.Is(err, ErrNotFound):
return huma.Error404NotFound("no such proposal")
case errors.Is(err, ErrAnswered), errors.Is(err, ErrNotBound), errors.Is(err, errNoEvent):
return huma.Error409Conflict(err.Error())
case errors.Is(err, ErrTaken):
return huma.Error409Conflict(err.Error())
case errors.Is(err, approvals.ErrNeedsFreshAuthentication):
return huma.NewError(http.StatusPreconditionRequired, err.Error())
case errors.Is(err, ErrNotSignedIn), errors.Is(err, ErrNotApprover), errors.Is(err, approvals.ErrFreshAuthenticationFailed):
return huma.Error403Forbidden(err.Error())
case errors.Is(err, ErrNoConfirmation):
return huma.Error409Conflict(err.Error())
case errors.Is(err, ErrReasonRequired), errors.Is(err, ErrInvalid), errors.Is(err, ErrRefused):
return huma.Error422UnprocessableEntity(err.Error())
case errors.As(err, &invalidDoc), errors.Is(err, judgement.ErrInvalidPolicy):
return invalid(err)
}
return m.fail(ctx, what, err)
}
func (m *Module) fail(ctx context.Context, what string, err error) error {
m.log.ErrorContext(ctx, what, "error", err)
return huma.Error500InternalServerError("couldn't " + what)
}