feat(judgement,approvals): link decisions and approval requests by action_type_id (#2130)

This commit is contained in:
sam committed 2026-11-24 06:23:19 +11:00
1 parent 1c10378a40
commit c5591d95da
14 files changed
+177 -108

No files matched your search

+3
View File
@@ -3067,6 +3067,8 @@ components:
properties:
action:
$ref: "#/components/schemas/JudgementAction"
action_type_id:
type: string
at:
format: date-time
type: string
@@ -3106,6 +3108,7 @@ components:
- id
- run_id
- key
- action_type_id
- action
- level
- verdicts
@@ -1,32 +1,6 @@
-- +goose Up
CREATE SCHEMA judgement;
-- A decision is the judgement of one concrete action, with every verdict in
-- its body. key identifies the attempt to run the action, so a replayed step
-- reads the existing decision instead of judging the action again. connector, action, target_kind and environment
-- identify the action type the decision counts towards.
CREATE TABLE judgement.decisions (
id uuid PRIMARY KEY,
org_id text NOT NULL,
run_id uuid NOT NULL,
key text NOT NULL,
connector text NOT NULL,
-- installation_id and installation_scope name the installation the action
-- resolved to, so an audit can say which configuration acted and whose it was.
installation_id uuid NOT NULL,
installation_scope text NOT NULL CHECK (installation_scope IN ('instance', 'org', 'person')),
action text NOT NULL,
target_kind text NOT NULL,
environment text NOT NULL,
level text NOT NULL CHECK (level IN ('act_quietly', 'act_and_tell', 'propose_and_wait', 'escalate', 'never')),
body json NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
dry boolean NOT NULL DEFAULT false,
UNIQUE (org_id, key)
);
CREATE INDEX decisions_by_run ON judgement.decisions (org_id, run_id, created_at);
CREATE INDEX decisions_by_class ON judgement.decisions (org_id, connector, action, target_kind, environment, created_at);
CREATE TABLE judgement.action_types (
id uuid PRIMARY KEY,
org_id text NOT NULL,
@@ -43,6 +17,35 @@ CREATE TABLE judgement.action_types (
UNIQUE (org_id, connector, action, target_kind, environment)
);
-- A decision is the judgement of one concrete action, with every verdict in
-- its body. key identifies the attempt to run the action, so a replayed step
-- reads the existing decision instead of judging the action again.
-- action_type_id identifies the action type the decision counts towards;
-- connector, action, target_kind and environment are point-in-time snapshots
-- for the audit trail.
CREATE TABLE judgement.decisions (
id uuid PRIMARY KEY,
org_id text NOT NULL,
run_id uuid NOT NULL,
key text NOT NULL,
action_type_id uuid NOT NULL REFERENCES judgement.action_types (id),
connector text NOT NULL,
-- installation_id and installation_scope name the installation the action
-- resolved to, so an audit can say which configuration acted and whose it was.
installation_id uuid NOT NULL,
installation_scope text NOT NULL CHECK (installation_scope IN ('instance', 'org', 'person')),
action text NOT NULL,
target_kind text NOT NULL,
environment text NOT NULL,
level text NOT NULL CHECK (level IN ('act_quietly', 'act_and_tell', 'propose_and_wait', 'escalate', 'never')),
body json NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
dry boolean NOT NULL DEFAULT false,
UNIQUE (org_id, key)
);
CREATE INDEX decisions_by_run ON judgement.decisions (org_id, run_id, created_at);
CREATE INDEX decisions_by_action_type ON judgement.decisions (org_id, action_type_id, created_at);
CREATE TABLE judgement.action_type_resets (
id uuid PRIMARY KEY,
org_id text NOT NULL,
@@ -10,6 +10,9 @@ CREATE TABLE approvals.requests (
run_id uuid NOT NULL,
key text NOT NULL,
decision_id uuid NOT NULL,
-- action_type_id names the judgement.action_types row for both action and
-- autonomy requests, without a cross-module foreign key.
action_type_id uuid NOT NULL,
digest text NOT NULL,
level text NOT NULL CHECK (level IN ('act_quietly', 'act_and_tell', 'propose_and_wait', 'escalate', 'never')),
summary text NOT NULL,
+30 -18
View File
@@ -71,15 +71,16 @@ type Request struct {
Kind string
RunID uuid.UUID
// Key identifies the run wait that receives the response.
Key string
Decision judgement.Decision
DecisionID uuid.UUID
RequestedAt time.Time
Connector string
Action string
TargetKind string
TargetID string
Level string
Key string
Decision judgement.Decision
DecisionID uuid.UUID
ActionTypeID uuid.UUID
RequestedAt time.Time
Connector string
Action string
TargetKind string
TargetID string
Level string
// Irreversible is whether the action can't be undone. Approving it needs
// a fresh passkey assertion from the dashboard.
Irreversible bool
@@ -229,6 +230,9 @@ func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, d judgeme
if len(path) == 0 {
return Request{}, ErrNoPath
}
if d.ActionTypeID == uuid.Nil {
return Request{}, errors.New("approval request needs an action type id")
}
changeRequest := d.ChangeRequest && m.changes != nil
now := m.now().UTC()
var total time.Duration
@@ -237,7 +241,7 @@ func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, d judgeme
}
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(),
DecisionID: d.ID, ActionTypeID: d.ActionTypeID, Kind: KindAction, Digest: d.Action.Digest, Level: d.Level.String(),
Connector: d.Action.Connector, Action: d.Action.Name,
InstallationID: d.Action.Installation.ID, InstallationScope: d.Action.Installation.Scope,
TargetKind: d.Action.Target.Kind, TargetID: d.Action.Target.ID, Irreversible: irreversible(d.Action),
@@ -322,13 +326,21 @@ func (m *Module) learn(ctx context.Context, row store.Request, a Answer) error {
func (m *Module) askProposal(ctx context.Context, r *judgement.AutonomyProposal) error {
actionType := r.ActionType
row, err := m.store.Put(ctx, store.Request{
ID: uuid.New(), OrgID: m.orgID, Key: "autonomy:" + r.ID.String(),
DecisionID: r.ID, Kind: KindAutonomy, Level: r.From.String(),
Connector: actionType.Connector, Action: actionType.Action, TargetKind: actionType.TargetKind, TargetID: actionType.Environment,
InstallationScope: connectors.ScopeInstance,
Summary: proposalSummary(r), State: StatePending, Deadline: r.Deadline,
})
var (
row store.Request
err error
)
if r.ActionTypeID == uuid.Nil {
err = errors.New("autonomy approval request needs an action type id")
} else {
row, err = m.store.Put(ctx, store.Request{
ID: uuid.New(), OrgID: m.orgID, Key: "autonomy:" + r.ID.String(),
DecisionID: r.ID, ActionTypeID: r.ActionTypeID, Kind: KindAutonomy, Level: r.From.String(),
Connector: actionType.Connector, Action: actionType.Action, TargetKind: actionType.TargetKind, TargetID: actionType.Environment,
InstallationScope: connectors.ScopeInstance,
Summary: proposalSummary(r), State: StatePending, Deadline: r.Deadline,
})
}
if err == nil {
err = m.tell.Ask(ctx, deliveries.ApprovalRequest{
RequestID: row.ID, Key: row.Key + ":ask",
@@ -645,7 +657,7 @@ func inputLine(input jsontext.Value) string {
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,
ID: row.ID, Kind: row.Kind, RunID: row.RunID, Key: row.Key, Decision: d, DecisionID: row.DecisionID, ActionTypeID: row.ActionTypeID, RequestedAt: row.CreatedAt,
Connector: row.Connector, Action: row.Action, TargetKind: row.TargetKind, TargetID: row.TargetID,
Level: row.Level, Irreversible: row.Irreversible, Summary: row.Summary, State: row.State, Deadline: row.Deadline,
Step: row.Step, ChangeRequest: row.ChangeRequest,
+10 -7
View File
@@ -19,10 +19,13 @@ type Request struct {
RunID uuid.UUID `db:"run_id"`
Key string `db:"key"`
// DecisionID identifies the judgement decision or the autonomy proposal.
DecisionID uuid.UUID `db:"decision_id"`
Kind string `db:"kind"`
Digest string `db:"digest"`
DecisionID uuid.UUID `db:"decision_id"`
ActionTypeID uuid.UUID `db:"action_type_id"`
Kind string `db:"kind"`
Digest string `db:"digest"`
// Copy the action details so the request can be read without loading the decision.
// Connector holds the connector's immutable package identifier, never
// renamed and never given to a different package.
Connector string `db:"connector"`
// InstallationID and InstallationScope name the installation the action
// resolved to. An autonomy proposal has none and records the nil ID at the
@@ -62,7 +65,7 @@ type Store struct {
// New returns a store on db.
func New(db *sqlx.DB) *Store { return &Store{db: db} }
const requestColumns = `id, org_id, run_id, key, decision_id, kind, digest, connector, installation_id, installation_scope, action, target_kind,
const requestColumns = `id, org_id, run_id, key, decision_id, action_type_id, kind, digest, connector, installation_id, installation_scope, action, target_kind,
target_id, level, irreversible, summary, state, deadline, created_at, answered_at, answered_by, answered_by_id, answered_via,
step, step_deadline, change_request, counted, discarded_because`
@@ -71,12 +74,12 @@ const requestColumns = `id, org_id, run_id, key, decision_id, kind, digest, conn
func (s *Store) Put(ctx context.Context, r Request) (Request, error) {
var out Request
err := s.db.GetContext(ctx, &out, `
INSERT INTO approvals.requests (id, org_id, run_id, key, decision_id, kind, digest, connector, installation_id,
INSERT INTO approvals.requests (id, org_id, run_id, key, decision_id, action_type_id, kind, digest, connector, installation_id,
installation_scope, action, target_kind, target_id, level, irreversible, summary, state, deadline, step_deadline, change_request)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21)
ON CONFLICT (org_id, run_id, key) DO NOTHING
RETURNING `+requestColumns,
r.ID, r.OrgID, r.RunID, r.Key, r.DecisionID, r.Kind, r.Digest, r.Connector, r.InstallationID, r.InstallationScope, r.Action, r.TargetKind,
r.ID, r.OrgID, r.RunID, r.Key, r.DecisionID, r.ActionTypeID, r.Kind, r.Digest, r.Connector, r.InstallationID, r.InstallationScope, r.Action, r.TargetKind,
r.TargetID, r.Level, r.Irreversible, r.Summary, r.State, r.Deadline, r.StepDeadline, r.ChangeRequest)
if errors.Is(err, sql.ErrNoRows) {
return s.Get(ctx, r.OrgID, r.RunID, r.Key)
+11 -7
View File
@@ -62,19 +62,23 @@ func NewActionTypes(db *sqlx.DB, log *slog.Logger, orgID string) *ActionTypes {
return &ActionTypes{orgID: orgID, store: store.New(db), log: log, now: time.Now}
}
// Level returns the level of action type c, creating it at its default level
// on its first action. readOnly is the action's own declaration and is stored
// with the action type, so a reset knows its default level.
func (c *ActionTypes) Level(ctx context.Context, actionType ActionType, readOnly bool) (Level, error) {
// Level returns the level and id of actionType, creating it at its default
// level on its first action. readOnly is the action's own declaration and is
// stored with the action type, so a reset knows its default level.
func (c *ActionTypes) Level(ctx context.Context, actionType ActionType, readOnly bool) (Level, uuid.UUID, error) {
row, err := c.store.EnsureActionType(ctx, store.ActionType{
ID: uuid.New(), OrgID: c.orgID, Connector: actionType.Connector, Action: actionType.Action,
TargetKind: actionType.TargetKind, Environment: actionType.Environment,
ReadOnly: readOnly, Level: DefaultLevel(readOnly).String(),
})
if err != nil {
return 0, err
return 0, uuid.Nil, err
}
return parseLevel(row.Level)
level, err := parseLevel(row.Level)
if err != nil {
return 0, uuid.Nil, err
}
return level, row.ID, nil
}
func parseLevel(s string) (Level, error) {
@@ -206,7 +210,7 @@ func (c *ActionTypes) Detail(ctx context.Context, id uuid.UUID, outcomes Outcome
if err != nil {
return ActionTypeDetail{}, err
}
decisions, err := c.store.ActionTypeDecisions(ctx, row, historyLimit)
decisions, err := c.store.ActionTypeDecisions(ctx, c.orgID, id, historyLimit)
if err != nil {
return ActionTypeDetail{}, err
}
+7 -6
View File
@@ -80,11 +80,12 @@ func freezeCeiling(frozen, readOnly bool) Level {
// AutonomyProposal is Archie's proposal to loosen an action type by one level, with the
// approvals that earned it.
type AutonomyProposal struct {
ID uuid.UUID
ActionType ActionType
From, To Level
Evidence []ProposalEvidence
Deadline time.Time
ID uuid.UUID
ActionTypeID uuid.UUID
ActionType ActionType
From, To Level
Evidence []ProposalEvidence
Deadline time.Time
}
// ProposalEvidence is one approval counted toward an autonomy proposal.
@@ -297,7 +298,7 @@ func (c *ActionTypes) propose(ctx context.Context, t *store.ActionTypeTx, from,
return nil, fmt.Errorf("encode evidence: %w", err)
}
r := &AutonomyProposal{
ID: uuid.New(), From: from, To: to, Evidence: shown, Deadline: deadline.UTC(),
ID: uuid.New(), ActionTypeID: t.ActionType.ID, From: from, To: to, Evidence: shown, Deadline: deadline.UTC(),
ActionType: ActionType{
Connector: t.ActionType.Connector, Action: t.ActionType.Action,
TargetKind: t.ActionType.TargetKind, Environment: t.ActionType.Environment,
+6 -4
View File
@@ -5,6 +5,8 @@ import (
"errors"
"fmt"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/modules/connectors"
)
@@ -34,9 +36,9 @@ func (Reversibility) Judge(_ context.Context, a Action) (Verdict, error) {
return Verdict{}, errors.New("the connector declares no reversibility for this action")
}
// ActionTypeLevels reports the level of an action type.
// ActionTypeLevels reports the level and id of an action type.
type ActionTypeLevels interface {
Level(ctx context.Context, c ActionType, readOnly bool) (Level, error)
Level(ctx context.Context, c ActionType, readOnly bool) (Level, uuid.UUID, error)
}
// Precedent sets a ceiling from the action type's current level. An action type
@@ -54,11 +56,11 @@ func (Precedent) Advisory() bool { return false }
// Judge returns the action type's level.
func (p Precedent) Judge(ctx context.Context, a Action) (Verdict, error) {
level, err := p.ActionTypes.Level(ctx, a.ActionType(), a.Effect.ReadOnly)
level, id, err := p.ActionTypes.Level(ctx, a.ActionType(), a.Effect.ReadOnly)
if err != nil {
return Verdict{}, fmt.Errorf("read action type level: %w", err)
}
return Verdict{Ceiling: level, Findings: []Finding{{Text: "this action type is at " + level.String()}}}, nil
return Verdict{Ceiling: level, actionTypeID: id, Findings: []Finding{{Text: "this action type is at " + level.String()}}}, nil
}
// Freezes says whether the organisation has frozen its actions.
+2 -2
View File
@@ -88,8 +88,8 @@ func TestGuardsReturnTheDemoVerdicts(t *testing.T) {
{"reversibility: reading", Reversibility{}, read, ActQuietly},
{"reversibility: undone automatically", Reversibility{}, func() Action { a := runner; a.Effect.Reversibility = connectors.UndoneAutomatically; return a }(), ActQuietly},
{"precedent: earned action type", Precedent{ActionTypes: actionTypeLevel{ActAndTell}}, runner, ActAndTell},
{"precedent: new action type", Precedent{ActionTypes: actionTypeLevel{ProposeAndWait}}, container, ProposeAndWait},
{"precedent: earned action type", Precedent{ActionTypes: actionTypeLevel{level: ActAndTell}}, runner, ActAndTell},
{"precedent: new action type", Precedent{ActionTypes: actionTypeLevel{level: ProposeAndWait}}, container, ProposeAndWait},
{"provenance: verified alert", Provenance{Events: fakeEvents{verified: true, untrusted: []string{prose}}}, runner, ActQuietly},
{"provenance: no verified source", Provenance{Events: fakeEvents{}}, runner, ProposeAndWait},
@@ -15,8 +15,10 @@ var ErrNoActionType = errors.New("no such action type")
// ActionType is one action type and the level it stands at.
type ActionType struct {
ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"`
ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"`
// Connector holds the connector's immutable package identifier, never
// renamed and never given to a different package.
Connector string `db:"connector"`
Action string `db:"action"`
TargetKind string `db:"target_kind"`
@@ -76,8 +78,7 @@ func (s *Store) ActionTypes(ctx context.Context, orgID string) ([]ActionTypeSumm
count(d.id) AS decisions, max(d.created_at) AS last_at,
(SELECT count(*) FROM judgement.action_type_approvals a WHERE a.action_type_id = c.id AND a.counted) AS streak
FROM judgement.action_types c
LEFT JOIN judgement.decisions d ON d.org_id = c.org_id AND d.connector = c.connector
AND d.action = c.action AND d.target_kind = c.target_kind AND d.environment = c.environment AND NOT d.dry
LEFT JOIN judgement.decisions d ON d.org_id = c.org_id AND d.action_type_id = c.id AND NOT d.dry
WHERE c.org_id = $1
GROUP BY c.id
ORDER BY coalesce(max(d.created_at), c.created_at) DESC, c.id`, orgID)
@@ -101,14 +102,14 @@ func (s *Store) ActionTypeByID(ctx context.Context, orgID string, id uuid.UUID)
}
// ActionTypeDecisions returns an action type's newest decisions, newest first.
func (s *Store) ActionTypeDecisions(ctx context.Context, c ActionType, limit int) ([]Decision, error) {
func (s *Store) ActionTypeDecisions(ctx context.Context, orgID string, actionTypeID uuid.UUID, limit int) ([]Decision, error) {
var out []Decision
err := s.db.SelectContext(ctx, &out, `
SELECT id, org_id, run_id, key, connector, action, target_kind, environment, level, body, created_at
SELECT `+decisionColumns+`, created_at
FROM judgement.decisions
WHERE org_id = $1 AND connector = $2 AND action = $3 AND target_kind = $4 AND environment = $5 AND NOT dry
ORDER BY created_at DESC, id LIMIT $6`,
c.OrgID, c.Connector, c.Action, c.TargetKind, c.Environment, limit)
WHERE org_id = $1 AND action_type_id = $2 AND NOT dry
ORDER BY created_at DESC, id LIMIT $3`,
orgID, actionTypeID, limit)
if err != nil {
return nil, fmt.Errorf("list action type decisions: %w", err)
}
+1 -2
View File
@@ -41,8 +41,7 @@ func (s *Store) ActionTypeOfDecision(ctx context.Context, orgID string, decision
SELECT c.id, c.org_id, c.connector, c.action, c.target_kind, c.environment, c.read_only, c.level,
c.created_at, c.reset_at, c.tightened_at, c.tightened_because
FROM judgement.decisions d
JOIN judgement.action_types c ON c.org_id = d.org_id AND c.connector = d.connector AND c.action = d.action
AND c.target_kind = d.target_kind AND c.environment = d.environment
JOIN judgement.action_types c ON c.id = d.action_type_id
WHERE d.org_id = $1 AND d.id = $2`, orgID, decisionID)
if errors.Is(err, sql.ErrNoRows) {
return ActionType{}, ErrNoActionType
+20 -15
View File
@@ -15,14 +15,17 @@ import (
// Decision is one recorded decision. Body is the whole decision as JSON.
type Decision struct {
ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"`
RunID uuid.UUID `db:"run_id"`
Key string `db:"key"`
Connector string `db:"connector"`
Action string `db:"action"`
TargetKind string `db:"target_kind"`
Environment string `db:"environment"`
ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"`
RunID uuid.UUID `db:"run_id"`
Key string `db:"key"`
ActionTypeID uuid.UUID `db:"action_type_id"`
// Connector holds the connector's immutable package identifier, never
// renamed and never given to a different package.
Connector string `db:"connector"`
Action string `db:"action"`
TargetKind string `db:"target_kind"`
Environment string `db:"environment"`
// InstallationID and InstallationScope name the installation the action
// resolved to.
InstallationID uuid.UUID `db:"installation_id"`
@@ -34,6 +37,8 @@ type Decision struct {
CreatedAt time.Time `db:"created_at"`
}
const decisionColumns = `id, org_id, run_id, key, action_type_id, connector, action, target_kind, environment, level, body`
// Store is the judgement module's Postgres store.
type Store struct {
db *sqlx.DB
@@ -48,14 +53,14 @@ func (s *Store) Record(ctx context.Context, d Decision) (Decision, error) {
var kept Decision
err := s.db.GetContext(ctx, &kept, `
INSERT INTO judgement.decisions
(id, org_id, run_id, key, connector, installation_id, installation_scope, action, target_kind, environment, level, dry, body)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
(id, org_id, run_id, key, action_type_id, connector, installation_id, installation_scope, action, target_kind, environment, level, dry, body)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
ON CONFLICT (org_id, key) DO NOTHING
RETURNING id, org_id, run_id, key, connector, action, target_kind, environment, level, body`,
d.ID, d.OrgID, d.RunID, d.Key, d.Connector, d.InstallationID, d.InstallationScope, d.Action, d.TargetKind, d.Environment, d.Level, d.Dry, d.Body)
RETURNING `+decisionColumns,
d.ID, d.OrgID, d.RunID, d.Key, d.ActionTypeID, d.Connector, d.InstallationID, d.InstallationScope, d.Action, d.TargetKind, d.Environment, d.Level, d.Dry, d.Body)
if errors.Is(err, sql.ErrNoRows) {
err = s.db.GetContext(ctx, &kept, `
SELECT id, org_id, run_id, key, connector, action, target_kind, environment, level, body
SELECT `+decisionColumns+`
FROM judgement.decisions WHERE org_id = $1 AND key = $2`, d.OrgID, d.Key)
}
if err != nil {
@@ -84,7 +89,7 @@ func (s *Store) AppendCall(ctx context.Context, orgID string, id uuid.UUID, call
func (s *Store) RecentBodies(ctx context.Context, orgID string, limit int) ([]Decision, error) {
var out []Decision
if err := s.db.SelectContext(ctx, &out, `
SELECT id, org_id, run_id, key, connector, action, target_kind, environment, level, body, created_at
SELECT `+decisionColumns+`, created_at
FROM judgement.decisions WHERE org_id = $1
ORDER BY created_at DESC LIMIT $2`, orgID, limit); err != nil {
return nil, fmt.Errorf("list recent decisions: %w", err)
@@ -96,7 +101,7 @@ func (s *Store) RecentBodies(ctx context.Context, orgID string, limit int) ([]De
func (s *Store) ForRun(ctx context.Context, orgID string, runID uuid.UUID) ([]Decision, error) {
var out []Decision
if err := s.db.SelectContext(ctx, &out, `
SELECT id, org_id, run_id, key, connector, action, target_kind, environment, level, body
SELECT `+decisionColumns+`
FROM judgement.decisions WHERE org_id = $1 AND run_id = $2 ORDER BY created_at, id`, orgID, runID); err != nil {
return nil, fmt.Errorf("list decisions: %w", err)
}
+33 -9
View File
@@ -125,6 +125,9 @@ type Verdict struct {
// Owner is the id of the person the impact guard found answering for the
// target, empty when it found none.
Owner string `json:"owner,omitzero"`
// actionTypeID carries the row id ensured by the precedent guard so record
// does not need to ensure the action type a second time.
actionTypeID uuid.UUID
}
// Guard judges one concrete action.
@@ -145,12 +148,13 @@ type HardRule interface {
// Decision is the judgement of one action.
type Decision struct {
ID uuid.UUID `json:"id"`
RunID uuid.UUID `json:"run_id"`
Key string `json:"key"`
Action Action `json:"action"`
Level Level `json:"level"`
Verdicts []Verdict `json:"verdicts"`
ID uuid.UUID `json:"id"`
RunID uuid.UUID `json:"run_id"`
Key string `json:"key"`
ActionTypeID uuid.UUID `json:"action_type_id"`
Action Action `json:"action"`
Level Level `json:"level"`
Verdicts []Verdict `json:"verdicts"`
// RefusedBy names the hard rule that refused the action, if one did.
RefusedBy string `json:"refused_by,omitzero"`
// Workflow is the workflow the decision was made for. Execution checks it
@@ -222,6 +226,7 @@ type FailureRecorder interface {
}
type recorder interface {
EnsureActionType(ctx context.Context, c store.ActionType) (store.ActionType, error)
Record(ctx context.Context, d store.Decision) (store.Decision, error)
ForRun(ctx context.Context, orgID string, runID uuid.UUID) ([]store.Decision, error)
AppendCall(ctx context.Context, orgID string, id uuid.UUID, call string) error
@@ -332,7 +337,11 @@ func (m *Module) decide(ctx context.Context, a Action) Decision {
}
wg.Wait()
ceilings := []Level{}
var actionTypeID uuid.UUID
for _, v := range verdicts {
if v.actionTypeID != uuid.Nil {
actionTypeID = v.actionTypeID
}
if !v.Advisory {
ceilings = append(ceilings, v.Ceiling)
}
@@ -341,7 +350,7 @@ func (m *Module) decide(ctx context.Context, a Action) Decision {
if len(ceilings) > 0 {
level = lowest(ceilings...)
}
d := Decision{Action: a, Level: level, Verdicts: verdicts}
d := Decision{ActionTypeID: actionTypeID, Action: a, Level: level, Verdicts: verdicts}
// A change request is a way to approve, so only a held action has one.
if m.changeRules != nil && level > ActAndTell && level < Never {
d.ChangeRequestRule, d.ChangeRequest = m.changeRules.Requires(ctx, a, level, verdicts)
@@ -495,19 +504,33 @@ func (m *Module) ForRun(ctx context.Context, runID uuid.UUID) ([]Decision, error
if err := json.Unmarshal(r.Body, &d); err != nil {
return nil, fmt.Errorf("decision %s: %w", r.ID, err)
}
d.ActionTypeID = r.ActionTypeID
out = append(out, d)
}
return out, nil
}
func (m *Module) record(ctx context.Context, d Decision) (Decision, error) {
c := d.Action.ActionType()
// Ensure the action type row exists even when the precedent guard did not
// run (for instance a hard-rule refusal or a test module without precedent).
if d.ActionTypeID == uuid.Nil {
actionType, err := m.store.EnsureActionType(ctx, store.ActionType{
ID: uuid.New(), OrgID: m.orgID, Connector: c.Connector, Action: c.Action,
TargetKind: c.TargetKind, Environment: c.Environment,
ReadOnly: d.Action.Effect.ReadOnly, Level: DefaultLevel(d.Action.Effect.ReadOnly).String(),
})
if err != nil {
return Decision{}, err
}
d.ActionTypeID = actionType.ID
}
body, err := json.Marshal(d)
if err != nil {
return Decision{}, fmt.Errorf("encode decision: %w", err)
}
c := d.Action.ActionType()
row, err := m.store.Record(ctx, store.Decision{
ID: d.ID, OrgID: m.orgID, RunID: d.RunID, Key: d.Key,
ID: d.ID, OrgID: m.orgID, RunID: d.RunID, Key: d.Key, ActionTypeID: d.ActionTypeID,
Connector: c.Connector, Action: c.Action, TargetKind: c.TargetKind, Environment: c.Environment,
InstallationID: d.Action.Installation.ID, InstallationScope: d.Action.Installation.Scope,
Level: d.Level.String(), Dry: d.Dry, Body: body,
@@ -522,5 +545,6 @@ func (m *Module) record(ctx context.Context, d Decision) (Decision, error) {
if err := json.Unmarshal(row.Body, &kept); err != nil {
return Decision{}, fmt.Errorf("decision %s: %w", row.ID, err)
}
kept.ActionTypeID = row.ActionTypeID
return kept, nil
}
+12 -3
View File
@@ -284,9 +284,14 @@ func TestExecuteApprovedRunsOnlyWhatThePersonSaw(t *testing.T) {
}
}
type actionTypeLevel struct{ level Level }
type actionTypeLevel struct {
level Level
id uuid.UUID
}
func (c actionTypeLevel) Level(context.Context, ActionType, bool) (Level, error) { return c.level, nil }
func (c actionTypeLevel) Level(context.Context, ActionType, bool) (Level, uuid.UUID, error) {
return c.level, c.id, nil
}
// TestPrecedentCeilingIsTheClassLevel guards the earned-autonomy seam: the
// precedent guard's ceiling is the level its action type stands at, not a
@@ -303,15 +308,19 @@ func TestPrecedentCeilingIsTheClassLevel(t *testing.T) {
{name: "a read-only action type lowered to escalate", level: Escalate, read: true},
{name: "an action type that never runs", level: Never},
}
wantID := uuid.New()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
v, err := Precedent{ActionTypes: actionTypeLevel{tt.level}}.Judge(t.Context(), Action{Effect: connectors.Effect{ReadOnly: tt.read}})
v, err := Precedent{ActionTypes: actionTypeLevel{tt.level, wantID}}.Judge(t.Context(), Action{Effect: connectors.Effect{ReadOnly: tt.read}})
if err != nil {
t.Fatal(err)
}
if v.Ceiling != tt.level {
t.Fatalf("ceiling = %s, want the action type level %s", v.Ceiling, tt.level)
}
if v.actionTypeID != wantID {
t.Fatalf("actionTypeID = %s, want %s", v.actionTypeID, wantID)
}
})
}
}