441 lines
15 KiB
Go
441 lines
15 KiB
Go
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"
|
|
"strings"
|
|
"time"
|
|
|
|
cedar "github.com/cedar-policy/cedar-go"
|
|
"github.com/cedar-policy/cedar-go/types"
|
|
"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/connectors"
|
|
"github.com/samcharles93/archie-core/modules/governance"
|
|
"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: string(governance.SystemID)}); 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
|
|
}
|
|
|
|
// PolicyOverlay is policy text of one kind added to the set in force, for a
|
|
// dry run judging a draft before it is published.
|
|
type PolicyOverlay struct {
|
|
Kind string `json:"kind"`
|
|
Body string `json:"body"`
|
|
}
|
|
|
|
func (p *Policies) compiled(ctx context.Context, kind string) (*cedar.PolicySet, error) {
|
|
row, err := p.current(ctx, kind)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
body := row.Body
|
|
if o := runFrom(ctx).Overlay; o != nil && o.Kind == kind {
|
|
body = joined(body, o.Body)
|
|
}
|
|
return parse(kind, body)
|
|
}
|
|
|
|
func joined(current, extra string) string { return current + "\n\n" + extra }
|
|
|
|
// Check reports whether extra, added to the set of kind in force, is a valid
|
|
// policy set: it compiles, fits the kind and reuses no policy id.
|
|
func (p *Policies) Check(ctx context.Context, kind, extra string) error {
|
|
row, err := p.current(ctx, kind)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if strings.Contains(row.Body, strings.TrimSpace(extra)) {
|
|
return nil
|
|
}
|
|
if _, err := parse(kind, joined(row.Body, extra)); err != nil {
|
|
return fmt.Errorf("%w: %w", ErrInvalidPolicy, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Append stores the set in force with extra added as the next version. Text
|
|
// the set already contains is not added again, so a retried publish is safe.
|
|
func (p *Policies) Append(ctx context.Context, kind, extra, by string) (PolicySetView, error) {
|
|
row, err := p.current(ctx, kind)
|
|
if err != nil {
|
|
return PolicySetView{}, err
|
|
}
|
|
if strings.Contains(row.Body, strings.TrimSpace(extra)) {
|
|
return p.View(ctx, kind, 0)
|
|
}
|
|
return p.Put(ctx, kind, joined(row.Body, extra), by)
|
|
}
|
|
|
|
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")
|
|
|
|
// Register adds the policy API.
|
|
func (p *Policies) Register(api huma.API) {
|
|
tags := []string{"Controls"}
|
|
for _, k := range []struct{ kind, path, id, noun string }{
|
|
{KindHardRules, "/api/policies/hard-rules", "hard-rules", "hard rules"},
|
|
{KindChangeRequest, "/api/policies/change-request", "change-request-rules", "change-request rules"},
|
|
} {
|
|
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindGuard), huma.Operation{
|
|
OperationID: "get-" + k.id, Method: http.MethodGet, Path: k.path,
|
|
Summary: "Get the " + k.noun, Tags: tags,
|
|
}, p.get(k.kind))
|
|
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindGuard), huma.Operation{
|
|
OperationID: "put-" + k.id, Method: http.MethodPut, Path: k.path,
|
|
Summary: "Replace the " + k.noun + " with a new version", Tags: tags,
|
|
}, p.put(k.kind))
|
|
}
|
|
}
|
|
|
|
func (p *Policies) get(kind string) func(context.Context, *policyVersionInput) (*httpapi.Reply[PolicySetView], error) {
|
|
return func(ctx context.Context, in *policyVersionInput) (*httpapi.Reply[PolicySetView], error) {
|
|
out, err := p.View(ctx, kind, in.Version)
|
|
switch {
|
|
case errors.Is(err, store.ErrNoPolicySet):
|
|
return nil, huma.Error404NotFound("no such version")
|
|
case err != nil:
|
|
p.log.ErrorContext(ctx, "read policies", "kind", kind, "error", err)
|
|
return nil, huma.Error500InternalServerError("couldn't read the policies")
|
|
}
|
|
return httpapi.OK(out), nil
|
|
}
|
|
}
|
|
|
|
type policyVersionInput struct {
|
|
Version int `query:"version" minimum:"1" doc:"A past version; the current one by default"`
|
|
}
|
|
|
|
type policyInput struct {
|
|
Body struct {
|
|
Body string `json:"body" doc:"The whole policy set, as Cedar"`
|
|
}
|
|
}
|
|
|
|
func (p *Policies) put(kind string) func(context.Context, *policyInput) (*httpapi.Reply[PolicySetView], error) {
|
|
return func(ctx context.Context, in *policyInput) (*httpapi.Reply[PolicySetView], error) {
|
|
out, err := p.Put(ctx, kind, in.Body.Body, governance.CallerID(ctx))
|
|
switch {
|
|
case errors.Is(err, ErrInvalidPolicy):
|
|
return nil, huma.Error400BadRequest(err.Error())
|
|
case err != nil:
|
|
p.log.ErrorContext(ctx, "save policies", "kind", kind, "error", err)
|
|
return nil, huma.Error500InternalServerError("couldn't save the policies")
|
|
}
|
|
return httpapi.OK(out), nil
|
|
}
|
|
}
|