Files
archie/modules/governance/access_api.go
T
sam 062336db91 refactor: rename denial records to access decisions
- rename governance.access_denials table, indexes and API types via migration 00061
- expose /api/access/decisions and decisions payload; keep audit auth unchanged
- rename UI store, page and route from denials to decisions
2026-11-23 02:03:35 +11:00

180 lines
7.0 KiB
Go

package governance
import (
"context"
"errors"
"log/slog"
"net/http"
"time"
"github.com/danielgtaylor/huma/v2"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
)
// policyAdmin is the stored policy chain the routes edit. PutPolicy and
// DeletePolicy refuse a change that leaves an org with nobody able to manage
// policies.
type policyAdmin interface {
ListPolicies(context.Context) ([]Policy, error)
PutPolicy(context.Context, Policy) (int64, error)
DeletePolicy(context.Context, Policy) error
}
// decisionSearch reads the recorded decisions.
type decisionSearch interface {
SearchDecisions(context.Context, DecisionQuery) ([]DecisionRecord, error)
}
// accessAPI serves the access policies and the record of decisions.
type accessAPI struct {
policies policyAdmin
decisions decisionSearch
log *slog.Logger
}
func (m *Module) access() *accessAPI {
return &accessAPI{policies: m, decisions: m, log: m.log}
}
type policiesBody struct {
Policies []Policy `json:"policies"`
Shipped []string `json:"shipped" doc:"IDs of the org policies Archie ships. They can be edited but not deleted, and a reset restores them"`
}
type policyVersionBody struct {
Version int64 `json:"version" doc:"The policy chain's new revision"`
}
type policyInput struct {
Body Policy
}
type decisionsInput struct {
Principal string `query:"principal" doc:"Only decisions about this identity"`
Action string `query:"action" doc:"Only decisions about this action"`
Kind string `query:"kind" doc:"Only decisions about this resource kind"`
Outcome string `query:"outcome" enum:"allowed,denied" doc:"Only decisions with this outcome. Default: every outcome"`
Since time.Time `query:"since" doc:"Only decisions first recorded at or after this time"`
Until time.Time `query:"until" doc:"Only decisions first recorded before this time"`
Limit int `query:"limit" default:"100" minimum:"1" maximum:"1000" doc:"How many decisions to return"`
Offset int `query:"offset" default:"0" minimum:"0" doc:"How many of the newest matching decisions to skip"`
}
type decisionsBody struct {
Decisions []DecisionRecord `json:"decisions"`
More bool `json:"more" doc:"Whether older decisions match beyond this page"`
}
func (m *Module) registerPolicies(api huma.API, op func(id, method, path, summary string, status int) huma.Operation) {
a := m.access()
httpapi.Register(api, httpapi.Authorized(ActionRead, KindPolicy), op("list-access-policies", http.MethodGet, "/api/access/policies", "List the organisation's access policies", 0), a.listPolicies)
httpapi.Register(api, httpapi.Authorized(ActionManagePolicies, KindPolicy), op("put-access-policy", http.MethodPut, "/api/access/policies", "Create or replace an access policy", 0), a.putPolicy)
httpapi.Register(api, httpapi.Authorized(ActionManagePolicies, KindPolicy), op("delete-access-policy", http.MethodDelete, "/api/access/policies", "Delete an access policy", http.StatusNoContent), a.deletePolicy)
}
func (m *Module) registerDecisions(api huma.API, op func(id, method, path, summary string, status int) huma.Operation) {
a := m.access()
httpapi.Register(api, httpapi.Authorized(ActionReadAudit, KindAudit), op("list-access-decisions", http.MethodGet, "/api/access/decisions", "List access policy decisions", 0), a.listDecisions)
}
func (a *accessAPI) listPolicies(ctx context.Context, _ *struct{}) (*httpapi.Reply[policiesBody], error) {
p, err := caller(ctx)
if err != nil {
return nil, err
}
stored, err := a.policies.ListPolicies(ctx)
if err != nil {
return nil, a.failed(ctx, "read the policies", err)
}
out := make([]Policy, 0, len(stored))
for _, s := range stored {
if s.Level == LevelInstance && p.InstanceAdmin() || s.Level != LevelInstance && s.OrgID == p.Org {
out = append(out, s)
}
}
return httpapi.OK(policiesBody{Policies: out, Shipped: shippedOrgPolicyIDs()}), nil
}
func (a *accessAPI) putPolicy(ctx context.Context, in *policyInput) (*httpapi.Reply[policyVersionBody], error) {
value, err := a.scoped(ctx, in.Body)
if err != nil {
return nil, err
}
if err := NewEngine(nil).Validate(value); err != nil {
return nil, a.failed(ctx, "save the policy", err)
}
version, err := a.policies.PutPolicy(ctx, value)
if err != nil {
return nil, a.failed(ctx, "save the policy", err)
}
return httpapi.OK(policyVersionBody{Version: version}), nil
}
func (a *accessAPI) deletePolicy(ctx context.Context, in *policyInput) (*struct{}, error) {
value, err := a.scoped(ctx, in.Body)
if err != nil {
return nil, err
}
if IsShippedPolicy(value) {
return nil, a.failed(ctx, "delete the policy", ErrPolicyShipped)
}
if err := a.policies.DeletePolicy(ctx, value); err != nil {
return nil, a.failed(ctx, "delete the policy", err)
}
return nil, nil
}
// scoped pins a policy to the caller's organisation, since no request field
// chooses where a policy applies. Instance policies span every organisation, so
// only an instance administrator edits them.
func (a *accessAPI) scoped(ctx context.Context, value Policy) (Policy, error) {
p, err := caller(ctx)
if err != nil {
return Policy{}, err
}
if value.Level == LevelInstance {
if !p.InstanceAdmin() {
return Policy{}, huma.Error403Forbidden("Only an instance owner can change instance policies.")
}
value.OrgID, value.WorkspaceID, value.ObjectKind, value.ObjectID = "", "", "", ""
return value, nil
}
value.OrgID = p.Org
return value, nil
}
func (a *accessAPI) listDecisions(ctx context.Context, in *decisionsInput) (*httpapi.Reply[decisionsBody], error) {
p, err := caller(ctx)
if err != nil {
return nil, err
}
found, err := a.decisions.SearchDecisions(ctx, DecisionQuery{
Org: p.Org, Principal: IdentityID(in.Principal), Action: Action(in.Action), Kind: ResourceKind(in.Kind),
Outcome: Outcome(in.Outcome), Since: in.Since, Until: in.Until, Limit: in.Limit + 1, Offset: in.Offset,
})
if err != nil {
return nil, a.failed(ctx, "read the decisions", err)
}
more := len(found) > in.Limit
return httpapi.OK(decisionsBody{Decisions: found[:min(len(found), in.Limit)], More: more}), nil
}
// failed answers a policy failure with the status a person can act on: the
// Cedar error for a policy that does not compile, a conflict for a change that
// would lock every owner out.
func (a *accessAPI) failed(ctx context.Context, what string, err error) error {
switch {
case errors.Is(err, ErrPolicyLockout):
return huma.Error409Conflict("That change would leave no owner able to manage policies.")
case errors.Is(err, ErrPolicyShipped):
return huma.Error409Conflict("Shipped policies can't be deleted. Edit the policy instead.")
case errors.Is(err, ErrPolicyNotFound):
return huma.Error404NotFound("That policy does not exist.")
case errors.Is(err, ErrInvalidPolicy), errors.Is(err, ErrInvalidLevel), errors.Is(err, ErrPolicyInvalidText):
return huma.Error400BadRequest(err.Error())
}
a.log.ErrorContext(ctx, "access operation failed", "operation", what, "err", err)
return huma.Error503ServiceUnavailable("Couldn't " + what + ". Try again shortly.")
}