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 } // denialSearch reads the recorded refusals. type denialSearch interface { SearchDenials(context.Context, DenialQuery) ([]Denial, error) } // accessAPI serves the access policies and the record of refused requests. type accessAPI struct { policies policyAdmin denials denialSearch log *slog.Logger } func (m *Module) access() *accessAPI { return &accessAPI{policies: m, denials: m, log: m.log} } type policiesBody struct { Policies []Policy `json:"policies"` Shipped []string `json:"shipped" doc:"IDs of the policies Archie ships, which a reset restores"` } type policyVersionBody struct { Version int64 `json:"version" doc:"The policy chain's new revision"` } type policyInput struct { Body Policy } type denialsInput struct { Principal string `query:"principal" doc:"Only refusals of this identity"` Action string `query:"action" doc:"Only refusals of this action"` Kind string `query:"kind" doc:"Only refusals on this resource kind"` Since time.Time `query:"since" doc:"Only refusals first recorded at or after this time"` Until time.Time `query:"until" doc:"Only refusals first recorded before this time"` Limit int `query:"limit" default:"100" minimum:"1" maximum:"1000" doc:"How many refusals to return"` Offset int `query:"offset" default:"0" minimum:"0" doc:"How many of the newest matching refusals to skip"` } type denialsBody struct { Denials []Denial `json:"denials"` More bool `json:"more" doc:"Whether older refusals 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) registerDenials(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-denials", http.MethodGet, "/api/access/denials", "List the requests access policies refused", 0), a.listDenials) } 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 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) listDenials(ctx context.Context, in *denialsInput) (*httpapi.Reply[denialsBody], error) { p, err := caller(ctx) if err != nil { return nil, err } found, err := a.denials.SearchDenials(ctx, DenialQuery{ Org: p.Org, Principal: IdentityID(in.Principal), Action: Action(in.Action), Kind: ResourceKind(in.Kind), Since: in.Since, Until: in.Until, Limit: in.Limit + 1, Offset: in.Offset, }) if err != nil { return nil, a.failed(ctx, "read the denials", err) } more := len(found) > in.Limit return httpapi.OK(denialsBody{Denials: 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, 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.") }