Files
archie/modules/judgement/classes.go
T
sam 1026d5e3b6 feat(httpapi): the API is described by an OpenAPI document generated with Huma (#2028)
Every /api operation is registered with Huma behind one admin-token
middleware, served at /api/openapi.json with a docs page at /api/docs,
and committed as api/openapi.yaml, which task check keeps current.
2026-11-16 20:05:05 +11:00

393 lines
12 KiB
Go

package judgement
import (
"context"
json "encoding/json/v2"
"errors"
"fmt"
"log/slog"
"net/http"
"time"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
"github.com/samcharles93/archie-core/modules/judgement/internal/store"
)
// historyLimit bounds the decisions one class's history returns.
const historyLimit = 100
// ErrNoClass means no action class has that id.
var ErrNoClass = store.ErrNoClass
// DefaultLevel is the level a class starts at, and returns to on a reset:
// reading starts at act quietly, everything else at propose and wait.
func DefaultLevel(readOnly bool) Level {
if readOnly {
return ActQuietly
}
return ProposeAndWait
}
// Outcome is what became of a decision's request for approval.
type Outcome struct {
State string
By string
At time.Time
}
// Outcomes says what became of decisions that were held for approval. It is
// the approvals module's to answer, so a class's history can show it.
type Outcomes interface {
Outcomes(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]Outcome, error)
}
// Classes owns one organisation's action classes: the level each stands at and
// the history behind it.
type Classes struct {
orgID string
store *store.Store
log *slog.Logger
now func() time.Time
}
// NewClasses returns the action classes of orgID.
func NewClasses(db *sqlx.DB, log *slog.Logger, orgID string) *Classes {
return &Classes{orgID: orgID, store: store.New(db), log: log, now: time.Now}
}
// Level returns the level c stands at, making the class at its default if this
// is the first action of it. readOnly is the action's own declaration and is
// kept with the class, so a reset knows what its default is.
func (c *Classes) Level(ctx context.Context, class Class, readOnly bool) (Level, error) {
row, err := c.store.EnsureClass(ctx, store.Class{
ID: uuid.New(), OrgID: c.orgID, Connector: class.Connector, Action: class.Action,
TargetKind: class.TargetKind, Environment: class.Environment,
ReadOnly: readOnly, Level: DefaultLevel(readOnly).String(),
})
if err != nil {
return 0, err
}
return parseLevel(row.Level)
}
func parseLevel(s string) (Level, error) {
var l Level
if err := l.UnmarshalText([]byte(s)); err != nil {
return 0, err
}
return l, nil
}
// ClassView is an action class as the API lists it.
type ClassView struct {
ID uuid.UUID `json:"id"`
Connector string `json:"connector"`
Action string `json:"action"`
TargetKind string `json:"target_kind"`
Environment string `json:"environment"`
Level Level `json:"level"`
Default Level `json:"default"`
Decisions int `json:"decisions"`
LastDecidedAt *time.Time `json:"last_decided_at,omitzero"`
ResetAt *time.Time `json:"reset_at,omitzero"`
// Count is the approvals in a row since the class was last tightened or
// raised.
Count int `json:"count"`
// TightenedAt and TightenedBecause say when and why the class last lost
// autonomy.
TightenedAt *time.Time `json:"tightened_at,omitzero"`
TightenedBecause string `json:"tightened_because,omitzero"`
}
// HistoryEntry is one decision in a class's history, with what became of its
// request for approval.
type HistoryEntry struct {
DecisionID uuid.UUID `json:"decision_id"`
RunID uuid.UUID `json:"run_id"`
Target string `json:"target"`
Level Level `json:"level"`
Refused string `json:"refused_by,omitzero"`
// Approval is the state of the request for approval: pending, approved,
// denied or expired. It is empty when none was asked.
Approval string `json:"approval,omitzero"`
AnsweredBy string `json:"answered_by,omitzero"`
At time.Time `json:"at"`
}
// ResetView is one return of a class to its default.
type ResetView struct {
From Level `json:"from"`
To Level `json:"to"`
By string `json:"by"`
At time.Time `json:"at"`
}
// RaiseView is one proposal to loosen a class by one level.
type RaiseView struct {
ID uuid.UUID `json:"id"`
From Level `json:"from"`
To Level `json:"to"`
State string `json:"state"`
Deadline time.Time `json:"deadline"`
ProposedAt time.Time `json:"proposed_at"`
AnsweredBy string `json:"answered_by,omitzero"`
AnsweredAt *time.Time `json:"answered_at,omitzero"`
// Evidence is the approvals that earned the proposal.
Evidence []RaiseEvidence `json:"evidence"`
}
// ClassDetail is a class with its history, newest first.
type ClassDetail struct {
ClassView
History []HistoryEntry `json:"history"`
Resets []ResetView `json:"resets"`
// Raises are the proposals to loosen the class, newest first. One whose
// state is pending waits for an answer.
Raises []RaiseView `json:"raises"`
}
// List returns every class, most recently decided first.
func (c *Classes) List(ctx context.Context) ([]ClassView, error) {
rows, err := c.store.Classes(ctx, c.orgID)
if err != nil {
return nil, err
}
out := make([]ClassView, 0, len(rows))
for _, r := range rows {
v, err := viewOf(r.Class)
if err != nil {
return nil, err
}
v.Decisions, v.Count = r.Decisions, r.Streak
if r.LastAt.Valid {
v.LastDecidedAt = &r.LastAt.Time
}
out = append(out, v)
}
return out, nil
}
func viewOf(r store.Class) (ClassView, error) {
level, err := parseLevel(r.Level)
if err != nil {
return ClassView{}, fmt.Errorf("class %s: %w", r.ID, err)
}
v := ClassView{
ID: r.ID, Connector: r.Connector, Action: r.Action, TargetKind: r.TargetKind,
Environment: r.Environment, Level: level, Default: DefaultLevel(r.ReadOnly),
}
if r.ResetAt.Valid {
v.ResetAt = &r.ResetAt.Time
}
if r.TightenedAt.Valid {
v.TightenedAt, v.TightenedBecause = &r.TightenedAt.Time, r.TightenedBecause.String
}
return v, nil
}
// Detail returns one class with its newest decisions and resets. The approval
// outcomes come from outcomes.
func (c *Classes) Detail(ctx context.Context, id uuid.UUID, outcomes Outcomes) (ClassDetail, error) {
row, err := c.store.ClassByID(ctx, c.orgID, id)
if err != nil {
return ClassDetail{}, err
}
view, err := viewOf(row)
if err != nil {
return ClassDetail{}, err
}
decisions, err := c.store.ClassDecisions(ctx, row, historyLimit)
if err != nil {
return ClassDetail{}, err
}
resets, err := c.store.ClassResets(ctx, id)
if err != nil {
return ClassDetail{}, err
}
if view.Count, err = c.store.ClassCount(ctx, id); err != nil {
return ClassDetail{}, err
}
raises, err := c.store.ClassRaises(ctx, id)
if err != nil {
return ClassDetail{}, err
}
ids := make([]uuid.UUID, len(decisions))
for i, d := range decisions {
ids[i] = d.ID
}
got, err := outcomes.Outcomes(ctx, ids)
if err != nil {
return ClassDetail{}, err
}
detail := ClassDetail{ClassView: view, Raises: make([]RaiseView, 0, len(raises))}
if detail.History, err = historyOf(decisions, got); err != nil {
return ClassDetail{}, err
}
if detail.Resets, err = resetViews(resets); err != nil {
return ClassDetail{}, err
}
for _, r := range raises {
v, err := c.raiseView(r)
if err != nil {
return ClassDetail{}, err
}
detail.Raises = append(detail.Raises, v)
}
return detail, nil
}
func historyOf(decisions []store.Decision, got map[uuid.UUID]Outcome) ([]HistoryEntry, error) {
out := make([]HistoryEntry, 0, len(decisions))
for _, d := range decisions {
var body Decision
if err := json.Unmarshal(d.Body, &body); err != nil {
return nil, fmt.Errorf("decision %s: %w", d.ID, err)
}
level, err := parseLevel(d.Level)
if err != nil {
return nil, fmt.Errorf("decision %s: %w", d.ID, err)
}
o := got[d.ID]
out = append(out, HistoryEntry{
DecisionID: d.ID, RunID: d.RunID, Target: body.Action.Target.ID, Level: level,
Refused: body.RefusedBy, Approval: o.State, AnsweredBy: o.By, At: d.CreatedAt,
})
}
return out, nil
}
func resetViews(resets []store.Reset) ([]ResetView, error) {
out := make([]ResetView, 0, len(resets))
for _, r := range resets {
from, err := parseLevel(r.FromLevel)
if err != nil {
return nil, err
}
to, err := parseLevel(r.ToLevel)
if err != nil {
return nil, err
}
out = append(out, ResetView{From: from, To: to, By: r.By, At: r.At})
}
return out, nil
}
func (c *Classes) raiseView(r store.Raise) (RaiseView, error) {
from, err := parseLevel(r.FromLevel)
if err != nil {
return RaiseView{}, err
}
to, err := parseLevel(r.ToLevel)
if err != nil {
return RaiseView{}, err
}
v := RaiseView{
ID: r.ID, From: from, To: to, State: r.State, Deadline: r.Deadline, ProposedAt: r.ProposedAt,
AnsweredBy: r.AnsweredBy.String, Evidence: []RaiseEvidence{},
}
if v.State == "pending" && !c.now().Before(r.Deadline) {
v.State = "expired"
}
if r.AnsweredAt.Valid {
v.AnsweredAt = &r.AnsweredAt.Time
}
if err := json.Unmarshal(r.Evidence, &v.Evidence); err != nil {
return RaiseView{}, fmt.Errorf("raise %s: %w", r.ID, err)
}
return v, nil
}
// Reset returns a class to its default level. Its decisions and earlier resets
// stay.
func (c *Classes) Reset(ctx context.Context, id uuid.UUID, by string) (ClassView, error) {
row, err := c.store.ClassByID(ctx, c.orgID, id)
if err != nil {
return ClassView{}, err
}
row, err = c.store.ResetClass(ctx, c.orgID, id, DefaultLevel(row.ReadOnly).String(), by, c.now().UTC())
if err != nil {
return ClassView{}, err
}
return viewOf(row)
}
// bootstrapAdmin names the identity the bootstrap admin token stands for.
const bootstrapAdmin = "admin"
// Register adds the action classes API.
func (c *Classes) Register(api huma.API, outcomes Outcomes) {
tags := []string{"Controls"}
huma.Register(api, huma.Operation{
OperationID: "list-classes", Method: http.MethodGet, Path: "/api/classes",
Summary: "List action classes with their earned levels", Tags: tags,
}, c.list)
huma.Register(api, huma.Operation{
OperationID: "get-class", Method: http.MethodGet, Path: "/api/classes/{id}",
Summary: "Get an action class with its history and outcomes", Tags: tags,
}, c.detail(outcomes))
huma.Register(api, huma.Operation{
OperationID: "reset-class", Method: http.MethodPost, Path: "/api/classes/{id}/reset",
Summary: "Reset an action class to its default level", Tags: tags,
}, c.reset)
}
func (c *Classes) list(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]ClassView], error) {
out, err := c.List(ctx)
if err != nil {
c.log.ErrorContext(ctx, "list classes", "error", err)
return nil, huma.Error500InternalServerError("couldn't list action classes")
}
return httpapi.OK(out), nil
}
func (c *Classes) detail(outcomes Outcomes) func(context.Context, *classInput) (*httpapi.Reply[ClassDetail], error) {
return func(ctx context.Context, in *classInput) (*httpapi.Reply[ClassDetail], error) {
id, err := classID(in.ID)
if err != nil {
return nil, err
}
out, err := c.Detail(ctx, id, outcomes)
if err != nil {
return nil, c.notFound(ctx, err)
}
return httpapi.OK(out), nil
}
}
type classInput struct {
ID string `path:"id" format:"uuid"`
}
func (c *Classes) reset(ctx context.Context, in *classInput) (*httpapi.Reply[ClassView], error) {
id, err := classID(in.ID)
if err != nil {
return nil, err
}
out, err := c.Reset(ctx, id, bootstrapAdmin)
if err != nil {
return nil, c.notFound(ctx, err)
}
return httpapi.OK(out), nil
}
func classID(raw string) (uuid.UUID, error) {
id, err := uuid.Parse(raw)
if err != nil {
return uuid.Nil, huma.Error400BadRequest("id is a class id")
}
return id, nil
}
// found writes the error response for err and reports whether there was none.
func (c *Classes) notFound(ctx context.Context, err error) error {
if errors.Is(err, ErrNoClass) {
return huma.Error404NotFound("no such action class")
}
c.log.ErrorContext(ctx, "action class", "error", err)
return huma.Error500InternalServerError("couldn't read the action class")
}