Files
archie/internal/infrastructure/access/engine.go
T
sam 03b43fc07b Feat/org epic (#1634)
* fix(postgres): scope OpenPRs to the caller's org

A principal-carrying caller read every org's pr_open tasks. The query now
honours the request scope; the daemon's unscoped review scan still sees all
orgs.

Issue: archie-core-kgxw.23

* fix(statestore): serve task logs only to the task's org

ReadTaskLog and StreamTaskLogContent took a task ID and read the file with
no org check. The State Store's task-log reader now confirms the task is
visible under the caller's scope first; unscoped services read as before.

Issue: archie-core-kgxw.24

* fix(postgres): scope ListPolicies to the caller's org

Every org's policy text reached any principal-carrying caller. A scoped read
now sees its own org's policies, plus instance policies when scoped to the
system org. The engines and the lockout guard decide for every org, so they
read the full chain unscoped: the dashboard engine loads without the
request's principal and the guard lifts the caller's scope.

Issue: archie-core-kgxw.25

* fix(postgres): scope identity reads to the caller's org

ListIdentities and GetIdentity (and its alias fallback) returned every
identity to any caller. A caller scoped to an org now sees only that org's
members and assigned agents; the system org and unscoped services still see
the whole instance.

Issue: archie-core-kgxw.26

* fix(postgres): hide instance status from other orgs

ListPresence, ListChannelStatus, ListApplyStatus and GetConfigSnapshot
answered any org principal with instance-wide state. They now return nothing
unless the request is unscoped or scoped to the system org. The dashboard
reads the published config as itself, since its handlers project it for
callers of every org.

Issue: archie-core-kgxw.27

* feat(postgres): assign new agents an org and role at creation

A bot or service account created through the API served no org until the
next State Store boot granted it one. Create now assigns it to the org the
request acts in with the developer role in the same transaction, so it is
authorized immediately.

Issue: archie-core-kgxw.14

* feat(edastore): create event records in a chosen workspace

Sources are created in a workspace of the caller's org, the default one when
none is named; event types and bindings take their source's workspace and
mappings their event type's, the same rule the org backfill applied. The
binding, mapping and event type contracts carry the workspace, the four list
endpoints accept ?workspace=, and the Events page has a workspace selector
that filters every step and picks where a new source goes.

Issue: archie-core-kgxw.11

* feat(webui): authorize a record in its workspace

The API built every access request with no workspace, so workspace
policies and per-workspace roles never applied. A request naming a source,
binding, mapping, event type or task now reads the record's workspace under
the caller's scope and authorizes in it; tasks carry their workspace on the
State Store contract for this.

Issue: archie-core-kgxw.9

* feat(access): expose workspace environment to policies

Policies can test resource.workspace.environment. The workspace attribute
is the workspace entity, which carries its environment; the principal
brings its org's workspaces from the State Store, so the dashboard and the
daemon's run checks describe a resource's workspace without another lookup,
and the daemon now authorizes runs in the task's or binding's workspace.

Issue: archie-core-kgxw.10

* fix(webui): ask read_secret when a source secret is read

Rotating a source's secret returns its value, but the route asked update,
which every developer holds, so no policy could narrow who reads a secret.
It now asks read_secret on the secret, which the shipped roles give admins
and an object policy can narrow further.

Issue: archie-core-kgxw.17

* refactor(org): delete the unused upgrade-incomplete sentinel

Nothing returns org.ErrUpgradeIncomplete: the State Store finishes the org
upgrade before it serves.

Issue: archie-core-kgxw.18
2026-10-12 03:24:04 +11:00

298 lines
11 KiB
Go

// Package access implements the Authorizer with cedar-go. Levels are
// evaluated instance, org, workspace, object: a level with policies must
// permit and any forbid wins. Cross-org access is always denied.
package access
import (
"fmt"
cedar "github.com/cedar-policy/cedar-go"
"github.com/cedar-policy/cedar-go/types"
expast "github.com/cedar-policy/cedar-go/x/exp/ast"
schema "github.com/cedar-policy/cedar-go/x/exp/schema"
validate "github.com/cedar-policy/cedar-go/x/exp/schema/validate"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// schemaText is the Cedar schema policies are validated against.
const schemaText = `namespace Archie {
entity Identity in [Org] = {"org": String, "role": String};
entity Org;
entity Workspace in [Org] = {"org": String, "environment": String};
entity Object in [Org, Workspace] = {"org": String, "workspace": Workspace, "kind": String, "owner": String, "state": String};
action read appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} };
action create appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} };
action update appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} };
action delete appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} };
action approve appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} };
action run appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} };
action read_logs appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} };
action read_secret appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} };
action manage_members appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} };
action manage_identities appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} };
action deliver appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} };
action manage_policies appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} };
}`
// Problem is one stored policy the engine could not validate. It is what a
// health issue names: the policy and the error
type Problem struct {
Policy access.Policy
Err error
}
// levelSet is one chain level's parsed policies. invalid is non-nil when
// any of the level's policies failed to compile: the level then refuses
// every request and none of its policies is evaluated.
type levelSet struct {
at access.Level
ids []string
set *cedar.PolicySet
invalid error
}
// active reports whether the level carries policies at all: a level whose
// policies failed to compile is active too, because it refuses everything.
func (l *levelSet) active() bool { return l != nil && (len(l.ids) > 0 || l.invalid != nil) }
// Engine evaluates the chain. It is immutable after construction: a policy
// change rebuilds it from a fresh snapshot of the store.
type Engine struct {
instance *levelSet
orgs map[org.OrgID]*levelSet
spaces map[spaceKey]*levelSet
objects map[objectKey]*levelSet
problems []Problem
// pending marks the engine of a chain whose policies have not loaded:
// it refuses everything without evaluating.
pending bool
}
// pendingEngine refuses every request until the stored policies load.
var pendingEngine = &Engine{pending: true}
type (
spaceKey struct {
org org.OrgID
ws org.WorkspaceID
}
objectKey struct {
org org.OrgID
kind access.ResourceKind
id string
}
)
// The engine satisfies the domain contracts.
var (
_ access.Authorizer = (*Engine)(nil)
_ access.Validator = (*Engine)(nil)
)
// New builds an engine from the stored policies. An invalid policy makes its
// level deny everything and is reported as a Problem.
func New(policies []access.Policy) *Engine {
e := &Engine{
orgs: map[org.OrgID]*levelSet{},
spaces: map[spaceKey]*levelSet{},
objects: map[objectKey]*levelSet{},
}
for _, p := range policies {
lvl := e.level(p)
policy, err := compile(p)
if err != nil {
// The refusal must name the policy that poisoned the level.
lvl.ids = append(lvl.ids, p.ID)
lvl.invalid = err
e.problems = append(e.problems, Problem{Policy: p, Err: err})
continue
}
lvl.ids = append(lvl.ids, p.ID)
lvl.set.Add(types.PolicyID(p.ID), policy)
}
return e
}
// Ready reports whether the engine was built from stored policies.
func (e *Engine) Ready() bool { return !e.pending }
// Problems reports every stored policy the engine could not compile. Empty
// when every stored policy is valid.
func (e *Engine) Problems() []Problem { return e.problems }
// key locates the level set the policy belongs to, creating it on first use.
func (e *Engine) level(p access.Policy) *levelSet {
switch p.Level {
case access.LevelInstance:
if e.instance == nil {
e.instance = &levelSet{at: p.Level, set: cedar.NewPolicySet()}
}
return e.instance
case access.LevelOrg:
id := p.OrgID
if lvl, ok := e.orgs[id]; ok {
return lvl
}
lvl := &levelSet{at: p.Level, set: cedar.NewPolicySet()}
e.orgs[id] = lvl
return lvl
case access.LevelWorkspace:
id := spaceKey{p.OrgID, p.WorkspaceID}
if lvl, ok := e.spaces[id]; ok {
return lvl
}
lvl := &levelSet{at: p.Level, set: cedar.NewPolicySet()}
e.spaces[id] = lvl
return lvl
case access.LevelObject:
id := objectKey{p.OrgID, p.ObjectKind, p.ObjectID}
if lvl, ok := e.objects[id]; ok {
return lvl
}
lvl := &levelSet{at: p.Level, set: cedar.NewPolicySet()}
e.objects[id] = lvl
return lvl
}
return nil
}
// Validate checks one policy against the schema: the save-time check the
// domain's Validator contract requires, and the re-check every start of
// archie performs by rebuilding the engine from the store.
func (e *Engine) Validate(p access.Policy) error {
_, err := compile(p)
return err
}
// compile parses and validates one policy: structural shape, Cedar syntax,
// then the schema.
func compile(p access.Policy) (*cedar.Policy, error) {
if err := p.Validate(); err != nil {
return nil, err
}
pls, err := cedar.NewPolicyListFromBytes(p.ID, []byte(p.Text))
if err != nil {
return nil, fmt.Errorf("%w: %w", access.ErrPolicyInvalidText, err)
}
if len(pls) != 1 {
return nil, fmt.Errorf("%w: %s carries %d policies, want exactly one", access.ErrPolicyInvalidText, p.ID, len(pls))
}
v, err := schemaValidator()
if err != nil {
return nil, err
}
if err := v.Policy(p.ID, (*expast.Policy)(pls[0].AST())); err != nil {
return nil, fmt.Errorf("%w: %w", access.ErrPolicyInvalidText, err)
}
return pls[0], nil
}
// Authorize evaluates the chain for one request.
func (e *Engine) Authorize(p access.Principal, a access.Action, r access.Resource, c access.Context) access.Decision {
if e.pending {
return access.Unavailable()
}
// The cross-org forbid, enforced structurally: a principal's requests
// only ever reach its own org. An unset resource org means the
// principal's org (a create request names a record that does not exist
// yet); an org-less principal is denied everything.
resOrg := r.Org
if resOrg == "" {
resOrg = p.Org
}
if p.Org == "" || resOrg != p.Org {
return access.DeniedAt(access.LevelInstance, []string{access.CrossOrgForbidID})
}
return evaluate(e.chain(p, r), buildEntities(p, r), buildRequest(p, a, r, c))
}
// AuthorizeDelivery decides whether addr may deliver an event to a source:
// the instance network rules, then the source's own object policies. A
// sender has no identity or role, so the org and workspace role policies
// never apply to it.
func (e *Engine) AuthorizeDelivery(orgID org.OrgID, sourcePath, addr string) access.Decision {
if e.pending {
return access.Unavailable()
}
sender := access.Principal{IdentityID: access.SenderID, Org: orgID}
resource := access.Resource{Kind: access.KindSource, ID: sourcePath, Org: orgID}
levels := []*levelSet{e.instance}
if l, ok := e.objects[objectKey{orgID, access.KindSource, sourcePath}]; ok {
levels = append(levels, l)
}
return evaluate(levels, buildEntities(sender, resource), buildRequest(sender, access.ActionDeliver, resource, access.Context{Addr: addr}))
}
// evaluate runs a request through levels: a level with policies must permit
// and any forbid wins.
func evaluate(levels []*levelSet, entities types.EntityMap, request types.Request) access.Decision {
for _, lvl := range levels {
if !lvl.active() {
continue
}
if lvl.invalid != nil {
decision := access.DeniedAt(lvl.at, lvl.ids)
decision.Err = lvl.invalid
return decision
}
decision, diag := cedar.Authorize(lvl.set, entities, request)
if decision == cedar.Allow {
continue
}
ids := make([]string, 0, len(diag.Reasons))
for _, reason := range diag.Reasons {
ids = append(ids, string(reason.PolicyID))
}
if len(ids) == 0 {
// No permit at a level with policies: the level denied by
// default, not through any one policy. Name the level's
// policies so the denial record still says what stood between
// the principal and the record.
ids = lvl.ids
}
return access.DeniedAt(lvl.at, ids)
}
return access.Allowed()
}
// chain returns the level sets the request passes through, in order. An
// invalid instance level refuses everything except an instance admin working
// on the policies, so the operator can repair it from the dashboard.
func (e *Engine) chain(p access.Principal, r access.Resource) []*levelSet {
var out []*levelSet
if e.instance == nil || e.instance.invalid == nil || r.Kind != access.KindPolicy || !p.InstanceAdmin() {
out = append(out, e.instance)
}
if l, ok := e.orgs[r.Org]; ok {
out = append(out, l)
}
if r.Workspace != "" {
if l, ok := e.spaces[spaceKey{r.Org, r.Workspace}]; ok {
out = append(out, l)
}
}
if r.Org != "" && r.ID != "" {
if l, ok := e.objects[objectKey{r.Org, r.Kind, r.ID}]; ok {
out = append(out, l)
}
}
return out
}
// schemaValidator returns the resolved schema, building it once. The schema
// is part of the shipped vocabulary and cannot change at runtime.
func schemaValidator() (*validate.Validator, error) {
var sch schema.Schema
if err := sch.UnmarshalCedar([]byte(schemaText)); err != nil {
return nil, err
}
resolved, err := sch.Resolve()
if err != nil {
return nil, err
}
return validate.New(resolved), nil
}