feat(access): policy schema, actions, request assembly and Authorizer contract (archie-core-qc8p)

This commit is contained in:
sam committed 2026-09-26 15:22:01 +10:00
1 parent e552de6ec3
commit 219301a88e
7 files changed
+712 -3

No files matched your search

+3 -3
View File
@@ -57,8 +57,6 @@ require (
github.com/nats-io/jwt/v2 v2.8.2 // indirect
github.com/nats-io/nkeys v0.4.16 // indirect
github.com/nats-io/nuid v1.0.1 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect
github.com/pjbgf/sha1cd v0.6.0 // indirect
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0 // indirect
@@ -90,7 +88,6 @@ require (
google.golang.org/genproto/googleapis/rpc v0.0.0-20260921155816-b14227669459 // indirect
modernc.org/libc v1.77.1 // indirect
modernc.org/sqlite v1.59.0 // indirect
oras.land/oras-go/v2 v2.6.2 // indirect
)
require (
@@ -111,6 +108,8 @@ require (
github.com/modelcontextprotocol/go-sdk v1.8.0
github.com/nats-io/nats-server/v2 v2.15.0
github.com/nats-io/nats.go v1.54.0
github.com/opencontainers/go-digest v1.0.0
github.com/opencontainers/image-spec v1.1.1
github.com/pressly/goose/v3 v3.28.0
github.com/samcharles93/ai-sdk v0.1.39
github.com/testcontainers/testcontainers-go v0.44.0
@@ -125,4 +124,5 @@ require (
google.golang.org/grpc v1.85.0-dev.0.20260825072537-93e31b48545e
google.golang.org/protobuf v1.36.12
gopkg.in/yaml.v3 v3.0.1
oras.land/oras-go/v2 v2.6.2
)
+193
View File
@@ -0,0 +1,193 @@
// Package access owns the policy schema, the action vocabulary, how
// principals and resources are turned into policy entities, and the
// Authorizer contract (docs/prds/orgs-and-access.md).
//
// The policy chain is
//
// instance ─▶ org ─▶ workspace ─▶ identity + workflow ─▶ object
//
// and the Cedar implementation lives in internal/infrastructure/access;
// internal/app wires it. Exactly two places call the Authorizer: the
// dashboard and API request path, and dispatch. Every other service verifies
// a credential and never evaluates policy.
//
// The chain's "identity + workflow" level is expressed with object policies:
// an identity or a workflow is one of the objects a policy can attach to
// (event source, secret, identity, binding, workflow), so the stored levels
// are instance, org, workspace and object.
package access
import (
"errors"
"fmt"
"slices"
"strings"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// Level is one level of the policy chain. A level's policies govern the
// requests the levels below it see: a lower level narrows and never widens.
type Level string
const (
// LevelInstance holds across every org. The shipped cross-org forbid
// lives here and cannot be removed.
LevelInstance Level = "instance"
// LevelOrg is an org's policies, including the shipped role policies.
LevelOrg Level = "org"
// LevelWorkspace is one workspace's stored policies.
LevelWorkspace Level = "workspace"
// LevelObject attaches to one object: an event source, a secret, an
// identity, a binding, a workflow.
LevelObject Level = "object"
)
// Validate reports whether l is one of the stored levels.
func (l Level) Validate() error {
switch l {
case LevelInstance, LevelOrg, LevelWorkspace, LevelObject:
return nil
}
return fmt.Errorf("%w: %q", ErrInvalidLevel, l)
}
// Action is the access vocabulary: what a principal may do to a resource.
type Action string
const (
ActionRead Action = "read"
ActionCreate Action = "create"
ActionUpdate Action = "update"
ActionDelete Action = "delete"
ActionApprove Action = "approve"
ActionRun Action = "run"
ActionReadLogs Action = "read_logs"
ActionReadSecret Action = "read_secret"
ActionManageMembers Action = "manage_members"
ActionManageIdentities Action = "manage_identities"
ActionManagePolicies Action = "manage_policies"
)
// Actions is every action, in vocabulary order. The engine and the shipped
// role policies iterate it.
func Actions() []Action {
return []Action{
ActionRead, ActionCreate, ActionUpdate, ActionDelete, ActionApprove,
ActionRun, ActionReadLogs, ActionReadSecret,
ActionManageMembers, ActionManageIdentities, ActionManagePolicies,
}
}
// Validate reports whether a is one of the shipped actions.
func (a Action) Validate() error {
if slices.Contains(Actions(), a) {
return nil
}
return fmt.Errorf("%w: %q", ErrInvalidAction, a)
}
// ResourceKind is what a resource record is. The kind is the object a policy
// names and the vocabulary the dashboard's API path derives actions from.
type ResourceKind string
const (
KindOrg ResourceKind = "org"
KindWorkspace ResourceKind = "workspace"
KindSource ResourceKind = "source"
KindEventType ResourceKind = "event_type"
KindMapping ResourceKind = "mapping"
KindBinding ResourceKind = "binding"
KindWorkflow ResourceKind = "workflow"
KindTask ResourceKind = "task"
KindCapture ResourceKind = "capture"
KindSecret ResourceKind = "secret"
KindIdentity ResourceKind = "identity"
KindPolicy ResourceKind = "policy"
KindMember ResourceKind = "member"
KindDashboard ResourceKind = "dashboard"
KindEventIngest ResourceKind = "event"
)
// Policy is one stored policy document. Its Text is Cedar policy language
// (one policy: an effect, a principal/action/resource scope and conditions).
//
// The scope fields say where the policy attaches. LevelInstance policies
// carry none; LevelOrg carries OrgID; LevelWorkspace adds WorkspaceID;
// LevelObject adds ObjectKind and ObjectID.
type Policy struct {
ID string `json:"id"`
Level Level `json:"level"`
OrgID org.OrgID `json:"org_id,omitempty"`
WorkspaceID org.WorkspaceID `json:"workspace_id,omitempty"`
ObjectKind ResourceKind `json:"object_kind,omitempty"`
ObjectID string `json:"object_id,omitempty"`
Text string `json:"text"`
}
// Validate checks a policy's shape: a level-appropriate scope, a non-empty
// text and a non-empty ID. The text's Cedar syntax is checked by the engine
// (the Validator contract); this check is structural, so the store and the
// reset path can reject a malformed document without an engine.
func (p Policy) Validate() error {
if strings.TrimSpace(p.ID) == "" {
return fmt.Errorf("%w: no ID", ErrInvalidPolicy)
}
if err := p.Level.Validate(); err != nil {
return err
}
switch p.Level {
case LevelInstance:
case LevelOrg:
if p.OrgID == "" {
return fmt.Errorf("%w: org policy carries no org", ErrInvalidPolicy)
}
case LevelWorkspace:
if p.OrgID == "" || p.WorkspaceID == "" {
return fmt.Errorf("%w: workspace policy carries no org or workspace", ErrInvalidPolicy)
}
case LevelObject:
if p.OrgID == "" || p.WorkspaceID == "" || p.ObjectKind == "" || p.ObjectID == "" {
return fmt.Errorf("%w: object policy carries no org, workspace, kind or ID", ErrInvalidPolicy)
}
}
if strings.TrimSpace(p.Text) == "" {
return fmt.Errorf("%w: no text", ErrInvalidPolicy)
}
return nil
}
// Governs reports whether the policy attaches to the level and scope of the
// given resource. An instance policy governs everything; an org policy
// governs the resources of its org; a workspace policy its workspace; an
// object policy the one record it names.
func (p Policy) Governs(r Resource) bool {
if p.Level != LevelInstance && p.OrgID != r.Org {
return false
}
switch p.Level {
case LevelWorkspace, LevelObject:
if p.WorkspaceID != r.Workspace {
return false
}
}
if p.Level == LevelObject && (p.ObjectKind != r.Kind || p.ObjectID != r.ID) {
return false
}
return true
}
// Sentinel errors. The message strings are part of the store's wire
// contract: staterpc's mapError/unmapError matches them by (code, canonical
// message), so they must never change.
var (
ErrInvalidLevel = errors.New("access: invalid level")
ErrInvalidAction = errors.New("access: invalid action")
ErrInvalidPolicy = errors.New("access: invalid policy")
// ErrPolicyNotFound is returned when a policy ID does not exist.
ErrPolicyNotFound = errors.New("access: policy not found")
// ErrPolicyInvalidText is returned when a policy's text does not parse.
ErrPolicyInvalidText = errors.New("access: policy text does not parse")
)
+197
View File
@@ -0,0 +1,197 @@
package access
import (
"errors"
"testing"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
)
func TestPolicyValidate(t *testing.T) {
tests := []struct {
name string
policy Policy
wantErr error
}{
{
name: "instance policy with no scope",
policy: Policy{ID: "p1", Level: LevelInstance, Text: "permit(principal, action, resource);"},
},
{
name: "instance policy without text",
policy: Policy{ID: "p1", Level: LevelInstance},
wantErr: ErrInvalidPolicy,
},
{
name: "org policy without org",
policy: Policy{ID: "p1", Level: LevelOrg, Text: "permit(principal, action, resource);"},
wantErr: ErrInvalidPolicy,
},
{
name: "workspace policy without workspace",
policy: Policy{ID: "p1", Level: LevelWorkspace, OrgID: "acme", Text: "permit(principal, action, resource);"},
wantErr: ErrInvalidPolicy,
},
{
name: "object policy with full scope",
policy: Policy{
ID: "p1", Level: LevelObject, OrgID: "acme", WorkspaceID: "net",
ObjectKind: KindSecret, ObjectID: "firewall-api",
Text: "forbid(principal, action == Archie::Action::\"read_secret\", resource);",
},
},
{
name: "object policy without kind",
policy: Policy{ID: "p1", Level: LevelObject, OrgID: "acme", WorkspaceID: "net", ObjectID: "firewall-api", Text: "forbid(principal, action, resource);"},
wantErr: ErrInvalidPolicy,
},
{
name: "unknown level",
policy: Policy{ID: "p1", Level: "galaxy", Text: "permit(principal, action, resource);"},
wantErr: ErrInvalidLevel,
},
{
name: "no ID",
policy: Policy{Level: LevelInstance, Text: "permit(principal, action, resource);"},
wantErr: ErrInvalidPolicy,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.policy.Validate()
if tt.wantErr == nil {
if err != nil {
t.Fatalf("Validate() = %v, want nil", err)
}
return
}
if !errors.Is(err, tt.wantErr) {
t.Fatalf("Validate() = %v, want %v", err, tt.wantErr)
}
})
}
}
func TestPolicyGoverns(t *testing.T) {
res := Resource{Kind: KindBinding, ID: "b1", Org: "acme", Workspace: "net"}
tests := []struct {
name string
policy Policy
want bool
}{
{
name: "instance governs everything",
policy: Policy{Level: LevelInstance},
want: true,
},
{
name: "org policy for the same org",
policy: Policy{Level: LevelOrg, OrgID: "acme"},
want: true,
},
{
name: "org policy for another org never governs",
policy: Policy{Level: LevelOrg, OrgID: "other"},
want: false,
},
{
name: "workspace policy for the resource's workspace",
policy: Policy{Level: LevelWorkspace, OrgID: "acme", WorkspaceID: "net"},
want: true,
},
{
name: "workspace policy for another workspace",
policy: Policy{Level: LevelWorkspace, OrgID: "acme", WorkspaceID: "desk"},
want: false,
},
{
name: "object policy for the same object",
policy: Policy{Level: LevelObject, OrgID: "acme", WorkspaceID: "net", ObjectKind: KindBinding, ObjectID: "b1"},
want: true,
},
{
name: "object policy for another object",
policy: Policy{Level: LevelObject, OrgID: "acme", WorkspaceID: "net", ObjectKind: KindBinding, ObjectID: "b2"},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.policy.Governs(res); got != tt.want {
t.Fatalf("Governs() = %v, want %v", got, tt.want)
}
})
}
}
func TestPrincipalRole(t *testing.T) {
id := identity.IdentityID("11111111-1111-5111-8111-111111111111")
p := Principal{
IdentityID: id,
Org: "acme",
Memberships: []org.Membership{
{IdentityID: id, OrgID: "acme", Role: org.RoleDeveloper},
{IdentityID: id, OrgID: "acme", WorkspaceID: "net", Role: org.RoleViewer},
{IdentityID: id, OrgID: "other", Role: org.RoleOwner}, // not this org's
},
}
tests := []struct {
name string
ws org.WorkspaceID
want org.Role
}{
{name: "workspace membership wins", ws: "net", want: org.RoleViewer},
{name: "org-wide role otherwise", ws: "desk", want: org.RoleDeveloper},
{name: "org-wide role with no workspace", ws: "", want: org.RoleDeveloper},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := p.Role(tt.ws); got != tt.want {
t.Fatalf("Role(%q) = %q, want %q", tt.ws, got, tt.want)
}
})
}
noRole := Principal{IdentityID: id, Org: "acme"}
if got := noRole.Role("net"); got != "" {
t.Fatalf("roleless principal Role() = %q, want empty", got)
}
}
func TestActionValidate(t *testing.T) {
for _, a := range Actions() {
if err := a.Validate(); err != nil {
t.Fatalf("Action(%q).Validate() = %v, want nil", a, err)
}
}
if err := Action("reboot").Validate(); !errors.Is(err, ErrInvalidAction) {
t.Fatalf("unknown action Validate() = %v, want ErrInvalidAction", err)
}
}
func TestShippedOrgPolicies(t *testing.T) {
policies := ShippedOrgPolicies("acme")
if len(policies) != 4 {
t.Fatalf("len(ShippedOrgPolicies) = %d, want 4", len(policies))
}
for _, p := range policies {
if p.Level != LevelOrg || p.OrgID != "acme" {
t.Fatalf("%s: level %q org %q, want org-level policy for acme", p.ID, p.Level, p.OrgID)
}
if err := p.Validate(); err != nil {
t.Fatalf("%s: Validate() = %v, want nil", p.ID, err)
}
}
ids := make(map[string]bool, len(policies))
for _, p := range policies {
ids[p.ID] = true
}
for _, want := range []string{PolicyOrgRead, PolicyOrgEdit, PolicyOrgAdmin, PolicyOrgOwner} {
if !ids[want] {
t.Fatalf("ShippedOrgPolicies missing %q", want)
}
}
}
+39
View File
@@ -0,0 +1,39 @@
// The contracts callers depend on: the Authorizer the dashboard/API path and
// dispatch call, the Validator policy changes are checked against, and the
// policy source the engine is built from.
package access
import "context"
// Authorizer evaluates the policy chain for one request. Exactly two places
// call it (docs/prds/orgs-and-access.md, "Where it lives"): the dashboard and
// API request path, and dispatch. The implementation is the Cedar engine in
// internal/infrastructure/access.
//
// Authorize never fails open: a stored policy the engine cannot parse makes
// its level deny everything and the decision carries the error; an invalid
// instance policy is a boot failure, not a denial the request path sees.
type Authorizer interface {
// Authorize evaluates instance, org, workspace and object policies for
// the request. A request is allowed only if every level with policies
// for it permits it; a forbid at any level wins; with no permit the
// request is denied.
Authorize(p Principal, a Action, r Resource, c Context) Decision
}
// Validator checks one policy against the current schema: Cedar syntax plus
// the entity vocabulary this package defines. A policy naming an unknown
// entity type, action or attribute is refused. Every stored policy is
// checked again when archie starts (the engine's construction reports the
// invalid ones).
type Validator interface {
Validate(p Policy) error
}
// PolicySource hands the engine its snapshot. The State Store owns the
// stored policies; a process loads them once at boot (a policy change takes
// effect when the process reloads, which the policy-editing surface ships
// with its own refresh).
type PolicySource interface {
Policies(ctx context.Context) ([]Policy, error)
}
+146
View File
@@ -0,0 +1,146 @@
// The entities a decision is made about. The domain owns their shape and the
// Cedar vocabulary they are built from (the schema); the engine in
// internal/infrastructure/access turns them into engine entities. This file
// carries no Cedar dependency: the vocabulary is plain constants so the
// domain never links the engine.
package access
import (
"time"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// The Cedar vocabulary every policy and every assembled entity shares. A
// policy naming an unknown type, action or attribute is refused when it is
// saved and denied at every start (the engine's validation).
const (
// Namespace prefixes every Cedar entity type the engine assembles.
Namespace = "Archie"
// EntityTypeIdentity is the principal: an Archie identity.
EntityTypeIdentity = Namespace + "::Identity"
// EntityTypeOrg is the org a resource belongs to.
EntityTypeOrg = Namespace + "::Org"
// EntityTypeWorkspace is the workspace a resource belongs to.
EntityTypeWorkspace = Namespace + "::Workspace"
// EntityTypeObject is the resource acted on. Every record -- source,
// binding, workflow, secret, task, the org itself -- is one Object
// entity carrying its kind, so a policy can scope on
// `resource.kind == Archie::Kind::"binding"` without a type per record.
EntityTypeObject = Namespace + "::Object"
// EntityTypeAction is the action entity of a request, one per Action.
EntityTypeAction = Namespace + "::Action"
// AttributeOrg is the org ID an identity or object carries.
AttributeOrg = "org"
// AttributeRole is the principal's effective role for the resource
// (workspace membership role when one exists, else its org-wide role).
AttributeRole = "role"
// AttributeKind is an object's resource kind.
AttributeKind = "kind"
// AttributeOwner is the ID of the identity that owns an object.
AttributeOwner = "owner"
// AttributeState is an object's state (binding's draft/armed, task's
// status, and so on), as the caller that assembles the request sees it.
AttributeState = "state"
)
// Principal is who acts: an identity, with the memberships that give it
// roles. The org is the one the identity serves (org.Repository's
// OrgForIdentity); Memberships carries its org-wide and workspace roles.
type Principal struct {
IdentityID identity.IdentityID
Kind identity.Kind
Org org.OrgID
Memberships []org.Membership
}
// Role returns the principal's effective role for a resource: the role of
// its membership in the resource's workspace when it holds one, else the
// role of its org-wide membership, else the empty string (no role, which
// the shipped role policies never permit).
func (p Principal) Role(ws org.WorkspaceID) org.Role {
var orgRole org.Role
for _, m := range p.Memberships {
if m.OrgID != p.Org {
continue
}
if m.WorkspaceID == "" {
orgRole = m.Role
}
if m.WorkspaceID == ws {
return m.Role
}
}
return orgRole
}
// Resource is the record acted on: its type, its workspace and org as
// parents, its owner and its state.
type Resource struct {
Kind ResourceKind
// ID is the record's caller-facing key: a source's path, a binding's
// ID, an org's ID, a workflow's name.
ID string
// Org is the org the record belongs to. Empty means the principal's own
// org, which is how a create request names a resource that does not
// exist yet.
Org org.OrgID
// Workspace is the workspace the record belongs to, empty for
// org-owned records.
Workspace org.WorkspaceID
Owner identity.IdentityID
State string
}
// Context is what was going on when the decision was asked for.
type Context struct {
// Signature is the event's signature result ("valid", "unsigned", ...).
Signature string
// Addr is the address the event came from.
Addr string
// Time is when the request was made; zero means now.
Time time.Time
// Run and Step identify the run and step when the principal is an agent.
Run string
Step string
}
// Decision is the outcome of one Authorize call. When the request is denied,
// Level names the level that decided and Policies the IDs of the deciding
// policies at that level, so a denial record can name them.
type Decision struct {
Allowed bool
Level Level
Policies []string
// Err carries the engine failure behind a deny-all level: a stored
// policy that no longer parses. A denied request with Err set was never
// evaluated -- the level refuses everything rather than decide.
Err error
}
// Allowed is the shared permit decision: no level denied.
func Allowed() Decision { return Decision{Allowed: true} }
// DeniedAt records a denial decided at a level by the given policies.
func DeniedAt(level Level, policies []string) Decision {
return Decision{Level: level, Policies: policies}
}
// Denial is one recorded refusal: who was refused, doing what, to what, by
// which level and which policies (docs/prds/orgs-and-access.md, "Denials").
type Denial struct {
Principal identity.IdentityID `json:"principal"`
Org org.OrgID `json:"org"`
Action Action `json:"action"`
Kind ResourceKind `json:"kind"`
ResourceID string `json:"resource"`
Level Level `json:"level"`
Policies []string `json:"policies"`
At time.Time `json:"at"`
// Count is how many identical denials this record stands for. The store
// coalesces identical denials within a minute into one row with a count.
Count int64 `json:"count"`
}
+81
View File
@@ -0,0 +1,81 @@
// The shipped policies: the four org roles every org carries, and the
// cross-org forbid the engine always enforces
// (docs/prds/orgs-and-access.md, "The policy chain" and "Roles").
//
// The role policies are Cedar policy text because that is what the engine
// evaluates. They live in the domain so the store seeds them, the reset
// command restores them, and the engine ships the same words regardless of
// which process builds it.
package access
import "github.com/samcharles93/archie-core/internal/domain/org"
// Role names as the shipped role policies test them: org.Role's lowercase
// vocabulary, carried in the principal's `role` attribute.
const (
roleOwner string = string(org.RoleOwner)
roleAdmin string = string(org.RoleAdmin)
roleDeveloper string = string(org.RoleDeveloper)
roleViewer string = string(org.RoleViewer)
)
// Shipped policy IDs. A stored policy must not reuse one: the store's
// seeding and the reset command overwrite these IDs with the shipped text.
const (
PolicyOrgRead = "org-role-read"
PolicyOrgEdit = "org-role-edit"
PolicyOrgAdmin = "org-role-admin"
PolicyOrgOwner = "org-role-owner"
PolicyCrossOrgID = "instance-cross-org"
)
// orgReadPolicy is every role's floor: read everything in the org, and its
// logs, but not a secret's value.
const orgReadPolicy = `permit(principal, action, resource) when
resource.org == principal.org &&
principal.role in ["` + roleViewer + `", "` + roleDeveloper + `", "` + roleAdmin + `", "` + roleOwner + `"] &&
action in [Archie::Action::"read", Archie::Action::"read_logs"];`
// orgEditPolicy is a developer's grant: create and edit workspace resources
// and org workflows, and run them.
const orgEditPolicy = `permit(principal, action, resource) when
resource.org == principal.org &&
principal.role in ["` + roleDeveloper + `", "` + roleAdmin + `", "` + roleOwner + `"] &&
action in [Archie::Action::"create", Archie::Action::"update", Archie::Action::"run"];`
// orgAdminPolicy is an admin's grant: approve, secret values, member and
// identity management, policy management, and deletion of every record that
// is not the org itself.
const orgAdminPolicy = `permit(principal, action, resource) when
resource.org == principal.org &&
principal.role in ["` + roleAdmin + `", "` + roleOwner + `"] &&
(action != Archie::Action::"delete" || resource.kind != "org");`
// orgOwnerPolicy is the owner's grant: everything in the org, including
// deleting it.
const orgOwnerPolicy = `permit(principal, action, resource) when
resource.org == principal.org &&
principal.role == "` + roleOwner + `";`
// ShippedOrgPolicies returns the four shipped role policies for one org, as
// the store seeds them and `archied access reset --org` restores them.
func ShippedOrgPolicies(orgID org.OrgID) []Policy {
return []Policy{
{ID: PolicyOrgRead, Level: LevelOrg, OrgID: orgID, Text: orgReadPolicy},
{ID: PolicyOrgEdit, Level: LevelOrg, OrgID: orgID, Text: orgEditPolicy},
{ID: PolicyOrgAdmin, Level: LevelOrg, OrgID: orgID, Text: orgAdminPolicy},
{ID: PolicyOrgOwner, Level: LevelOrg, OrgID: orgID, Text: orgOwnerPolicy},
}
}
// CrossOrgForbidID is the ID the shipped cross-org forbid is known by in
// denial records. The forbid is engine-enforced, never stored, so it cannot
// be edited away or removed by `archied access reset --instance`.
const CrossOrgForbidID = PolicyCrossOrgID
// The cross-org forbid's semantics, carried as text for the policy surface
// and the reset command's audit trail. The engine enforces it structurally
// (a principal never reaches a resource outside its org) before any Cedar
// runs, which is what makes it non-removable.
const CrossOrgForbidText = `forbid(principal, action, resource)
when resource.org != principal.org;`
+53
View File
@@ -0,0 +1,53 @@
// The persistence contracts for policies and denial records. The State Store
// implements them (internal/infrastructure/postgres); composition wires them
// like org.Repository.
package access
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// PolicyStore persists stored policies. Versioned per level: PutPolicy
// returns the level's new version, so a policy change is one version bump
// the engine's next load can detect. Every change is an audit event naming
// who made it.
type PolicyStore interface {
// ListPolicies returns every stored policy across levels.
ListPolicies(ctx context.Context) ([]Policy, error)
// PutPolicy stores or replaces one policy by its (level, scope, ID)
// key, and returns the level's new version.
PutPolicy(ctx context.Context, p Policy) (int64, error)
// DeletePolicy removes one stored policy; an unknown key is
// ErrPolicyNotFound.
DeletePolicy(ctx context.Context, p Policy) error
// EnsureShippedOrgPolicies seeds an org's shipped role policies when it
// has none; an org that already carries them is left untouched, so a
// restart never overwrites an edited role policy.
EnsureShippedOrgPolicies(ctx context.Context, orgID org.OrgID) error
}
// Resetter restores access for a locked-out org or a broken instance policy
// (docs/prds/orgs-and-access.md, "Recovering from a locked-out org"). It
// runs only on the State Store host, never over the network, and the reset
// command records it as an audit event.
type Resetter interface {
// ResetOrgPolicies restores the shipped role policies for one org and
// removes its other org-level policies.
ResetOrgPolicies(ctx context.Context, orgID org.OrgID) error
// ResetInstancePolicies removes every stored instance policy. The
// cross-org forbid is engine-enforced and survives any reset.
ResetInstancePolicies(ctx context.Context) error
}
// DenialStore records and lists denial records. The store coalesces
// identical denials within a minute into one row with a count, so a retry
// storm does not flood the surface.
type DenialStore interface {
// RecordDenial records one refusal with the level that decided it and
// the deciding policies.
RecordDenial(ctx context.Context, d Denial) error
// ListDenials returns an org's most recent denials, newest first.
ListDenials(ctx context.Context, orgID org.OrgID, limit int) ([]Denial, error)
}