Files
archie/modules/proposals/proposals.go
T

656 lines
22 KiB
Go

// Package proposals holds the changes Archie proposes, with their evidence: a
// root-cause fix, a trigger and workflow for unmatched events, a workflow or
// policy change. A proposal can list the actions it will take. They are judged
// when it is proposed and shown with it, and approving the proposal approves
// exactly those actions, which a run then takes once. A policy change needs a
// person with authority over policies, and any other change needs the owner.
// A rejection keeps its reason.
package proposals
import (
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"fmt"
"log/slog"
"strings"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/samcharles93/archie-core/modules/approvals"
"github.com/samcharles93/archie-core/modules/connectors"
"github.com/samcharles93/archie-core/modules/events"
"github.com/samcharles93/archie-core/modules/governance"
"github.com/samcharles93/archie-core/modules/judgement"
"github.com/samcharles93/archie-core/modules/memory"
"github.com/samcharles93/archie-core/modules/proposals/internal/store"
"github.com/samcharles93/archie-core/modules/runs"
)
// The kinds of proposal.
const (
KindRootCauseFix = "root_cause_fix"
KindTrigger = "trigger"
KindWorkflowChange = "workflow_change"
KindPolicyChange = "policy_change"
)
// The states of a proposal. An approved proposal is applied and then
// published; a rejected one stays as the record of why.
const (
StatePending = "pending"
StateApproved = "approved"
StateRejected = "rejected"
StatePublished = "published"
)
// Who must approve a proposal.
const (
NeedsOwner = "owner"
NeedsAuthority = "authority"
)
var (
// 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 a proposal")
// ErrNotApprover means the person may not answer this proposal.
ErrNotApprover = errors.New("you may not answer this proposal")
// ErrAnswered means the proposal is not waiting for an answer.
ErrAnswered = store.ErrAnswered
// ErrNotFound means no such proposal.
ErrNotFound = store.ErrNotFound
// ErrTaken means a workflow or another proposal already uses the name.
ErrTaken = store.ErrTaken
// ErrRefused means judgement refuses one of the proposed actions.
ErrRefused = errors.New("judgement refuses a proposed action")
// ErrInvalid means the proposal is not one that can be made.
ErrInvalid = errors.New("invalid proposal")
// ErrNoConfirmation means the proposal needs no passkey confirmation, or the
// instance can't give one.
ErrNoConfirmation = errors.New("that proposal can't be confirmed with a passkey")
// ErrReasonRequired means a rejection did not say why.
ErrReasonRequired = errors.New("a rejection needs a reason")
)
// workInterval is how often approved proposals that are not yet applied are
// picked up again.
const workInterval = 5 * time.Second
// Groups provides unmatched event groups, replay tracking and trigger storage.
type Groups interface {
Group(ctx context.Context, id uuid.UUID) (events.Group, bool, error)
GroupEvents(ctx context.Context, id uuid.UUID, limit int) ([]events.Stored, error)
Replayed(ctx context.Context, eventID uuid.UUID, trigger string, runID uuid.UUID) error
SaveTrigger(ctx context.Context, t events.TriggerSpec) error
}
// Workflows installs workflow documents, starts runs and manages dry runs.
type Workflows interface {
Install(ctx context.Context, orgID, name, body, by string) (uuid.UUID, int, error)
WorkflowNamed(ctx context.Context, orgID, name string) (uuid.UUID, error)
Start(ctx context.Context, req runs.StartRequest) (uuid.UUID, error)
StartDry(ctx context.Context, req runs.DryRequest) (uuid.UUID, error)
DryReport(ctx context.Context, orgID string, id uuid.UUID) (runs.DryReport, bool, error)
}
// Policies validates a policy against the current policy set and adds it when
// its proposal is approved.
type Policies interface {
Check(ctx context.Context, kind, extra string) error
Append(ctx context.Context, kind, extra, by string) (judgement.PolicySetView, error)
}
// Judge judges a proposed action and returns the decisions recorded for a
// proposal.
type Judge interface {
Assess(ctx context.Context, req judgement.Request) (judgement.Decision, error)
ForRun(ctx context.Context, runID uuid.UUID) ([]judgement.Decision, error)
}
// Module holds one organisation's proposals.
type Module struct {
orgID string
store *store.Store
groups Groups
workflows Workflows
policies Policies
judge Judge
authz governance.Authorizer
confirm approvals.Confirmer
log *slog.Logger
}
// NewModule returns the proposals module for orgID.
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, g Groups, w Workflows, p Policies, j Judge) *Module {
return &Module{orgID: orgID, store: store.New(db), groups: g, workflows: w, policies: p, judge: j, log: log}
}
// UseAuthorizer attaches the access policies an answer is judged against.
// Until one is attached, no answer is accepted.
func (m *Module) UseAuthorizer(a governance.Authorizer) { m.authz = a }
// UseConfirmer configures the passkey check behind approving a proposal whose
// actions can't be undone. Without one, such a proposal can't be approved.
func (m *Module) UseConfirmer(c approvals.Confirmer) { m.confirm = c }
// confirmationSubject ties a passkey ceremony to one proposal.
func confirmationSubject(id uuid.UUID) string { return "proposal:" + id.String() }
// irreversible reports whether any of the proposal's actions can't be undone.
func irreversible(decisions []judgement.Decision) bool {
for _, d := range decisions {
if approvals.Irreversible(d.Action) {
return true
}
}
return false
}
// confirmed checks the passkey assertion approving an irreversible action
// needs.
func (m *Module) confirmed(ctx context.Context, id uuid.UUID, a *approvals.Assertion) error {
if m.confirm == nil || a == nil || a.Token == "" || len(a.Credential) == 0 {
return approvals.ErrNeedsFreshAuthentication
}
err := m.confirm.Confirm(ctx, a.Token, a.Credential, confirmationSubject(id))
switch {
case errors.Is(err, governance.ErrCredentialRejected):
return approvals.ErrFreshAuthenticationFailed
case err != nil:
return fmt.Errorf("check passkey confirmation: %w", err)
}
return nil
}
// NewProposal is a change to propose and the actions it will take.
type NewProposal struct {
Kind string
Title string
Summary string
Evidence jsontext.Value
// Change is what approving the proposal writes: for a workflow change the
// name and workflow, for a policy change the policy kind and policy, for a
// root-cause fix the cause.
Change jsontext.Value
TargetKind string
TargetID string
PromptedBy []uuid.UUID
// OriginRunID is the run that produced the proposal, if one did.
OriginRunID uuid.UUID
ProposedByID string
Actions []NewAction
}
// NewAction is an action a proposal will take once it is approved.
type NewAction struct {
Connector string
Action string
Input jsontext.Value
}
// Propose records a proposal after judging each of its actions. The proposal
// is shown with the decisions, and approving it approves those actions and no
// others. A proposal for a cause that already has an open root-cause proposal
// refreshes that one instead.
func (m *Module) Propose(ctx context.Context, n NewProposal) (View, error) {
change, needs, err := m.checkProposal(ctx, n)
if err != nil {
return View{}, err
}
id := uuid.New()
actions := make([]store.Action, 0, len(n.Actions))
for i, a := range n.Actions {
stored, err := m.judged(ctx, id, i, a)
if err != nil {
return View{}, err
}
actions = append(actions, stored)
}
promptedBy, err := json.Marshal(append([]uuid.UUID{}, n.PromptedBy...))
if err != nil {
return View{}, fmt.Errorf("encode the prompting events: %w", err)
}
if n.ProposedByID == "" {
n.ProposedByID = callerID(ctx)
}
evidence := n.Evidence
if len(evidence) == 0 {
evidence = jsontext.Value(`{}`)
}
p := store.Proposal{
ID: id, OrgID: m.orgID, Kind: n.Kind, Needs: needs, Title: n.Title, Summary: n.Summary,
Evidence: evidence, Change: change, TargetKind: n.TargetKind, TargetID: n.TargetID,
PromptedBy: promptedBy, OriginRunID: uuid.NullUUID{UUID: n.OriginRunID, Valid: n.OriginRunID != uuid.Nil},
ProposedByID: n.ProposedByID,
}
created, err := m.store.Create(ctx, p, actions)
if err != nil {
return View{}, err
}
if !created {
return m.refreshOpen(ctx, p)
}
return m.get(ctx, id)
}
// refreshOpen updates the open root-cause proposal that kept p out with the
// newer evidence, and returns it.
func (m *Module) refreshOpen(ctx context.Context, p store.Proposal) (View, error) {
if p.Kind != KindRootCauseFix {
return View{}, fmt.Errorf("%w: an equivalent proposal is already open", ErrTaken)
}
var c struct {
Cause string `json:"cause"`
}
if err := json.Unmarshal(p.Change, &c); err != nil {
return View{}, fmt.Errorf("read the cause: %w", err)
}
open, err := m.store.OpenRootCause(ctx, m.orgID, p.TargetKind, p.TargetID, c.Cause)
if err != nil {
return View{}, err
}
if open.State == StatePending {
if err := m.store.Refresh(ctx, m.orgID, open.ID, p.Summary, p.Evidence); err != nil && !errors.Is(err, ErrNotFound) {
return View{}, err
}
}
return m.get(ctx, open.ID)
}
// checkProposal validates a new proposal and returns its change and who it
// needs.
func (m *Module) checkProposal(ctx context.Context, n NewProposal) (jsontext.Value, string, error) {
if strings.TrimSpace(n.Title) == "" || strings.TrimSpace(n.Summary) == "" {
return nil, "", fmt.Errorf("%w: a title and a summary are required", ErrInvalid)
}
change := n.Change
if len(change) == 0 {
change = jsontext.Value(`{}`)
}
switch n.Kind {
case KindRootCauseFix:
var c struct {
Cause string `json:"cause"`
}
if err := json.Unmarshal(change, &c); err != nil || c.Cause == "" {
return nil, "", fmt.Errorf("%w: a root-cause fix names its cause", ErrInvalid)
}
return change, NeedsOwner, nil
case KindWorkflowChange:
var c struct {
Name string `json:"name"`
Workflow string `json:"workflow"`
}
if err := json.Unmarshal(change, &c); err != nil {
return nil, "", fmt.Errorf("%w: %w", ErrInvalid, err)
}
if !validName.MatchString(c.Name) {
return nil, "", fmt.Errorf("%w: name is lowercase letters, digits and hyphens, starting with a letter", ErrInvalid)
}
if _, err := runs.ParseDocument(c.Workflow); err != nil {
return nil, "", err
}
return change, NeedsOwner, nil
case KindPolicyChange:
var c struct {
PolicyKind string `json:"policy_kind"`
Policy string `json:"policy"`
}
if err := json.Unmarshal(change, &c); err != nil {
return nil, "", fmt.Errorf("%w: %w", ErrInvalid, err)
}
if strings.TrimSpace(c.Policy) == "" {
return nil, "", fmt.Errorf("%w: a policy change carries the policy", ErrInvalid)
}
if err := m.checkPolicy(ctx, c.PolicyKind, c.Policy); err != nil {
return nil, "", err
}
return change, NeedsAuthority, nil
}
return nil, "", fmt.Errorf("%w: %q is not a kind that can be proposed here", ErrInvalid, n.Kind)
}
// judged judges one proposed action. The decision is recorded against the
// proposal, so the same decision is shown and later approved.
func (m *Module) judged(ctx context.Context, proposal uuid.UUID, seq int, a NewAction) (store.Action, error) {
input := connectors.Canonical(a.Input)
if len(input) == 0 {
input = jsontext.Value(`{}`)
}
d, err := m.judge.Assess(ctx, judgement.Request{
RunID: proposal, Key: fmt.Sprintf("proposal:%s:%d", proposal, seq), Connector: a.Connector, Action: a.Action,
Input: input, Workflow: runs.ProposalWorkflow,
})
if err != nil {
return store.Action{}, fmt.Errorf("judge action %d: %w", seq, err)
}
if d.Level == judgement.Never {
return store.Action{}, fmt.Errorf("%w: %s %s: %s", ErrRefused, a.Connector, a.Action, d.Reason)
}
return store.Action{
ProposalID: proposal, Seq: seq, Connector: a.Connector, InstallationID: d.Action.Installation.ID, Action: a.Action,
TargetKind: d.Action.Target.Kind, TargetID: d.Action.Target.ID,
Input: input, Digest: d.Action.Digest, DecisionID: d.ID,
}, nil
}
// ProposeRootCause proposes a root-cause fix for a cause that keeps recurring
// on a target. There is at most one open proposal per target and cause.
func (m *Module) ProposeRootCause(ctx context.Context, req memory.FixRequest) error {
evidence, err := evidenceOf(map[string]any{"cause": req.Cause, "incidents": req.Incidents})
if err != nil {
return err
}
change, err := json.Marshal(map[string]string{"cause": req.Cause})
if err != nil {
return fmt.Errorf("encode the change: %w", err)
}
_, err = m.Propose(ctx, NewProposal{
Kind: KindRootCauseFix,
Title: fmt.Sprintf("Fix the recurring %s on %s %s", req.Cause, req.Target.Kind, req.Target.ID),
Summary: req.Summary, Evidence: evidence, Change: change,
TargetKind: req.Target.Kind, TargetID: req.Target.ID,
OriginRunID: req.RunID, ProposedByID: string(governance.SystemID),
})
return err
}
// Approve records the signed-in person's approval of a proposal and applies
// it. Approving a proposal approves its actions, each only as it was judged.
// The approval is durable once it returns, even if applying it fails: the work
// loop finishes an approved proposal.
func (m *Module) Approve(ctx context.Context, id uuid.UUID, assertion *approvals.Assertion) (View, error) {
p, actions, decisions, err := m.load(ctx, id)
if err != nil {
return View{}, err
}
if p.State != StatePending {
return View{}, ErrAnswered
}
who, err := m.mayAnswer(ctx, p, decisions)
if err != nil {
return View{}, err
}
if err := m.readyToApprove(ctx, p, actions, decisions, who); err != nil {
return View{}, err
}
if irreversible(decisions) {
if err := m.confirmed(ctx, id, assertion); err != nil {
return View{}, err
}
}
approved, err := m.store.Answer(ctx, m.orgID, id, StateApproved, who, "")
if err != nil {
return View{}, err
}
if err := m.apply(ctx, approved); err != nil {
m.log.ErrorContext(ctx, "apply approved proposal", "proposal", id, "error", err)
}
return m.get(ctx, id)
}
// readyToApprove refuses an approval that could not be applied: a trigger
// whose workflow name is taken or whose parts are invalid, or an action that
// would not be bound to the approval.
func (m *Module) readyToApprove(ctx context.Context, p store.Proposal, actions []store.Action, decisions []judgement.Decision, who string) error {
if p.Kind == KindTrigger {
c, err := readTrigger(p)
if err != nil {
return err
}
if err := m.check(ctx, c.Name, c.Workflow, c.PolicyKind, c.Policy); err != nil {
return err
}
switch _, err := m.workflows.WorkflowNamed(ctx, m.orgID, c.Name); {
case errors.Is(err, runs.ErrNoWorkflow):
case err != nil:
return fmt.Errorf("check the workflow name: %w", err)
default:
return fmt.Errorf("%w: a workflow named %s already exists; rename the proposal", ErrTaken, c.Name)
}
}
trial := p
trial.State = StateApproved
trial.AnsweredByID.String, trial.AnsweredByID.Valid = who, true
trial.AnsweredAt.Time, trial.AnsweredAt.Valid = time.Now(), true
_, err := bind(trial, actions, decisions)
return err
}
// Confirmation starts the passkey ceremony approving a proposal with an
// irreversible action needs.
func (m *Module) Confirmation(ctx context.Context, id uuid.UUID) (governance.PasskeyCeremony, error) {
p, _, decisions, err := m.load(ctx, id)
if err != nil {
return governance.PasskeyCeremony{}, err
}
if _, err := m.mayAnswer(ctx, p, decisions); err != nil {
return governance.PasskeyCeremony{}, err
}
if !irreversible(decisions) || m.confirm == nil {
return governance.PasskeyCeremony{}, ErrNoConfirmation
}
return m.confirm.BeginConfirmation(ctx, confirmationSubject(id))
}
// Reject records why the signed-in person turned a proposal down.
func (m *Module) Reject(ctx context.Context, id uuid.UUID, reason string) (View, error) {
reason = strings.TrimSpace(reason)
if reason == "" {
return View{}, ErrReasonRequired
}
p, _, decisions, err := m.load(ctx, id)
if err != nil {
return View{}, err
}
who, err := m.mayAnswer(ctx, p, decisions)
if err != nil {
return View{}, err
}
if _, err := m.store.Answer(ctx, m.orgID, id, StateRejected, who, reason); err != nil {
return View{}, err
}
return m.get(ctx, id)
}
// mayAnswer returns the identity ID of the signed-in person when their access
// lets them answer p: approving needs the approve action on the proposal,
// owned by whoever answers for its target, and a proposal that needs authority
// also needs the policy-management action.
func (m *Module) mayAnswer(ctx context.Context, p store.Proposal, decisions []judgement.Decision) (string, error) {
person, ok := governance.PrincipalFromContext(ctx)
if !ok || person.IdentityID == governance.SystemID || person.Kind != governance.KindUser {
return "", ErrNotSignedIn
}
if m.authz == nil {
return "", ErrNotApprover
}
actions := []governance.Action{governance.ActionApprove}
if p.Needs == NeedsAuthority {
actions = append(actions, governance.ActionManagePolicies)
}
res := governance.Resource{
Kind: governance.KindProposal, ID: p.ID.String(), Org: governance.DefaultOrgID,
Owner: governance.IdentityID(ownerOf(decisions)), State: p.State,
}
for _, a := range actions {
d := m.authz.Authorize(ctx, person, a, res, governance.AccessContext{})
if d.Err != nil {
return "", fmt.Errorf("check access: %w", d.Err)
}
if !d.Allowed {
return "", ErrNotApprover
}
}
return string(person.IdentityID), nil
}
// ownerOf is the person who answers for the target of the first action that
// has one.
func ownerOf(decisions []judgement.Decision) string {
for _, d := range decisions {
if owner := d.Owner(); owner != "" {
return owner
}
}
return ""
}
// apply carries out an approved proposal and publishes it once its actions have
// settled. Every step is idempotent, so a retry never repeats an effect.
func (m *Module) apply(ctx context.Context, p store.Proposal) error {
var err error
switch p.Kind {
case KindTrigger:
err = m.publishTrigger(ctx, p)
case KindWorkflowChange:
err = m.publishWorkflow(ctx, p)
case KindPolicyChange:
err = m.publishPolicy(ctx, p)
}
if err != nil {
return err
}
actions, err := m.store.Actions(ctx, p.ID)
if err != nil {
return err
}
if len(actions) > 0 {
runID, err := m.workflows.Start(workloadContext(ctx), runs.StartRequest{
OrgID: m.orgID, WorkflowID: runs.ShippedID(m.orgID, runs.ProposalWorkflow), Key: "proposal:" + p.ID.String(),
Input: jsontext.Value(`{"proposal_id":"` + p.ID.String() + `"}`),
})
if err != nil {
return fmt.Errorf("start the run for the actions: %w", err)
}
if err := m.store.SetRun(ctx, m.orgID, p.ID, runID); err != nil {
return err
}
}
_, err = m.store.Publish(ctx, m.orgID, p.ID)
return err
}
func (m *Module) publishWorkflow(ctx context.Context, p store.Proposal) error {
var c struct {
Name string `json:"name"`
Workflow string `json:"workflow"`
}
if err := json.Unmarshal(p.Change, &c); err != nil {
return fmt.Errorf("read the workflow change: %w", err)
}
if _, _, err := m.workflows.Install(ctx, m.orgID, c.Name, c.Workflow, p.AnsweredByID.String); err != nil {
return fmt.Errorf("install the workflow: %w", err)
}
return nil
}
func (m *Module) publishPolicy(ctx context.Context, p store.Proposal) error {
var c struct {
PolicyKind string `json:"policy_kind"`
Policy string `json:"policy"`
}
if err := json.Unmarshal(p.Change, &c); err != nil {
return fmt.Errorf("read the policy change: %w", err)
}
if _, err := m.policies.Append(ctx, c.PolicyKind, c.Policy, p.AnsweredByID.String); err != nil {
return fmt.Errorf("add the policy: %w", err)
}
return nil
}
// Work finishes approved proposals that were not applied, such as after a
// restart, until ctx ends.
func (m *Module) Work(ctx context.Context) {
ticker := time.NewTicker(workInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
m.finish(ctx)
}
}
}
func (m *Module) finish(ctx context.Context) {
open, err := m.store.Unfinished(ctx, m.orgID, 20)
if err != nil {
m.log.ErrorContext(ctx, "list approved proposals", "error", err)
return
}
for _, p := range open {
if err := m.apply(ctx, p); err != nil {
m.log.ErrorContext(ctx, "apply approved proposal", "proposal", p.ID, "error", err)
}
}
}
// ApprovedActions returns the actions of an approved proposal, each with the
// approval that covers exactly that action.
func (m *Module) ApprovedActions(ctx context.Context, proposalID uuid.UUID) ([]runs.ApprovedAction, error) {
p, actions, decisions, err := m.load(ctx, proposalID)
if err != nil {
return nil, err
}
return bind(p, actions, decisions)
}
// SettleAction records how one action of a proposal ended, and publishes the
// proposal when every action has.
func (m *Module) SettleAction(ctx context.Context, proposalID uuid.UUID, seq int, state, outcome string) error {
if err := m.store.SettleAction(ctx, proposalID, seq, state, outcome); err != nil {
return err
}
_, err := m.store.Publish(ctx, m.orgID, proposalID)
return err
}
// load reads a proposal, its actions and the decisions that judged them.
func (m *Module) load(ctx context.Context, id uuid.UUID) (store.Proposal, []store.Action, []judgement.Decision, error) {
p, err := m.store.ByID(ctx, m.orgID, id)
if err != nil {
return store.Proposal{}, nil, nil, err
}
actions, err := m.store.Actions(ctx, id)
if err != nil {
return store.Proposal{}, nil, nil, err
}
var decisions []judgement.Decision
if len(actions) > 0 {
decisions, err = m.judge.ForRun(ctx, id)
if err != nil {
return store.Proposal{}, nil, nil, fmt.Errorf("read the judgements: %w", err)
}
}
return p, actions, decisions, nil
}
func callerID(ctx context.Context) string { return governance.CallerID(ctx) }
// workloadContext acts as the workload principal, as queued work does, so a
// run start is decided by the same policy chain as any other background start.
func workloadContext(ctx context.Context) context.Context {
return governance.WithPrincipal(ctx, governance.WorkloadPrincipal(governance.DefaultOrgID))
}
// unavailable reports an error that a retry may clear, as opposed to a refusal.
func unavailable(err error) bool {
return errors.Is(err, governance.ErrChainUnavailable) || errors.Is(err, context.Canceled)
}
func unmarshalIDs(raw jsontext.Value, dst *[]uuid.UUID) error {
if len(raw) == 0 {
return nil
}
if err := json.Unmarshal(raw, dst); err != nil {
return fmt.Errorf("read the prompting events: %w", err)
}
return nil
}