feat(judgement): hard rules and change-request rules as versioned Cedar policy sets (#1989)
This commit is contained in:
17 files changed
+756
-20
No files matched your search
@@ -87,12 +87,13 @@ func Run(ctx context.Context, configPath string) error {
|
||||
engine := runs.New(db, log.With("module", "runs"), runs.Options{Owner: owner()})
|
||||
// A workflow takes its context from the run handle, as a handler takes it
|
||||
// from the request.
|
||||
judge, classes := newJudgement(db, log, conns, settings)
|
||||
judge, classes, policies := newJudgement(db, log, conns, settings)
|
||||
// An approval request is carried by deliveries, and its answer wakes the run
|
||||
// that is waiting on it.
|
||||
allow := approvals.NewModule(db, log.With("module", "approvals"), orgID, tell, engine, classes, settings, settings)
|
||||
allow.Routes(mux, guard)
|
||||
classes.Routes(mux, guard, allow)
|
||||
policies.Routes(mux, guard)
|
||||
remembered := memory.NewModule(db, orgID)
|
||||
engine.Register("investigate", 1, runs.Investigate(settings, conns, judge, allow, tell, remembered)) //nolint:contextcheck // see above
|
||||
|
||||
@@ -123,13 +124,15 @@ func work(ctx context.Context, loops ...func(context.Context)) func() {
|
||||
}
|
||||
|
||||
// newJudgement returns the judgement module and the action classes its
|
||||
// precedent guard reads. A failed action tightens its class.
|
||||
func newJudgement(db *sqlx.DB, log *slog.Logger, conns *connectors.Module, freezes judgement.Freezes) (*judgement.Module, *judgement.Classes) {
|
||||
// precedent guard reads, and the policy sets. A failed action tightens its class.
|
||||
func newJudgement(db *sqlx.DB, log *slog.Logger, conns *connectors.Module, freezes judgement.Freezes) (*judgement.Module, *judgement.Classes, *judgement.Policies) {
|
||||
classes := judgement.NewClasses(db, log.With("module", "judgement"), orgID)
|
||||
judge := judgement.NewModule(db, log.With("module", "judgement"), orgID, conns, nil,
|
||||
policies := judgement.NewPolicies(db, log.With("module", "judgement"), orgID)
|
||||
judge := judgement.NewModule(db, log.With("module", "judgement"), orgID, conns, []judgement.HardRule{policies},
|
||||
[]judgement.Guard{judgement.Reversibility{}, judgement.Precedent{Classes: classes}, judgement.Freeze{Freezes: freezes}}, classes)
|
||||
judge.UseExtensions(conns)
|
||||
return judge, classes
|
||||
judge.UseChangeRules(policies)
|
||||
return judge, classes, policies
|
||||
}
|
||||
|
||||
// orgID is the one organisation until hosting is multi-tenant.
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
-- +goose Up
|
||||
-- Hard rules and change-request rules are Cedar policy sets, one per kind per
|
||||
-- organisation. Every version is kept; the highest is the one in force.
|
||||
CREATE TABLE judgement.policy_sets (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
kind text NOT NULL CHECK (kind IN ('hard_rules', 'change_request')),
|
||||
version integer NOT NULL,
|
||||
body text NOT NULL,
|
||||
created_by text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (org_id, kind, version)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE judgement.policy_sets;
|
||||
@@ -22,8 +22,9 @@ type identified interface {
|
||||
|
||||
// RunContext is the run an action belongs to, passed to guards that want it.
|
||||
type RunContext struct {
|
||||
RunID uuid.UUID
|
||||
Key string
|
||||
RunID uuid.UUID
|
||||
Key string
|
||||
Workflow string
|
||||
}
|
||||
|
||||
type runKey struct{}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ErrNoPolicySet means no version of that policy set exists.
|
||||
var ErrNoPolicySet = errors.New("no such policy set")
|
||||
|
||||
// PolicySet is one version of an organisation's policy set of one kind.
|
||||
type PolicySet struct {
|
||||
ID uuid.UUID `db:"id"`
|
||||
OrgID string `db:"org_id"`
|
||||
Kind string `db:"kind"`
|
||||
Version int `db:"version"`
|
||||
Body string `db:"body"`
|
||||
CreatedBy string `db:"created_by"`
|
||||
CreatedAt time.Time `db:"created_at"`
|
||||
}
|
||||
|
||||
const policyColumns = `id, org_id, kind, version, body, created_by, created_at`
|
||||
|
||||
// Policy returns a version of a policy set, or the one in force when version
|
||||
// is zero.
|
||||
func (s *Store) Policy(ctx context.Context, orgID, kind string, version int) (PolicySet, error) {
|
||||
var out PolicySet
|
||||
query := `SELECT ` + policyColumns + ` FROM judgement.policy_sets WHERE org_id = $1 AND kind = $2`
|
||||
args := []any{orgID, kind}
|
||||
if version > 0 {
|
||||
query += ` AND version = $3`
|
||||
args = append(args, version)
|
||||
} else {
|
||||
query += ` ORDER BY version DESC LIMIT 1`
|
||||
}
|
||||
err := s.db.GetContext(ctx, &out, query, args...)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return PolicySet{}, ErrNoPolicySet
|
||||
}
|
||||
if err != nil {
|
||||
return PolicySet{}, fmt.Errorf("read policy set: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// PolicyVersions returns every version of a policy set, newest first, without
|
||||
// their bodies.
|
||||
func (s *Store) PolicyVersions(ctx context.Context, orgID, kind string) ([]PolicySet, error) {
|
||||
var out []PolicySet
|
||||
if err := s.db.SelectContext(ctx, &out, `
|
||||
SELECT id, org_id, kind, version, '' AS body, created_by, created_at
|
||||
FROM judgement.policy_sets WHERE org_id = $1 AND kind = $2 ORDER BY version DESC`, orgID, kind); err != nil {
|
||||
return nil, fmt.Errorf("list policy versions: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// AddPolicy stores body as the next version of the kind's policy set. Two
|
||||
// writers racing for one version make the second fail on the unique key.
|
||||
func (s *Store) AddPolicy(ctx context.Context, p PolicySet) (PolicySet, error) {
|
||||
var out PolicySet
|
||||
err := s.db.GetContext(ctx, &out, `
|
||||
INSERT INTO judgement.policy_sets (id, org_id, kind, version, body, created_by)
|
||||
SELECT $1, $2, $3, coalesce(max(version), 0) + 1, $4, $5
|
||||
FROM judgement.policy_sets WHERE org_id = $2 AND kind = $3
|
||||
RETURNING `+policyColumns, p.ID, p.OrgID, p.Kind, p.Body, p.CreatedBy)
|
||||
if err != nil {
|
||||
return PolicySet{}, fmt.Errorf("add policy set: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -98,9 +98,8 @@ type Guard interface {
|
||||
|
||||
// HardRule refuses actions outright. Hard rules run before any guard.
|
||||
type HardRule interface {
|
||||
Name() string
|
||||
// Refuses reports whether the rule forbids the action, and why.
|
||||
Refuses(a Action) (reason string, refused bool)
|
||||
// Refuses reports whether a rule forbids the action: the rule's id and why.
|
||||
Refuses(ctx context.Context, a Action) (by, reason string, refused bool)
|
||||
}
|
||||
|
||||
// Decision is the judgement of one action.
|
||||
@@ -112,9 +111,13 @@ type Decision struct {
|
||||
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"`
|
||||
Reason string `json:"reason,omitzero"`
|
||||
At time.Time `json:"at"`
|
||||
RefusedBy string `json:"refused_by,omitzero"`
|
||||
// ChangeRequest says approval goes through a change request, and
|
||||
// ChangeRequestRule which change-request rule said so.
|
||||
ChangeRequest bool `json:"change_request,omitzero"`
|
||||
ChangeRequestRule string `json:"change_request_rule,omitzero"`
|
||||
Reason string `json:"reason,omitzero"`
|
||||
At time.Time `json:"at"`
|
||||
}
|
||||
|
||||
// Request asks for one action to be judged. Key identifies the attempt to run
|
||||
@@ -126,6 +129,8 @@ type Request struct {
|
||||
Connector string
|
||||
Action string
|
||||
Input jsontext.Value
|
||||
// Workflow is the workflow the run executes, the principal hard rules see.
|
||||
Workflow string
|
||||
}
|
||||
|
||||
// Tools finds the tool that resolves and runs an action.
|
||||
@@ -152,6 +157,8 @@ type Module struct {
|
||||
guards []Guard
|
||||
store recorder
|
||||
failed FailureRecorder
|
||||
// changeRules decides whether approval goes through a change request.
|
||||
changeRules ChangeRules
|
||||
// extensions are the guard extensions asked alongside the built-in guards.
|
||||
extensions GuardExtensions
|
||||
// timeout bounds one guard; zero means guardTimeout.
|
||||
@@ -160,6 +167,10 @@ type Module struct {
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// UseChangeRules makes the module ask rules whether a held action's approval
|
||||
// goes through a change request.
|
||||
func (m *Module) UseChangeRules(r ChangeRules) { m.changeRules = r }
|
||||
|
||||
// UseExtensions makes the module ask every running guard extension alongside
|
||||
// its built-in guards, on each decision.
|
||||
func (m *Module) UseExtensions(e GuardExtensions) { m.extensions = e }
|
||||
@@ -185,7 +196,7 @@ func (m *Module) Assess(ctx context.Context, req Request) (Decision, error) {
|
||||
Connector: req.Connector, Name: req.Action, Input: req.Input,
|
||||
Digest: connectors.Digest(req.Action, req.Input), Target: res.Target, Effect: res.Effect,
|
||||
}
|
||||
d := m.decide(withRun(ctx, RunContext{RunID: req.RunID, Key: req.Key}), a)
|
||||
d := m.decide(withRun(ctx, RunContext{RunID: req.RunID, Key: req.Key, Workflow: req.Workflow}), a)
|
||||
d.ID, d.RunID, d.Key, d.At = uuid.New(), req.RunID, req.Key, m.now().UTC()
|
||||
return m.record(ctx, d)
|
||||
}
|
||||
@@ -194,8 +205,8 @@ func (m *Module) Assess(ctx context.Context, req Request) (Decision, error) {
|
||||
// ceilings: the action runs at the lowest.
|
||||
func (m *Module) decide(ctx context.Context, a Action) Decision {
|
||||
for _, r := range m.rules {
|
||||
if reason, refused := r.Refuses(a); refused {
|
||||
return Decision{Action: a, Level: Never, RefusedBy: r.Name(), Reason: reason, Verdicts: []Verdict{}}
|
||||
if by, reason, refused := r.Refuses(ctx, a); refused {
|
||||
return Decision{Action: a, Level: Never, RefusedBy: by, Reason: reason, Verdicts: []Verdict{}}
|
||||
}
|
||||
}
|
||||
guards := slices.Clone(m.guards)
|
||||
@@ -220,7 +231,12 @@ func (m *Module) decide(ctx context.Context, a Action) Decision {
|
||||
if len(ceilings) > 0 {
|
||||
level = lowest(ceilings...)
|
||||
}
|
||||
return Decision{Action: a, Level: level, Verdicts: verdicts}
|
||||
d := Decision{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)
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// judge asks one guard, turning a failure, a timeout or a missing ceiling
|
||||
|
||||
@@ -37,8 +37,9 @@ func (g fixedGuard) Judge(context.Context, Action) (Verdict, error) {
|
||||
|
||||
type refuseAll struct{}
|
||||
|
||||
func (refuseAll) Name() string { return "no deletes in production" }
|
||||
func (refuseAll) Refuses(Action) (string, bool) { return "production is off limits", true }
|
||||
func (refuseAll) Refuses(context.Context, Action) (string, string, bool) {
|
||||
return "no deletes in production", "production is off limits", true
|
||||
}
|
||||
|
||||
// TestDecisionRunsAtTheLowestCeiling guards the weakest-link decision (spec
|
||||
// section 5, decision tree 8.3): hard rules refuse before any guard runs; the
|
||||
|
||||
@@ -0,0 +1,393 @@
|
||||
package judgement
|
||||
|
||||
import (
|
||||
"context"
|
||||
_ "embed" // the starter policy sets
|
||||
"encoding/json/jsontext"
|
||||
json "encoding/json/v2"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
cedar "github.com/cedar-policy/cedar-go"
|
||||
"github.com/cedar-policy/cedar-go/types"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
||||
"github.com/samcharles93/archie-core/modules/connectors"
|
||||
"github.com/samcharles93/archie-core/modules/judgement/internal/store"
|
||||
)
|
||||
|
||||
// Policy kinds. Hard rules are forbids that run before any guard; change
|
||||
// request rules are permits that run after the guards.
|
||||
const (
|
||||
KindHardRules = "hard_rules"
|
||||
KindChangeRequest = "change_request"
|
||||
maxPolicyBytes = 64 << 10
|
||||
hardRulesUnreadable = "hard-rules-unavailable"
|
||||
changeRuleUnread = "change-request-rules-unavailable"
|
||||
)
|
||||
|
||||
//go:embed starter/hard_rules.cedar
|
||||
var starterHardRules string
|
||||
|
||||
//go:embed starter/change_request.cedar
|
||||
var starterChangeRequest string
|
||||
|
||||
// ChangeRules decides whether an approval goes through a change request.
|
||||
type ChangeRules interface {
|
||||
// Requires returns the rule that sends the action through a change
|
||||
// request, given the level and verdicts the guards reached.
|
||||
Requires(ctx context.Context, a Action, level Level, verdicts []Verdict) (rule string, required bool)
|
||||
}
|
||||
|
||||
type policyStore interface {
|
||||
Policy(ctx context.Context, orgID, kind string, version int) (store.PolicySet, error)
|
||||
PolicyVersions(ctx context.Context, orgID, kind string) ([]store.PolicySet, error)
|
||||
AddPolicy(ctx context.Context, p store.PolicySet) (store.PolicySet, error)
|
||||
}
|
||||
|
||||
// Policies are an organisation's Cedar policy sets: the hard rules and the
|
||||
// change-request rules, every version kept.
|
||||
type Policies struct {
|
||||
orgID string
|
||||
store policyStore
|
||||
log *slog.Logger
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// NewPolicies returns the policy sets of orgID.
|
||||
func NewPolicies(db *sqlx.DB, log *slog.Logger, orgID string) *Policies {
|
||||
return &Policies{orgID: orgID, store: store.New(db), log: log, now: time.Now}
|
||||
}
|
||||
|
||||
var starters = map[string]string{KindHardRules: starterHardRules, KindChangeRequest: starterChangeRequest}
|
||||
|
||||
// current returns the version of a kind in force, seeding the starter set the
|
||||
// first time.
|
||||
func (p *Policies) current(ctx context.Context, kind string) (store.PolicySet, error) {
|
||||
set, err := p.store.Policy(ctx, p.orgID, kind, 0)
|
||||
if !errors.Is(err, store.ErrNoPolicySet) {
|
||||
return set, err
|
||||
}
|
||||
if _, err := p.store.AddPolicy(ctx, store.PolicySet{ID: uuid.New(), OrgID: p.orgID, Kind: kind, Body: starters[kind], CreatedBy: "starter"}); err != nil {
|
||||
// Another writer seeded it first.
|
||||
if again, rerr := p.store.Policy(ctx, p.orgID, kind, 0); rerr == nil {
|
||||
return again, nil
|
||||
}
|
||||
return store.PolicySet{}, err
|
||||
}
|
||||
return p.store.Policy(ctx, p.orgID, kind, 0)
|
||||
}
|
||||
|
||||
// parse compiles a policy set. Every policy needs a unique @id and must be a
|
||||
// forbid in hard rules or a permit in change-request rules.
|
||||
func parse(kind, body string) (*cedar.PolicySet, error) {
|
||||
list, err := cedar.NewPolicyListFromBytes(kind, []byte(body))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse policies: %w", err)
|
||||
}
|
||||
want := cedar.Forbid
|
||||
if kind == KindChangeRequest {
|
||||
want = cedar.Permit
|
||||
}
|
||||
set := cedar.NewPolicySet()
|
||||
for i, pol := range list {
|
||||
id := pol.Annotations()["id"]
|
||||
switch {
|
||||
case id == "":
|
||||
return nil, fmt.Errorf("policy %d needs an @id annotation", i+1)
|
||||
case pol.Effect() != want:
|
||||
return nil, fmt.Errorf("policy %q must be a %s", id, effectName(want))
|
||||
case !set.Add(cedar.PolicyID(id), pol):
|
||||
return nil, fmt.Errorf("policy id %q is used twice", id)
|
||||
}
|
||||
}
|
||||
return set, nil
|
||||
}
|
||||
|
||||
func effectName(e cedar.Effect) string {
|
||||
if e == cedar.Forbid {
|
||||
return "forbid"
|
||||
}
|
||||
return "permit"
|
||||
}
|
||||
|
||||
// Refuses reports whether a hard rule forbids the action, naming the policy.
|
||||
// A policy set that can't be read or evaluated refuses: a rule that can't be
|
||||
// checked is not one to run past.
|
||||
func (p *Policies) Refuses(ctx context.Context, a Action) (by, reason string, refused bool) {
|
||||
set, err := p.compiled(ctx, KindHardRules)
|
||||
if err != nil {
|
||||
p.log.ErrorContext(ctx, "read hard rules", "error", err)
|
||||
return hardRulesUnreadable, "the hard rules couldn't be read", true
|
||||
}
|
||||
_, diag := cedar.Authorize(set, entities(ctx, a), request(ctx, a, nil))
|
||||
if len(diag.Reasons) > 0 {
|
||||
return p.explain(set, diag.Reasons[0].PolicyID, "refused by hard rule")
|
||||
}
|
||||
if len(diag.Errors) > 0 {
|
||||
return p.explain(set, diag.Errors[0].PolicyID, "a hard rule couldn't be evaluated: "+diag.Errors[0].Message)
|
||||
}
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
func (p *Policies) explain(set *cedar.PolicySet, id cedar.PolicyID, fallback string) (string, string, bool) {
|
||||
if pol := set.Get(id); pol != nil {
|
||||
if r := pol.Annotations()["reason"]; r != "" {
|
||||
return string(id), string(r), true
|
||||
}
|
||||
}
|
||||
return string(id), fallback + " " + string(id), true
|
||||
}
|
||||
|
||||
// Requires reports the change-request rule that matches the action and what
|
||||
// the guards decided. A rule that can't be evaluated counts as matching:
|
||||
// more oversight is the safe side.
|
||||
func (p *Policies) Requires(ctx context.Context, a Action, level Level, verdicts []Verdict) (string, bool) {
|
||||
set, err := p.compiled(ctx, KindChangeRequest)
|
||||
if err != nil {
|
||||
p.log.ErrorContext(ctx, "read change-request rules", "error", err)
|
||||
return changeRuleUnread, true
|
||||
}
|
||||
decision, diag := cedar.Authorize(set, entities(ctx, a), request(ctx, a, verdictContext(level, verdicts)))
|
||||
if decision == types.Allow && len(diag.Reasons) > 0 {
|
||||
return string(diag.Reasons[0].PolicyID), true
|
||||
}
|
||||
if len(diag.Errors) > 0 {
|
||||
return string(diag.Errors[0].PolicyID), true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func (p *Policies) compiled(ctx context.Context, kind string) (*cedar.PolicySet, error) {
|
||||
row, err := p.current(ctx, kind)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return parse(kind, row.Body)
|
||||
}
|
||||
|
||||
func entities(ctx context.Context, a Action) types.EntityMap {
|
||||
principal := types.NewEntityUID("Workflow", types.String(runFrom(ctx).Workflow))
|
||||
resource := resourceUID(a)
|
||||
return types.EntityMap{
|
||||
principal: {UID: principal, Attributes: types.NewRecord(types.RecordMap{"name": types.String(runFrom(ctx).Workflow)})},
|
||||
resource: {UID: resource, Attributes: types.NewRecord(types.RecordMap{
|
||||
"kind": types.String(a.Target.Kind), "id": types.String(a.Target.ID),
|
||||
"environment": types.String(a.Target.Environment), "disposable": types.Boolean(a.Target.Disposable),
|
||||
})},
|
||||
}
|
||||
}
|
||||
|
||||
func resourceUID(a Action) types.EntityUID {
|
||||
return types.NewEntityUID("Target", types.String(a.Target.Kind+"/"+a.Target.ID))
|
||||
}
|
||||
|
||||
func request(ctx context.Context, a Action, extra types.RecordMap) types.Request {
|
||||
cc := types.RecordMap{
|
||||
"effect": types.NewRecord(types.RecordMap{
|
||||
"read_only": types.Boolean(a.Effect.ReadOnly),
|
||||
"reversibility": types.String(reversibilityName(a.Effect.Reversibility)),
|
||||
"summary": types.String(a.Effect.Summary),
|
||||
}),
|
||||
"input": inputValue(a.Input),
|
||||
}
|
||||
maps.Copy(cc, extra)
|
||||
return types.Request{
|
||||
Principal: types.NewEntityUID("Workflow", types.String(runFrom(ctx).Workflow)),
|
||||
Action: types.NewEntityUID("Action", types.String(a.Connector+"::"+a.Name)),
|
||||
Resource: resourceUID(a),
|
||||
Context: types.NewRecord(cc),
|
||||
}
|
||||
}
|
||||
|
||||
func reversibilityName(r connectors.Reversibility) string {
|
||||
switch r {
|
||||
case connectors.UndoneAutomatically:
|
||||
return "undone_automatically"
|
||||
case connectors.Recoverable:
|
||||
return "recoverable"
|
||||
case connectors.Irreversible:
|
||||
return "irreversible"
|
||||
}
|
||||
return "unspecified"
|
||||
}
|
||||
|
||||
// verdictContext is what change-request rules read of the guards: the level
|
||||
// they reached, whether any guard failed to answer, and each guard's verdict
|
||||
// by name.
|
||||
func verdictContext(level Level, verdicts []Verdict) types.RecordMap {
|
||||
byGuard := types.RecordMap{}
|
||||
failed := false
|
||||
for _, v := range verdicts {
|
||||
failed = failed || v.Failed != ""
|
||||
byGuard[types.String(v.Guard)] = types.NewRecord(types.RecordMap{
|
||||
"ceiling": types.String(v.Ceiling.String()), "failed": types.Boolean(v.Failed != ""), "advisory": types.Boolean(v.Advisory),
|
||||
})
|
||||
}
|
||||
return types.RecordMap{"level": types.String(level.String()), "guard_failed": types.Boolean(failed), "verdicts": types.NewRecord(byGuard)}
|
||||
}
|
||||
|
||||
// inputValue converts an action's JSON input to a Cedar record. Cedar has no
|
||||
// null or float: null members are left out and a non-integer number is its
|
||||
// decimal text.
|
||||
func inputValue(in jsontext.Value) types.Value {
|
||||
var v any
|
||||
if len(in) == 0 || json.Unmarshal(in, &v) != nil {
|
||||
return types.NewRecord(nil)
|
||||
}
|
||||
if out, ok := cedarValue(v).(types.Record); ok {
|
||||
return out
|
||||
}
|
||||
return types.NewRecord(types.RecordMap{"value": cedarValue(v)})
|
||||
}
|
||||
|
||||
func cedarValue(v any) types.Value {
|
||||
switch x := v.(type) {
|
||||
case map[string]any:
|
||||
m := types.RecordMap{}
|
||||
for k, e := range x {
|
||||
if e != nil {
|
||||
m[types.String(k)] = cedarValue(e)
|
||||
}
|
||||
}
|
||||
return types.NewRecord(m)
|
||||
case []any:
|
||||
items := make([]types.Value, 0, len(x))
|
||||
for _, e := range x {
|
||||
if e != nil {
|
||||
items = append(items, cedarValue(e))
|
||||
}
|
||||
}
|
||||
return types.NewSet(items...)
|
||||
case string:
|
||||
return types.String(x)
|
||||
case bool:
|
||||
return types.Boolean(x)
|
||||
case float64:
|
||||
if x == math.Trunc(x) && math.Abs(x) < 1<<53 {
|
||||
return types.Long(int64(x))
|
||||
}
|
||||
return types.String(strconv.FormatFloat(x, 'g', -1, 64))
|
||||
}
|
||||
return types.String(fmt.Sprint(v))
|
||||
}
|
||||
|
||||
// PolicySetView is one version of a policy set, with every version's number.
|
||||
type PolicySetView struct {
|
||||
Version int `json:"version"`
|
||||
Body string `json:"body"`
|
||||
CreatedBy string `json:"created_by"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Versions []VersionView `json:"versions"`
|
||||
}
|
||||
|
||||
// VersionView is one stored version of a policy set.
|
||||
type VersionView struct {
|
||||
Version int `json:"version"`
|
||||
CreatedBy string `json:"created_by"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// View returns a version of a kind's policy set, or the one in force when
|
||||
// version is zero.
|
||||
func (p *Policies) View(ctx context.Context, kind string, version int) (PolicySetView, error) {
|
||||
row, err := p.current(ctx, kind)
|
||||
if err == nil && version > 0 {
|
||||
row, err = p.store.Policy(ctx, p.orgID, kind, version)
|
||||
}
|
||||
if err != nil {
|
||||
return PolicySetView{}, err
|
||||
}
|
||||
rows, err := p.store.PolicyVersions(ctx, p.orgID, kind)
|
||||
if err != nil {
|
||||
return PolicySetView{}, err
|
||||
}
|
||||
out := PolicySetView{Version: row.Version, Body: row.Body, CreatedBy: row.CreatedBy, CreatedAt: row.CreatedAt}
|
||||
for _, r := range rows {
|
||||
out.Versions = append(out.Versions, VersionView{Version: r.Version, CreatedBy: r.CreatedBy, CreatedAt: r.CreatedAt})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Put validates body and stores it as the next version of the kind's policy
|
||||
// set. A body that doesn't compile changes nothing.
|
||||
func (p *Policies) Put(ctx context.Context, kind, body, by string) (PolicySetView, error) {
|
||||
if len(body) > maxPolicyBytes {
|
||||
return PolicySetView{}, fmt.Errorf("%w: at most %d bytes", ErrInvalidPolicy, maxPolicyBytes)
|
||||
}
|
||||
if _, err := parse(kind, body); err != nil {
|
||||
return PolicySetView{}, fmt.Errorf("%w: %w", ErrInvalidPolicy, err)
|
||||
}
|
||||
if _, err := p.current(ctx, kind); err != nil {
|
||||
return PolicySetView{}, err
|
||||
}
|
||||
if _, err := p.store.AddPolicy(ctx, store.PolicySet{ID: uuid.New(), OrgID: p.orgID, Kind: kind, Body: body, CreatedBy: by}); err != nil {
|
||||
return PolicySetView{}, err
|
||||
}
|
||||
return p.View(ctx, kind, 0)
|
||||
}
|
||||
|
||||
// ErrInvalidPolicy means a policy set didn't compile or didn't fit its kind.
|
||||
var ErrInvalidPolicy = errors.New("invalid policy set")
|
||||
|
||||
// Routes adds the policy API to mux behind guard.
|
||||
func (p *Policies) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler) {
|
||||
for path, kind := range map[string]string{"/api/policies/hard-rules": KindHardRules, "/api/policies/change-request": KindChangeRequest} {
|
||||
mux.Handle("GET "+path, guard(p.get(kind)))
|
||||
mux.Handle("PUT "+path, guard(p.put(kind)))
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Policies) get(kind string) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
version := 0
|
||||
if q := r.URL.Query().Get("version"); q != "" {
|
||||
n, err := strconv.Atoi(q)
|
||||
if err != nil || n < 1 {
|
||||
httpjson.Error(w, http.StatusBadRequest, "version is a number")
|
||||
return
|
||||
}
|
||||
version = n
|
||||
}
|
||||
out, err := p.View(r.Context(), kind, version)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNoPolicySet):
|
||||
httpjson.Error(w, http.StatusNotFound, "no such version")
|
||||
case err != nil:
|
||||
p.log.ErrorContext(r.Context(), "read policies", "kind", kind, "error", err)
|
||||
httpjson.Error(w, http.StatusInternalServerError, "couldn't read the policies")
|
||||
default:
|
||||
httpjson.Write(w, http.StatusOK, out)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (p *Policies) put(kind string) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Body string `json:"body"`
|
||||
}
|
||||
if err := httpjson.Read(r, &req); err != nil {
|
||||
httpjson.Error(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
out, err := p.Put(r.Context(), kind, req.Body, bootstrapAdmin)
|
||||
switch {
|
||||
case errors.Is(err, ErrInvalidPolicy):
|
||||
httpjson.Error(w, http.StatusBadRequest, err.Error())
|
||||
case err != nil:
|
||||
p.log.ErrorContext(r.Context(), "save policies", "kind", kind, "error", err)
|
||||
httpjson.Error(w, http.StatusInternalServerError, "couldn't save the policies")
|
||||
default:
|
||||
httpjson.Write(w, http.StatusOK, out)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package judgement
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json/jsontext"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/modules/connectors"
|
||||
"github.com/samcharles93/archie-core/modules/judgement/internal/store"
|
||||
)
|
||||
|
||||
type memoryPolicies struct{ sets map[string][]store.PolicySet }
|
||||
|
||||
func (m *memoryPolicies) Policy(_ context.Context, _, kind string, _ int) (store.PolicySet, error) {
|
||||
v := m.sets[kind]
|
||||
if len(v) == 0 {
|
||||
return store.PolicySet{}, store.ErrNoPolicySet
|
||||
}
|
||||
return v[len(v)-1], nil
|
||||
}
|
||||
|
||||
func (m *memoryPolicies) PolicyVersions(context.Context, string, string) ([]store.PolicySet, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *memoryPolicies) AddPolicy(_ context.Context, p store.PolicySet) (store.PolicySet, error) {
|
||||
p.Version = len(m.sets[p.Kind]) + 1
|
||||
m.sets[p.Kind] = append(m.sets[p.Kind], p)
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// TestStarterPoliciesDecide guards the policy layer (spec section 5 rule 1,
|
||||
// R25): a hard rule refuses before any guard runs and a refusal names the
|
||||
// policy; the unknown-impact change-request rule flags a held action for a
|
||||
// change request, and only a held one.
|
||||
func TestStarterPoliciesDecide(t *testing.T) {
|
||||
prod := connectors.Target{Kind: "host", ID: "h1", Environment: "production"}
|
||||
tests := []struct {
|
||||
name string
|
||||
target connectors.Target
|
||||
effect connectors.Effect
|
||||
guard fixedGuard
|
||||
wantRefused string
|
||||
wantRule string
|
||||
wantLevel Level
|
||||
}{
|
||||
{
|
||||
name: "irreversible in production is refused before any guard", target: prod,
|
||||
effect: connectors.Effect{Reversibility: connectors.Irreversible}, guard: fixedGuard{name: "g", ceiling: ActQuietly},
|
||||
wantRefused: "no-irreversible-in-production", wantLevel: Never,
|
||||
},
|
||||
{
|
||||
name: "irreversible in staging is judged", target: connectors.Target{Kind: "host", ID: "h1", Environment: "staging"},
|
||||
effect: connectors.Effect{Reversibility: connectors.Irreversible}, guard: fixedGuard{name: "g", ceiling: ProposeAndWait},
|
||||
wantLevel: ProposeAndWait,
|
||||
},
|
||||
{
|
||||
name: "unknown impact held goes through a change request", target: prod,
|
||||
effect: connectors.Effect{}, guard: fixedGuard{name: "g", err: errors.New("no evidence")},
|
||||
wantRule: "unknown-impact", wantLevel: ProposeAndWait,
|
||||
},
|
||||
{
|
||||
name: "known impact held needs no change request", target: prod,
|
||||
effect: connectors.Effect{Reversibility: connectors.Recoverable}, guard: fixedGuard{name: "g", ceiling: ProposeAndWait},
|
||||
wantLevel: ProposeAndWait,
|
||||
},
|
||||
{
|
||||
name: "unknown impact that acts quietly needs no change request", target: prod,
|
||||
effect: connectors.Effect{}, guard: fixedGuard{name: "g", ceiling: ActQuietly},
|
||||
wantLevel: ActQuietly,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
tt.guard.calls = &calls
|
||||
p := &Policies{store: &memoryPolicies{sets: map[string][]store.PolicySet{}}, log: slog.New(slog.DiscardHandler)}
|
||||
m := &Module{rules: []HardRule{p}, changeRules: p, guards: []Guard{tt.guard}}
|
||||
a := Action{Connector: "ssh", Name: "rm", Input: jsontext.Value(`{"path":"/data"}`), Target: tt.target, Effect: tt.effect}
|
||||
d := m.decide(withRun(t.Context(), RunContext{Workflow: "cleanup"}), a)
|
||||
if d.Level != tt.wantLevel || d.RefusedBy != tt.wantRefused || d.ChangeRequestRule != tt.wantRule || d.ChangeRequest != (tt.wantRule != "") {
|
||||
t.Fatalf("decision = level %s, refused by %q, change request %v by %q; want %s, %q, rule %q",
|
||||
d.Level, d.RefusedBy, d.ChangeRequest, d.ChangeRequestRule, tt.wantLevel, tt.wantRefused, tt.wantRule)
|
||||
}
|
||||
if tt.wantRefused != "" && calls.Load() != 0 {
|
||||
t.Fatalf("a guard ran %d times before the hard rule refused", calls.Load())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// A change-request rule is a permit. It runs after the guards and decides only
|
||||
// whether approval goes through a change request.
|
||||
@id("unknown-impact")
|
||||
permit (principal, action, resource)
|
||||
when {
|
||||
context.effect.read_only == false &&
|
||||
(context.effect.reversibility == "unspecified" || context.guard_failed)
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
// A hard rule is a forbid. It runs before any guard on the exact action and
|
||||
// target, and nothing overrides it.
|
||||
@id("no-irreversible-in-production")
|
||||
forbid (principal, action, resource)
|
||||
when {
|
||||
resource.environment == "production" &&
|
||||
resource.disposable == false &&
|
||||
context.effect.read_only == false &&
|
||||
context.effect.reversibility == "irreversible"
|
||||
};
|
||||
@@ -87,6 +87,9 @@ func (rc *Context) Begin(ctx context.Context, key string) (bool, error) {
|
||||
// RunID is the run's id.
|
||||
func (rc *Context) RunID() uuid.UUID { return rc.run.ID }
|
||||
|
||||
// Workflow is the name of the workflow this run executes.
|
||||
func (rc *Context) Workflow() string { return rc.run.Workflow }
|
||||
|
||||
// OrgID is the organisation the run belongs to.
|
||||
func (rc *Context) OrgID() string { return rc.run.OrgID }
|
||||
|
||||
|
||||
@@ -389,6 +389,7 @@ func runApproved(rc *Context, judge Judge, d judgement.Decision, answer approval
|
||||
fresh, err := rc.Step("judge-again:"+d.Key, func(ctx context.Context, key string) (judgement.Decision, error) {
|
||||
return judge.Assess(ctx, judgement.Request{
|
||||
RunID: rc.RunID(), Key: key, Connector: d.Action.Connector, Action: d.Action.Name, Input: d.Action.Input,
|
||||
Workflow: rc.Workflow(),
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
@@ -531,7 +532,7 @@ func call(ctx context.Context, box Toolbox, judge Judge, rc *Context, d connecto
|
||||
// is proposed to a person when the investigation ends, so it comes back to
|
||||
// the agent as something waiting rather than a failure.
|
||||
key := core.IdempotencyKey(ctx)
|
||||
decision, err := judge.Assess(ctx, judgement.Request{RunID: rc.RunID(), Key: key, Connector: d.Connector, Action: d.Name, Input: input})
|
||||
decision, err := judge.Assess(ctx, judgement.Request{RunID: rc.RunID(), Key: key, Connector: d.Connector, Action: d.Name, Input: input, Workflow: rc.Workflow()})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
@@ -43,6 +43,8 @@ const ceilingTone = (v: Verdict): Tone => (v.failed ? "warn" : "secondary");
|
||||
<span class="font-medium">{{ decision.action.connector }} {{ decision.action.name }}</span>
|
||||
<span class="text-caption text-muted-foreground">{{ target }}</span>
|
||||
<Badge :variant="decision.reason ? 'danger' : 'secondary'">{{ decision.level }}</Badge>
|
||||
<Badge v-if="decision.refused_by" variant="danger">{{ decision.refused_by }}</Badge>
|
||||
<Badge v-if="decision.change_request" variant="warn">Change request: {{ decision.change_request_rule }}</Badge>
|
||||
<Timestamp :at="decision.at" class="ml-auto text-caption" />
|
||||
</div>
|
||||
<p v-if="decision.action.effect.Summary" class="text-muted-foreground">{{ decision.action.effect.Summary }}</p>
|
||||
|
||||
@@ -36,6 +36,7 @@ function signOut() {
|
||||
<RouterLink to="/runs" active-class="text-foreground" class="text-muted-foreground">Runs</RouterLink>
|
||||
<RouterLink to="/classes" active-class="text-foreground" class="text-muted-foreground">Classes</RouterLink>
|
||||
<RouterLink to="/people" active-class="text-foreground" class="text-muted-foreground">People</RouterLink>
|
||||
<RouterLink to="/policies" active-class="text-foreground" class="text-muted-foreground">Policies</RouterLink>
|
||||
<RouterLink to="/settings" active-class="text-foreground" class="text-muted-foreground">Settings</RouterLink>
|
||||
<Button variant="ghost" size="xs" class="ml-auto" @click="signOut">Sign out</Button>
|
||||
</nav>
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, reactive, ref } from "vue";
|
||||
|
||||
import PageHeader from "@/base/PageHeader.vue";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Timestamp } from "@/components/ui/timestamp";
|
||||
import { getPolicies, savePolicies, Unauthorized, type PolicyKind, type PolicySet } from "./api";
|
||||
|
||||
/** Cedar policy sets: hard rules run before the guards, change-request rules after. */
|
||||
const emit = defineEmits<{ unauthorized: [] }>();
|
||||
|
||||
interface Editor {
|
||||
kind: PolicyKind;
|
||||
title: string;
|
||||
current?: PolicySet;
|
||||
body: string;
|
||||
saving: boolean;
|
||||
error: string;
|
||||
}
|
||||
|
||||
const editors = reactive<Editor[]>([
|
||||
{ kind: "hard-rules", title: "Hard rules", body: "", saving: false, error: "" },
|
||||
{ kind: "change-request", title: "Change-request rules", body: "", saving: false, error: "" },
|
||||
]);
|
||||
const loading = ref(true);
|
||||
const loadError = ref("");
|
||||
const controller = new AbortController();
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
loadError.value = "";
|
||||
try {
|
||||
const sets = await Promise.all(editors.map((e) => getPolicies(e.kind, controller.signal)));
|
||||
editors.forEach((e, i) => {
|
||||
e.current = sets[i];
|
||||
e.body = sets[i].body;
|
||||
});
|
||||
} catch (err) {
|
||||
fail(err, (m) => (loadError.value = m));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function save(e: Editor) {
|
||||
e.saving = true;
|
||||
e.error = "";
|
||||
try {
|
||||
e.current = await savePolicies(e.kind, e.body);
|
||||
e.body = e.current.body;
|
||||
} catch (err) {
|
||||
fail(err, (m) => (e.error = m));
|
||||
} finally {
|
||||
e.saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
function fail(err: unknown, show: (message: string) => void) {
|
||||
if (controller.signal.aborted) return;
|
||||
if (err instanceof Unauthorized) emit("unauthorized");
|
||||
show(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
onBeforeUnmount(() => controller.abort());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<PageHeader title="Policies" />
|
||||
<Spinner v-if="loading" />
|
||||
<ReadError v-else-if="loadError" :message="loadError" retry-label="Retry" @retry="load" />
|
||||
<template v-else>
|
||||
<Section v-for="e in editors" :key="e.kind" :title="e.title">
|
||||
<Textarea v-model="e.body" :aria-label="e.title" rows="12" class="font-mono" spellcheck="false" />
|
||||
<p v-if="e.error" class="mt-2 text-caption text-danger">{{ e.error }}</p>
|
||||
<div class="mt-2 flex items-center gap-3">
|
||||
<Button :disabled="e.saving || e.body === e.current?.body" @click="save(e)">Save</Button>
|
||||
<span v-if="e.current" class="text-caption text-muted-foreground">
|
||||
Version {{ e.current.version }}, <Timestamp :at="e.current.created_at" /> by {{ e.current.created_by }}
|
||||
</span>
|
||||
</div>
|
||||
</Section>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -102,6 +102,8 @@ export interface Decision {
|
||||
level: string;
|
||||
verdicts: Verdict[];
|
||||
refused_by?: string;
|
||||
change_request?: boolean;
|
||||
change_request_rule?: string;
|
||||
reason?: string;
|
||||
at: string;
|
||||
}
|
||||
@@ -173,6 +175,10 @@ export const saveSettings = (next: Settings) => put("/api/settings", next);
|
||||
export const savePeople = (next: Person[]) => put("/api/people", next);
|
||||
|
||||
async function put(path: string, payload: unknown): Promise<void> {
|
||||
await putJSON(path, payload);
|
||||
}
|
||||
|
||||
async function putJSON<T>(path: string, payload: unknown): Promise<T> {
|
||||
const res = await fetch(path, {
|
||||
method: "PUT",
|
||||
headers: { Authorization: `Bearer ${token()}`, "Content-Type": "application/json" },
|
||||
@@ -183,8 +189,23 @@ async function put(path: string, payload: unknown): Promise<void> {
|
||||
const body = (await res.json().catch(() => ({}))) as { error?: string };
|
||||
throw new Error(body.error ?? `${res.status} ${res.statusText}`);
|
||||
}
|
||||
return (await res.json().catch(() => undefined)) as T;
|
||||
}
|
||||
|
||||
export interface PolicySet {
|
||||
version: number;
|
||||
body: string;
|
||||
created_by: string;
|
||||
created_at: string;
|
||||
versions: { version: number; created_by: string; created_at: string }[];
|
||||
}
|
||||
|
||||
export type PolicyKind = "hard-rules" | "change-request";
|
||||
|
||||
export const getPolicies = (kind: PolicyKind, signal?: AbortSignal) => get<PolicySet>(`/api/policies/${kind}`, signal);
|
||||
|
||||
export const savePolicies = (kind: PolicyKind, body: string) => putJSON<PolicySet>(`/api/policies/${kind}`, { body });
|
||||
|
||||
export const latestMessages = (signal?: AbortSignal) => get<Message[]>("/api/composer/messages", signal);
|
||||
export const messagesAfter = (seq: number, signal?: AbortSignal) =>
|
||||
get<Message[]>(`/api/composer/messages?after=${seq}`, signal);
|
||||
|
||||
@@ -9,6 +9,7 @@ export default createRouter({
|
||||
{ path: "/classes", name: "classes", component: () => import("./ClassesView.vue") },
|
||||
{ path: "/classes/:id", name: "class", component: () => import("./ClassView.vue"), props: true },
|
||||
{ path: "/people", name: "people", component: () => import("./PeopleView.vue") },
|
||||
{ path: "/policies", name: "policies", component: () => import("./PoliciesView.vue") },
|
||||
{ path: "/settings", name: "settings", component: () => import("./SettingsView.vue") },
|
||||
{ path: "/runs/:id", name: "run", component: () => import("./RunView.vue"), props: true },
|
||||
],
|
||||
|
||||
Reference in new issue
Block a user