Merge crew/qc8p: archie-core-qc8p

This commit is contained in:
sam committed 2026-09-26 15:27:12 +10:00
commit affbcde47e
46 files changed
+5150 -243

No files matched your search

+280
View File
@@ -0,0 +1,280 @@
// Package access implements internal/domain/access's Authorizer with
// github.com/cedar-policy/cedar-go. The engine owns policy parsing and
// validation against the shipped Cedar schema, and the chain evaluation:
// instance ▶ org ▶ workspace ▶ object, where a level with policies must
// permit, a forbid at any level wins, and with no permit the request is
// denied (docs/prds/orgs-and-access.md).
//
// The cross-org forbid is enforced here, structurally, before any Cedar
// runs: a principal never reaches a resource outside its org. It is not a
// stored policy, so it cannot be edited away or removed by
// `archied access reset`.
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 the engine validates every policy against.
// It names the entity vocabulary internal/domain/access defines: an
// Identity principal carrying its org and effective role, the org and
// workspace parents, one Object entity per record, and one Action per
// action. Context carries the event's signature result, the address it came
// from, and the run and step of an agent's request.
const schemaText = `namespace Archie {
entity Identity in [Org] = {"org": String, "role": String};
entity Org;
entity Workspace in [Org] = {"org": String};
entity Object in [Org, Workspace] = {"org": String, "workspace": String, "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 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
// (docs/prds/orgs-and-access.md, "Storing and changing policies").
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
}
type (
spaceKey struct {
org org.OrgID
ws org.WorkspaceID
}
objectKey struct {
org org.OrgID
ws org.WorkspaceID
kind access.ResourceKind
id string
}
)
// The engine satisfies the domain contracts.
var (
_ access.Authorizer = (*Engine)(nil)
_ access.Validator = (*Engine)(nil)
)
// New builds an engine over one snapshot of the stored policies. An invalid
// instance policy is a boot failure: it returns (nil, err) and archie stops
// serving until the policy is fixed. An invalid org, workspace or object
// policy becomes a Problem and makes its level deny everything -- the other
// levels still serve, and the health surface reports the problem by name.
func New(policies []access.Policy) (*Engine, error) {
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 {
if p.Level == access.LevelInstance {
return nil, fmt.Errorf("access: instance policy %q: %w", p.ID, err)
}
// 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, nil
}
// 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.WorkspaceID, 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 {
// 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})
}
request := buildRequest(p, a, r, c)
entities := buildEntities(p, r)
for _, lvl := range e.chain(r) {
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.
func (e *Engine) chain(r access.Resource) []*levelSet {
out := []*levelSet{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.Workspace, 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
}
@@ -0,0 +1,250 @@
package access
import (
"errors"
"testing"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
)
const acme = "acme"
func principal(role org.Role) access.Principal {
return access.Principal{
IdentityID: identity.IdentityID("11111111-1111-5111-8111-111111111111"),
Kind: identity.KindUser,
Org: acme,
Memberships: []org.Membership{
{IdentityID: identity.IdentityID("11111111-1111-5111-8111-111111111111"), OrgID: acme, Role: role},
},
}
}
func resource(kind access.ResourceKind, id string) access.Resource {
return access.Resource{Kind: kind, ID: id, Org: acme, Workspace: "net"}
}
func newEngine(t *testing.T, policies ...access.Policy) *Engine {
t.Helper()
e, err := New(policies)
if err != nil {
t.Fatalf("New() = %v, want nil", err)
}
return e
}
func TestShippedRoleMatrix(t *testing.T) {
shipped := access.ShippedOrgPolicies(acme)
e := newEngine(t, shipped...)
tests := []struct {
name string
role org.Role
action access.Action
kind access.ResourceKind
id string
wantAllow bool
}{
// Viewer: read everything except secret values.
{name: "viewer reads a binding", role: org.RoleViewer, action: access.ActionRead, kind: access.KindBinding, id: "b1", wantAllow: true},
{name: "viewer reads logs", role: org.RoleViewer, action: access.ActionReadLogs, kind: access.KindTask, id: "1", wantAllow: true},
{name: "viewer cannot read a secret", role: org.RoleViewer, action: access.ActionReadSecret, kind: access.KindSecret, id: "firewall-api"},
{name: "viewer cannot create", role: org.RoleViewer, action: access.ActionCreate, kind: access.KindBinding, id: "b1"},
{name: "viewer cannot run", role: org.RoleViewer, action: access.ActionRun, kind: access.KindWorkflow, id: "implement"},
// Developer: create and edit, run, read logs -- no approve, no delete,
// no secret values.
{name: "developer creates a binding", role: org.RoleDeveloper, action: access.ActionCreate, kind: access.KindBinding, id: "b1", wantAllow: true},
{name: "developer edits a mapping", role: org.RoleDeveloper, action: access.ActionUpdate, kind: access.KindMapping, id: "m1", wantAllow: true},
{name: "developer runs a workflow", role: org.RoleDeveloper, action: access.ActionRun, kind: access.KindWorkflow, id: "implement", wantAllow: true},
{name: "developer cannot approve", role: org.RoleDeveloper, action: access.ActionApprove, kind: access.KindBinding, id: "b1"},
{name: "developer cannot delete", role: org.RoleDeveloper, action: access.ActionDelete, kind: access.KindBinding, id: "b1"},
{name: "developer cannot read a secret", role: org.RoleDeveloper, action: access.ActionReadSecret, kind: access.KindSecret, id: "firewall-api"},
{name: "developer cannot manage members", role: org.RoleDeveloper, action: access.ActionManageMembers, kind: access.KindMember, id: "u2"},
// Admin: everything except deleting the org.
{name: "admin approves a binding", role: org.RoleAdmin, action: access.ActionApprove, kind: access.KindBinding, id: "b1", wantAllow: true},
{name: "admin deletes a binding", role: org.RoleAdmin, action: access.ActionDelete, kind: access.KindBinding, id: "b1", wantAllow: true},
{name: "admin deletes the org is denied", role: org.RoleAdmin, action: access.ActionDelete, kind: access.KindOrg, id: acme},
{name: "admin reads a secret", role: org.RoleAdmin, action: access.ActionReadSecret, kind: access.KindSecret, id: "firewall-api", wantAllow: true},
{name: "admin manages policies", role: org.RoleAdmin, action: access.ActionManagePolicies, kind: access.KindPolicy, id: "p1", wantAllow: true},
// Owner: everything in the org, including deleting it.
{name: "owner deletes the org", role: org.RoleOwner, action: access.ActionDelete, kind: access.KindOrg, id: acme, wantAllow: true},
{name: "owner manages identities", role: org.RoleOwner, action: access.ActionManageIdentities, kind: access.KindIdentity, id: "u2", wantAllow: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := e.Authorize(principal(tt.role), tt.action, resource(tt.kind, tt.id), access.Context{})
if got.Allowed != tt.wantAllow {
t.Fatalf("Authorize(%s, %s, %s/%s) allowed=%v level=%v policies=%v, want allow=%v",
tt.role, tt.action, tt.kind, tt.id, got.Allowed, got.Level, got.Policies, tt.wantAllow)
}
})
}
}
func TestCrossOrgForbid(t *testing.T) {
e := newEngine(t, access.ShippedOrgPolicies(acme)...)
p := access.Principal{
IdentityID: identity.IdentityID("11111111-1111-5111-8111-111111111111"),
Org: acme,
Memberships: []org.Membership{
{IdentityID: identity.IdentityID("11111111-1111-5111-8111-111111111111"), OrgID: acme, Role: org.RoleOwner},
},
}
got := e.Authorize(p, access.ActionRead, access.Resource{Kind: access.KindBinding, ID: "b1", Org: "other", Workspace: "net"}, access.Context{})
if got.Allowed {
t.Fatal("owner read of another org's binding was allowed; the cross-org forbid must win")
}
if got.Level != access.LevelInstance || len(got.Policies) != 1 || got.Policies[0] != access.CrossOrgForbidID {
t.Fatalf("denial = level %v policies %v, want instance level with %q", got.Level, got.Policies, access.CrossOrgForbidID)
}
// An org-less principal is denied everything.
agentless := p
agentless.Org = ""
if got := e.Authorize(agentless, access.ActionRead, resource(access.KindBinding, "b1"), access.Context{}); got.Allowed {
t.Fatal("org-less principal was allowed")
}
// A create request with no resource org is the principal's own org.
create := resource(access.KindBinding, "b1")
create.Org = ""
if got := e.Authorize(principal(org.RoleDeveloper), access.ActionCreate, create, access.Context{}); !got.Allowed {
t.Fatalf("create in own org denied: level=%v policies=%v", got.Level, got.Policies)
}
}
func TestWorkspacePolicyCannotWidenOrg(t *testing.T) {
// The org forbids run where the workspace is production; a workspace
// policy permitting run has no effect.
orgPolicies := access.ShippedOrgPolicies(acme)
orgPolicies = append(orgPolicies, access.Policy{
ID: "org-no-run-production", Level: access.LevelOrg, OrgID: acme,
Text: `forbid(principal, action == Archie::Action::"run", resource) when { resource.workspace == "production" };`,
})
workspace := access.Policy{
ID: "ws-allow-run", Level: access.LevelWorkspace, OrgID: acme, WorkspaceID: "production",
Text: `permit(principal, action, resource) when { action == Archie::Action::"run" };`,
}
e := newEngine(t, append(orgPolicies, workspace)...)
r := resource(access.KindWorkflow, "implement")
r.Workspace = "production"
got := e.Authorize(principal(org.RoleDeveloper), access.ActionRun, r, access.Context{})
if got.Allowed {
t.Fatal("workspace policy widened an org forbid")
}
if got.Level != access.LevelOrg || got.Policies[0] != "org-no-run-production" {
t.Fatalf("denial decided at %v by %v, want the org policy", got.Level, got.Policies)
}
}
func TestObjectPolicyNarrows(t *testing.T) {
// Only one identity may read the firewall-api secret.
socID := identity.IdentityID("33333333-3333-5333-8333-333333333333")
object := access.Policy{
ID: "secret-soc-only", Level: access.LevelObject, OrgID: acme, WorkspaceID: "net",
ObjectKind: access.KindSecret, ObjectID: "firewall-api",
Text: `permit(principal, action == Archie::Action::"read_secret", resource) when {
principal == Archie::Identity::"` + string(socID) + `"
};`,
}
e := newEngine(t, append(access.ShippedOrgPolicies(acme), object)...)
// An admin would otherwise read it, but the object level narrows: the
// object policy has no permit for this principal, so the level denies.
admin := principal(org.RoleAdmin)
admin.IdentityID = identity.IdentityID("22222222-2222-5222-8222-222222222222")
got := e.Authorize(admin, access.ActionReadSecret, resource(access.KindSecret, "firewall-api"), access.Context{})
if got.Allowed {
t.Fatal("admin read a secret the object policy narrows away")
}
if got.Level != access.LevelObject {
t.Fatalf("denial decided at %v, want object level", got.Level)
}
soc := admin
soc.IdentityID = socID
if got := e.Authorize(soc, access.ActionReadSecret, resource(access.KindSecret, "firewall-api"), access.Context{}); !got.Allowed {
t.Fatalf("permitted identity denied: level=%v policies=%v", got.Level, got.Policies)
}
}
func TestInvalidPolicyDeniesItsLevel(t *testing.T) {
invalid := access.Policy{
ID: "broken-workspace", Level: access.LevelWorkspace, OrgID: acme, WorkspaceID: "net",
Text: `permit(principal, action, resource) when { principal.bogus == "x" };`,
}
e := newEngine(t, append(access.ShippedOrgPolicies(acme), invalid)...)
problems := e.Problems()
if len(problems) != 1 || problems[0].Policy.ID != "broken-workspace" {
t.Fatalf("Problems() = %+v, want one entry for broken-workspace", problems)
}
if !errors.Is(problems[0].Err, access.ErrPolicyInvalidText) {
t.Fatalf("problem err = %v, want ErrPolicyInvalidText", problems[0].Err)
}
// The workspace level denies everything, even what the org permits.
got := e.Authorize(principal(org.RoleOwner), access.ActionRead, resource(access.KindBinding, "b1"), access.Context{})
if got.Allowed || got.Level != access.LevelWorkspace {
t.Fatalf("level with an invalid policy did not refuse: %+v", got)
}
if !errors.Is(got.Err, access.ErrPolicyInvalidText) {
t.Fatalf("decision err = %v, want ErrPolicyInvalidText", got.Err)
}
// The denial record names the level's policies.
if len(got.Policies) == 0 || got.Policies[0] != "broken-workspace" {
t.Fatalf("refusal named %v, want the level's policy", got.Policies)
}
}
func TestInvalidInstancePolicyStopsServing(t *testing.T) {
if _, err := New([]access.Policy{
{ID: "broken-instance", Level: access.LevelInstance, Text: `permit(principal, action, resource) when { resource.nope == 1 };`},
}); err == nil {
t.Fatal("New() accepted an invalid instance policy; archie must stop serving")
}
}
func TestValidateRefusesUnknownVocabulary(t *testing.T) {
e := newEngine(t)
bad := access.Policy{ID: "p1", Level: access.LevelOrg, OrgID: acme, Text: `permit(principal, action, resource) when { resource.wat == "x" };`}
if err := e.Validate(bad); !errors.Is(err, access.ErrPolicyInvalidText) {
t.Fatalf("Validate(unknown attribute) = %v, want ErrPolicyInvalidText", err)
}
badText := access.Policy{ID: "p2", Level: access.LevelOrg, OrgID: acme, Text: `permit(principal, action, resource) when { principal.org == 42 };`}
if err := e.Validate(badText); !errors.Is(err, access.ErrPolicyInvalidText) {
t.Fatalf("Validate(type error) = %v, want ErrPolicyInvalidText", err)
}
multi := access.Policy{ID: "p3", Level: access.LevelOrg, OrgID: acme, Text: `permit(principal, action, resource); permit(principal, action, resource);`}
if err := e.Validate(multi); !errors.Is(err, access.ErrPolicyInvalidText) {
t.Fatalf("Validate(multiple policies) = %v, want ErrPolicyInvalidText", err)
}
}
func TestWorkspaceRoleNarrowsTheOrgRole(t *testing.T) {
// A developer org-wide, viewer in the net workspace: read-only there.
p := principal(org.RoleDeveloper)
p.Memberships = append(p.Memberships, org.Membership{IdentityID: p.IdentityID, OrgID: acme, WorkspaceID: "net", Role: org.RoleViewer})
e := newEngine(t, access.ShippedOrgPolicies(acme)...)
if got := e.Authorize(p, access.ActionRead, resource(access.KindBinding, "b1"), access.Context{}); !got.Allowed {
t.Fatalf("viewer-in-workspace denied a read: %+v", got)
}
if got := e.Authorize(p, access.ActionCreate, resource(access.KindBinding, "b1"), access.Context{}); got.Allowed {
t.Fatal("workspace viewer role did not narrow the org-wide developer role")
}
}
func TestDenialNamesDecidingPolicies(t *testing.T) {
e := newEngine(t, access.ShippedOrgPolicies(acme)...)
// A viewer denied create is decided by the org level, whose only
// policies are the shipped role set.
got := e.Authorize(principal(org.RoleViewer), access.ActionCreate, resource(access.KindBinding, "b1"), access.Context{})
if got.Level != access.LevelOrg {
t.Fatalf("level = %v, want org", got.Level)
}
for _, id := range got.Policies {
if id != access.PolicyOrgRead && id != access.PolicyOrgEdit && id != access.PolicyOrgAdmin && id != access.PolicyOrgOwner {
t.Fatalf("denial names an unknown policy %q", id)
}
}
}
+106
View File
@@ -0,0 +1,106 @@
// Entity assembly: the engine's view of internal/domain/access's Principal,
// Resource and Context. The vocabulary (entity types, attributes) is the
// domain's; the shape is what the shipped schema declares.
package access
import (
"time"
cedar "github.com/cedar-policy/cedar-go"
"github.com/cedar-policy/cedar-go/types"
"github.com/samcharles93/archie-core/internal/domain/access"
)
// buildRequest turns the assembled request into the engine's shape. The
// context record carries only the fields that were set: a policy testing a
// field the caller did not supply cannot match, which is the fail-closed
// reading of "context: the event's signature result, the address it came
// from, the time, and the run and step when the principal is an agent".
func buildRequest(p access.Principal, a access.Action, r access.Resource, c access.Context) types.Request {
record := types.RecordMap{}
if c.Signature != "" {
record["signature"] = types.String(c.Signature)
}
if c.Addr != "" {
if addr, err := types.ParseIPAddr(c.Addr); err == nil {
record["addr"] = addr
}
}
if c.Run != "" {
record["run"] = types.String(c.Run)
}
if c.Step != "" {
record["step"] = types.String(c.Step)
}
// The context always carries a time: the zero Time resolves to now.
at := c.Time
if at.IsZero() {
at = time.Now().UTC()
}
record["time"] = types.NewDatetime(at)
return types.Request{
Principal: types.NewEntityUID(access.EntityTypeIdentity, types.String(p.IdentityID)),
Action: types.NewEntityUID(access.EntityTypeAction, types.String(string(a))),
Resource: types.NewEntityUID(access.EntityTypeObject, types.String(r.ID)),
Context: types.NewRecord(record),
}
}
// buildEntities assembles the entity graph policies may walk: the principal
// (its org and effective role), the resource (its kind, org, workspace,
// owner and state), and the org and workspace parents the resource hangs
// from. A policy naming a parent the request does not supply simply does
// not match.
func buildEntities(p access.Principal, r access.Resource) cedar.EntityMap {
resOrg := r.Org
if resOrg == "" {
resOrg = p.Org
}
entities := cedar.EntityMap{}
orgUID := types.NewEntityUID(access.EntityTypeOrg, types.String(resOrg))
entities[orgUID] = cedar.Entity{UID: orgUID}
principalUID := types.NewEntityUID(access.EntityTypeIdentity, types.String(p.IdentityID))
entities[principalUID] = cedar.Entity{
UID: principalUID,
// The principal's parent chain is its org; a policy may write
// `principal in Archie::Org::"acme"`.
Parents: cedar.NewEntityUIDSet(orgUID),
Attributes: types.NewRecord(types.RecordMap{
"org": types.String(resOrg),
"role": types.String(string(p.Role(r.Workspace))),
}),
}
parents := []types.EntityUID{orgUID}
if r.Workspace != "" {
wsUID := types.NewEntityUID(access.EntityTypeWorkspace, types.String(r.Workspace))
entities[wsUID] = cedar.Entity{
UID: wsUID,
Parents: cedar.NewEntityUIDSet(orgUID),
Attributes: types.NewRecord(types.RecordMap{"org": types.String(resOrg)}),
}
parents = append(parents, wsUID)
}
resUID := types.NewEntityUID(access.EntityTypeObject, types.String(r.ID))
attrs := types.RecordMap{
"org": types.String(resOrg),
"workspace": types.String(string(r.Workspace)),
"kind": types.String(string(r.Kind)),
}
if r.Owner != "" {
attrs["owner"] = types.String(string(r.Owner))
}
if r.State != "" {
attrs["state"] = types.String(r.State)
}
entities[resUID] = cedar.Entity{
UID: resUID,
Parents: cedar.NewEntityUIDSet(parents...),
Attributes: types.NewRecord(attrs),
}
return entities
}
+239
View File
@@ -0,0 +1,239 @@
// Access policies and denial records: the Postgres implementation of
// internal/domain/access's PolicyStore, Resetter and DenialStore
// (docs/prds/orgs-and-access.md). Policy changes are versioned per level
// scope and audited as one sys_audit row per change naming who made it.
package postgres
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/jackc/pgx/v5"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
var (
_ access.PolicyStore = (*Store)(nil)
_ access.Resetter = (*Store)(nil)
_ access.DenialStore = (*Store)(nil)
)
// shippedOrgPolicyIDs lists an org's shipped role policy IDs: the seed's
// conflict keys, and what an org reset keeps.
func shippedOrgPolicyIDs() []string {
ids := make([]string, 0, 4)
for _, p := range access.ShippedOrgPolicies("") {
ids = append(ids, p.ID)
}
return ids
}
// accessScopeOf is the scope tuple every access query carries.
func accessScopeOf(p access.Policy) (string, string, string, string, string, string) {
return string(p.Level), string(p.OrgID), string(p.WorkspaceID),
string(p.ObjectKind), p.ObjectID, p.ID
}
// auditKey is the sys_audit record_key for one policy: its scope and ID, so
// an operator can trace one policy document's changes.
func auditKey(p access.Policy) string {
joined := strings.Join([]string{
string(p.Level), string(p.OrgID), string(p.WorkspaceID),
string(p.ObjectKind), p.ObjectID, p.ID,
}, "/")
return strings.Trim(joined, "/")
}
// textJSON wraps a policy text as the JSON string sys_audit stores.
func textJSON(text string) []byte {
out, _ := json.Marshal(text)
return out
}
// ListPolicies returns every stored policy across levels.
func (s *Store) ListPolicies(ctx context.Context) ([]access.Policy, error) {
rows, err := s.queries().ListAccessPolicies(ctx)
if err != nil {
return nil, err
}
out := make([]access.Policy, 0, len(rows))
for _, r := range rows {
out = append(out, access.Policy{
ID: r.PolicyID,
Level: access.Level(r.Level),
OrgID: org.OrgID(r.OrgID),
WorkspaceID: org.WorkspaceID(r.WorkspaceID),
ObjectKind: access.ResourceKind(r.ObjectKind),
ObjectID: r.ObjectID,
Text: r.Text,
})
}
return out, nil
}
// PutPolicy stores or replaces one policy by its scope+ID key, bumps the
// level's version, and writes the audit row -- in one transaction, so a
// version that never moved cannot advertise a change that half-landed.
func (s *Store) PutPolicy(ctx context.Context, p access.Policy) (int64, error) {
if err := p.Validate(); err != nil {
return 0, err
}
q := s.queries()
level, orgID, wsID, kind, id, policyID := accessScopeOf(p)
var version int64
err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
q := q.WithTx(tx)
if err := q.UpsertAccessPolicy(ctx, postgresdb.UpsertAccessPolicyParams{
Level: level, OrgID: orgID, WorkspaceID: wsID,
ObjectKind: kind, ObjectID: id,
PolicyID: policyID, Text: p.Text,
}); err != nil {
return err
}
v, err := q.UpsertAccessPolicyVersion(ctx, postgresdb.UpsertAccessPolicyVersionParams{
Level: level, OrgID: orgID, WorkspaceID: wsID,
})
if err != nil {
return err
}
version = v
return q.InsertAccessPolicyAudit(ctx, postgresdb.InsertAccessPolicyAuditParams{
RecordKey: auditKey(p),
NewValue: textJSON(p.Text),
RecordVersion: version,
Actor: "archied",
Source: "archied",
RequestID: "",
})
})
if err != nil {
return 0, err
}
return version, nil
}
// DeletePolicy removes one stored policy; an unknown key is
// ErrPolicyNotFound.
func (s *Store) DeletePolicy(ctx context.Context, p access.Policy) error {
if err := p.Validate(); err != nil {
return err
}
level, orgID, wsID, kind, id, policyID := accessScopeOf(p)
deleted, err := s.queries().DeleteAccessPolicy(ctx, postgresdb.DeleteAccessPolicyParams{
Level: level, OrgID: orgID, WorkspaceID: wsID,
ObjectKind: kind, ObjectID: id, PolicyID: policyID,
})
if err != nil {
return err
}
if deleted == 0 {
return access.ErrPolicyNotFound
}
if _, err := s.queries().UpsertAccessPolicyVersion(ctx, postgresdb.UpsertAccessPolicyVersionParams{
Level: level, OrgID: orgID, WorkspaceID: wsID,
}); err != nil {
return err
}
// A level-scope with no policies left keeps no version row.
return s.queries().DeleteAccessPolicyVersion(ctx, postgresdb.DeleteAccessPolicyVersionParams{
Level: level, OrgID: orgID, WorkspaceID: wsID,
})
}
// EnsureShippedOrgPolicies seeds an org's shipped role policies when it
// carries none of them, so a restart never overwrites an edited role policy.
func (s *Store) EnsureShippedOrgPolicies(ctx context.Context, orgID org.OrgID) error {
shipped := access.ShippedOrgPolicies(orgID)
count, err := s.queries().CountShippedOrgPolicies(ctx, postgresdb.CountShippedOrgPoliciesParams{
OrgID: string(orgID), Column2: shippedOrgPolicyIDs(),
})
if err != nil {
return err
}
if count > 0 {
return nil
}
for _, p := range shipped {
if _, err := s.PutPolicy(ctx, p); err != nil {
return err
}
}
return nil
}
// ResetOrgPolicies restores the shipped role policies for one org and
// removes its other org-level policies. It is the store-side half of
// `archied access reset --org`, which runs on this host and records the
// reset as an audit event.
func (s *Store) ResetOrgPolicies(ctx context.Context, orgID org.OrgID) error {
if orgID == "" {
return fmt.Errorf("%w: no org", access.ErrInvalidPolicy)
}
if err := s.queries().DeleteOrgPoliciesNotShipped(ctx, postgresdb.DeleteOrgPoliciesNotShippedParams{
OrgID: string(orgID), Column2: shippedOrgPolicyIDs(),
}); err != nil {
return err
}
for _, p := range access.ShippedOrgPolicies(orgID) {
if _, err := s.PutPolicy(ctx, p); err != nil {
return err
}
}
return nil
}
// ResetInstancePolicies removes every stored instance policy. The
// cross-org forbid is engine-enforced and survives any reset.
func (s *Store) ResetInstancePolicies(ctx context.Context) error {
return s.queries().ResetInstancePolicies(ctx)
}
// RecordResetAudit records the one audit row a reset is written as.
func (s *Store) RecordResetAudit(ctx context.Context, key string) error {
return s.queries().InsertAccessResetAudit(ctx, key)
}
// RecordDenial records one refusal The store coalesces identical denials
// within a minute into one row with a count, so a retry storm does not
// flood the surface.
func (s *Store) RecordDenial(ctx context.Context, d access.Denial) error {
if d.Org == "" || d.Principal == "" {
return fmt.Errorf("%w: org and principal are required", access.ErrInvalidPolicy)
}
return s.queries().RecordDenial(ctx, postgresdb.RecordDenialParams{
OrgID: string(d.Org), Principal: string(d.Principal), Action: string(d.Action),
ResourceKind: string(d.Kind), ResourceID: d.ResourceID, Level: string(d.Level),
Policies: d.Policies,
})
}
// ListDenials returns an org's most recent denials, newest first.
func (s *Store) ListDenials(ctx context.Context, orgID org.OrgID, limit int) ([]access.Denial, error) {
rows, err := s.queries().ListDenials(ctx, postgresdb.ListDenialsParams{
OrgID: string(orgID), Limit: int32(limit),
})
if err != nil {
return nil, err
}
out := make([]access.Denial, 0, len(rows))
for _, r := range rows {
out = append(out, access.Denial{
Principal: identity.IdentityID(r.Principal),
Org: org.OrgID(r.OrgID),
Action: access.Action(r.Action),
Kind: access.ResourceKind(r.ResourceKind),
ResourceID: r.ResourceID,
Level: access.Level(r.Level),
Policies: r.Policies,
At: r.CreatedAt,
Count: r.Count,
})
}
return out, nil
}
@@ -0,0 +1,225 @@
package postgres
import (
"errors"
"testing"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
func newStoreForAccess(t *testing.T) *Store {
t.Helper()
pool, _ := migrated(t)
return New(pool)
}
func TestAccessPolicyStore(t *testing.T) {
s := newStoreForAccess(t)
ctx := t.Context()
// PutPolicy stores one policy and reports a versioned level.
p := access.Policy{
ID: "test-policy", Level: access.LevelOrg, OrgID: "soc",
Text: `permit(principal, action, resource) when { resource.kind == "binding" };`,
}
v1, err := s.PutPolicy(ctx, p)
if err != nil {
t.Fatalf("PutPolicy: %v", err)
}
if v1 != 2 { // the counter starts at 1; the first write bumps it
t.Fatalf("PutPolicy version = %d, want 2", v1)
}
v2, err := s.PutPolicy(ctx, p)
if err != nil {
t.Fatalf("second PutPolicy: %v", err)
}
if v2 <= v1 {
t.Fatalf("second PutPolicy version = %d, want > %d", v2, v1)
}
// A malformed policy is refused by the store's own structural check.
bad := access.Policy{ID: "bad", Level: access.LevelOrg, OrgID: "soc"}
if _, err := s.PutPolicy(ctx, bad); !errors.Is(err, access.ErrInvalidPolicy) {
t.Fatalf("PutPolicy(structurally invalid) = %v, want ErrInvalidPolicy", err)
}
// ListPolicies round-trips the scope tuple.
list, err := s.ListPolicies(ctx)
if err != nil {
t.Fatalf("ListPolicies: %v", err)
}
if len(list) != 1 {
t.Fatalf("ListPolicies = %d policies, want 1", len(list))
}
if list[0].ID != "test-policy" || list[0].OrgID != "soc" {
t.Fatalf("ListPolicies[0] = %+v, want the stored policy", list[0])
}
// DeletePolicy removes it and reports an unknown key as a sentinel.
if err := s.DeletePolicy(ctx, p); err != nil {
t.Fatalf("DeletePolicy: %v", err)
}
if err := s.DeletePolicy(ctx, p); !errors.Is(err, access.ErrPolicyNotFound) {
t.Fatalf("second DeletePolicy = %v, want ErrPolicyNotFound", err)
}
}
func TestEnsureShippedOrgPolicies(t *testing.T) {
s := newStoreForAccess(t)
ctx := t.Context()
if err := s.EnsureShippedOrgPolicies(ctx, "soc"); err != nil {
t.Fatalf("EnsureShippedOrgPolicies: %v", err)
}
list, err := s.ListPolicies(ctx)
if err != nil {
t.Fatalf("ListPolicies: %v", err)
}
if len(list) != 4 {
t.Fatalf("seeding produced %d policies, want the 4 shipped roles", len(list))
}
// An edited role policy survives a re-seed: an org that already carries
// the shipped IDs is left untouched.
edited := list[0]
edited.Text = `permit(principal, action, resource) when { resource.kind == "edited" };`
if _, err := s.PutPolicy(ctx, edited); err != nil {
t.Fatalf("PutPolicy(edit): %v", err)
}
if err := s.EnsureShippedOrgPolicies(ctx, "soc"); err != nil {
t.Fatalf("re-seed: %v", err)
}
after, err := s.ListPolicies(ctx)
if err != nil {
t.Fatalf("ListPolicies after re-seed: %v", err)
}
for _, p := range after {
if p.ID == edited.ID && p.Text != edited.Text {
t.Fatalf("re-seed overwrote an edited role policy %s", p.ID)
}
}
}
func TestResetPolicies(t *testing.T) {
s := newStoreForAccess(t)
ctx := t.Context()
if err := s.ResetOrgPolicies(ctx, "soc"); err != nil {
t.Fatalf("ResetOrgPolicies: %v", err)
}
// An operator's custom org policy on top of the shipped set.
custom := access.Policy{
ID: "org-lockdown", Level: access.LevelOrg, OrgID: "soc",
Text: `forbid(principal, action, resource) when { resource.kind == "source" };`,
}
if _, err := s.PutPolicy(ctx, custom); err != nil {
t.Fatalf("PutPolicy(custom): %v", err)
}
// A workspace policy must survive an org reset.
ws := access.Policy{
ID: "ws-rule", Level: access.LevelWorkspace, OrgID: "soc", WorkspaceID: "net",
Text: `permit(principal, action, resource) when { resource.kind == "binding" };`,
}
if _, err := s.PutPolicy(ctx, ws); err != nil {
t.Fatalf("PutPolicy(ws): %v", err)
}
// And an instance policy must survive an org reset but not an instance
// reset.
instance := access.Policy{
ID: "instance-rule", Level: access.LevelInstance,
Text: `forbid(principal, action, resource) when { resource.kind == "secret" };`,
}
if _, err := s.PutPolicy(ctx, instance); err != nil {
t.Fatalf("PutPolicy(instance): %v", err)
}
if err := s.ResetOrgPolicies(ctx, "soc"); err != nil {
t.Fatalf("org reset: %v", err)
}
after, err := s.ListPolicies(ctx)
if err != nil {
t.Fatalf("ListPolicies: %v", err)
}
orgPolicies := 0
for _, p := range after {
switch {
case p.Level == access.LevelOrg && p.OrgID == "soc":
orgPolicies++
case p.Level == access.LevelOrg:
t.Fatalf("org reset touched policy %s of another org", p.ID)
}
}
if orgPolicies != 4 {
t.Fatalf("org-level policies after reset = %d, want the 4 shipped roles", orgPolicies)
}
if err := s.ResetInstancePolicies(ctx); err != nil {
t.Fatalf("ResetInstancePolicies: %v", err)
}
after, err = s.ListPolicies(ctx)
if err != nil {
t.Fatalf("ListPolicies after instance reset: %v", err)
}
for _, p := range after {
if p.Level == access.LevelInstance {
t.Fatalf("instance reset left policy %s", p.ID)
}
}
if len(after) == 0 {
t.Fatal("instance reset removed non-instance policies")
}
}
func TestDenialStore(t *testing.T) {
s := newStoreForAccess(t)
ctx := t.Context()
denial := access.Denial{
Principal: identity.IdentityID("11111111-1111-5111-8111-111111111111"),
Org: "soc", Action: access.ActionRead, Kind: access.KindBinding,
ResourceID: "b1", Level: access.LevelOrg,
Policies: []string{access.PolicyOrgRead, access.PolicyOrgEdit},
}
if err := s.RecordDenial(ctx, denial); err != nil {
t.Fatalf("RecordDenial: %v", err)
}
if err := s.RecordDenial(ctx, denial); err != nil {
t.Fatalf("repeat RecordDenial: %v", err)
}
// A different action is a separate row.
other := denial
other.Action = access.ActionDelete
if err := s.RecordDenial(ctx, other); err != nil {
t.Fatalf("RecordDenial(other action): %v", err)
}
rows, err := s.ListDenials(ctx, "soc", 10)
if err != nil {
t.Fatalf("ListDenials: %v", err)
}
if len(rows) != 2 {
t.Fatalf("ListDenials = %d rows, want 2", len(rows))
}
if rows[0].Action != access.ActionDelete {
t.Fatalf("newest denial = %v, want the delete denial", rows[0].Action)
}
for _, r := range rows {
if r.Action == access.ActionRead {
if r.Count != 2 {
t.Fatalf("repeated denial count = %d, want 2 (coalesced within the minute)", r.Count)
}
if len(r.Policies) != 2 {
t.Fatalf("denial policies = %v, want the deciding policies", r.Policies)
}
}
}
// Another org sees none of these.
if rows, err := s.ListDenials(ctx, "other", 10); err != nil || len(rows) != 0 {
t.Fatalf("ListDenials(other org) = %d rows %v, want none", len(rows), err)
}
// An org-less denial is refused at the producer.
if err := s.RecordDenial(ctx, access.Denial{Action: access.ActionRead}); err == nil {
t.Fatal("RecordDenial accepted a denial with no org or principal")
}
}
@@ -0,0 +1,60 @@
-- Access policies and denial records: the stored half of the policy chain
-- (docs/prds/orgs-and-access.md, "Storing and changing policies" and
-- "Denials"). The shipped cross-org forbid is engine-enforced and has no row
-- here; the shipped role policies are seeded per org as ordinary rows with
-- the shipped IDs, so a reset overwrites them and an edit sticks until reset.
--
-- The scope tuple (level, org_id, workspace_id, object_kind, object_id) is
-- the policy's place in the chain; policy_id names the document inside it.
-- The version counter is per level-scope: PutPolicy bumps it and returns it,
-- so the engine's next load can detect a change.
-- +goose Up
CREATE TABLE access_policies (
level text NOT NULL CHECK (level IN ('instance', 'org', 'workspace', 'object')),
org_id text NOT NULL DEFAULT '',
workspace_id text NOT NULL DEFAULT '',
object_kind text NOT NULL DEFAULT '',
object_id text NOT NULL DEFAULT '',
policy_id text NOT NULL,
text text NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (level, org_id, workspace_id, object_kind, object_id, policy_id)
);
CREATE TABLE access_policy_versions (
level text NOT NULL CHECK (level IN ('instance', 'org', 'workspace', 'object')),
org_id text NOT NULL DEFAULT '',
workspace_id text NOT NULL DEFAULT '',
version bigint NOT NULL DEFAULT 1,
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (level, org_id, workspace_id)
);
-- One denial row per (principal, action, resource, level, policies, minute):
-- a retry storm inside one minute is a count bump, not a row flood
-- (docs/prds/orgs-and-access.md, "Audit retention").
CREATE TABLE access_denials (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
org_id text NOT NULL,
principal text NOT NULL,
action text NOT NULL,
resource_kind text NOT NULL,
resource_id text NOT NULL,
level text NOT NULL,
policies text[] NOT NULL DEFAULT '{}',
minute_at timestamptz NOT NULL DEFAULT date_trunc('minute', now()),
count bigint NOT NULL DEFAULT 1,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX idx_access_denials_dedup ON access_denials
(org_id, principal, action, resource_kind, resource_id, level, policies, minute_at);
-- +goose Down
DROP INDEX idx_access_denials_dedup;
DROP TABLE access_denials;
DROP TABLE access_policy_versions;
DROP TABLE access_policies;
+38
View File
@@ -17,6 +17,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
@@ -150,6 +151,43 @@ func (s *Store) AssignAgent(ctx context.Context, value org.AgentAssignment) erro
})
}
// EnsureAgentOrgMembership grants every agent identity the shipped developer
// role in the org it serves. It runs at the State Store's boot, after the
// default-org upgrade, so dispatch's chain has a principal to evaluate.
// Idempotent: an existing membership (any role) is left alone.
func (s *Store) EnsureAgentOrgMembership(ctx context.Context) error {
return s.queries().EnsureAgentOrgMembership(ctx)
}
// PrincipalFor assembles the access principal for one identity: the org it
// serves and its memberships (internal/domain/access). An identity in no org
// is the default org with no role, which the shipped role policies never
// permit.
func (s *Store) PrincipalFor(ctx context.Context, id identity.IdentityID) (access.Principal, error) {
resolved, err := s.OrgForIdentity(ctx, id)
if err != nil {
return access.Principal{}, err
}
rows, err := s.queries().ListMembershipsByIdentity(ctx, string(id))
if err != nil {
return access.Principal{}, err
}
memberships := make([]org.Membership, 0, len(rows))
for _, r := range rows {
var ws org.WorkspaceID
if r.WorkspaceID.Valid {
ws = org.WorkspaceID(r.WorkspaceID.String)
}
memberships = append(memberships, org.Membership{
IdentityID: id,
OrgID: org.OrgID(r.OrgID),
WorkspaceID: ws,
Role: org.Role(r.Role),
})
}
return access.Principal{IdentityID: id, Org: resolved, Memberships: memberships}, nil
}
// OrgForIdentity returns the org an identity serves: the assigned org for an
// agent, the org of one of its memberships for a person, and the default org
// for an identity in no org.
@@ -0,0 +1,341 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: access.sql
package postgresdb
import (
"context"
)
const countShippedOrgPolicies = `-- name: CountShippedOrgPolicies :one
SELECT count(*) FROM access_policies
WHERE level = 'org' AND org_id = $1 AND policy_id = ANY($2::text[])
`
type CountShippedOrgPoliciesParams struct {
OrgID string
Column2 []string
}
// How many of an org's shipped role policies are stored. The seeding runs
// only when the org carries none of them, so a restart never overwrites an
// edited role policy (the shipped IDs are reserved for the shipped text).
func (q *Queries) CountShippedOrgPolicies(ctx context.Context, arg CountShippedOrgPoliciesParams) (int64, error) {
row := q.db.QueryRow(ctx, countShippedOrgPolicies, arg.OrgID, arg.Column2)
var count int64
err := row.Scan(&count)
return count, err
}
const deleteAccessPolicy = `-- name: DeleteAccessPolicy :execrows
DELETE FROM access_policies
WHERE level = $1 AND org_id = $2 AND workspace_id = $3 AND object_kind = $4
AND object_id = $5 AND policy_id = $6
`
type DeleteAccessPolicyParams struct {
Level string
OrgID string
WorkspaceID string
ObjectKind string
ObjectID string
PolicyID string
}
func (q *Queries) DeleteAccessPolicy(ctx context.Context, arg DeleteAccessPolicyParams) (int64, error) {
result, err := q.db.Exec(ctx, deleteAccessPolicy,
arg.Level,
arg.OrgID,
arg.WorkspaceID,
arg.ObjectKind,
arg.ObjectID,
arg.PolicyID,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const deleteAccessPolicyVersion = `-- name: DeleteAccessPolicyVersion :exec
DELETE FROM access_policy_versions v
WHERE v.level = $1 AND v.org_id = $2 AND v.workspace_id = $3
AND NOT EXISTS (SELECT 1 FROM access_policies p
WHERE p.level = v.level AND p.org_id = v.org_id AND p.workspace_id = v.workspace_id)
`
type DeleteAccessPolicyVersionParams struct {
Level string
OrgID string
WorkspaceID string
}
// Tidy a level-scope with no policies left: its version row has no reader.
func (q *Queries) DeleteAccessPolicyVersion(ctx context.Context, arg DeleteAccessPolicyVersionParams) error {
_, err := q.db.Exec(ctx, deleteAccessPolicyVersion, arg.Level, arg.OrgID, arg.WorkspaceID)
return err
}
const deleteOrgPoliciesNotShipped = `-- name: DeleteOrgPoliciesNotShipped :exec
DELETE FROM access_policies
WHERE level = 'org' AND org_id = $1 AND NOT (policy_id = ANY($2::text[]))
`
type DeleteOrgPoliciesNotShippedParams struct {
OrgID string
Column2 []string
}
// The org reset's removal half: every org-level policy except the shipped
// role set.
func (q *Queries) DeleteOrgPoliciesNotShipped(ctx context.Context, arg DeleteOrgPoliciesNotShippedParams) error {
_, err := q.db.Exec(ctx, deleteOrgPoliciesNotShipped, arg.OrgID, arg.Column2)
return err
}
const getAccessPolicy = `-- name: GetAccessPolicy :one
SELECT text FROM access_policies
WHERE level = $1 AND org_id = $2 AND workspace_id = $3 AND object_kind = $4
AND object_id = $5 AND policy_id = $6
`
type GetAccessPolicyParams struct {
Level string
OrgID string
WorkspaceID string
ObjectKind string
ObjectID string
PolicyID string
}
func (q *Queries) GetAccessPolicy(ctx context.Context, arg GetAccessPolicyParams) (string, error) {
row := q.db.QueryRow(ctx, getAccessPolicy,
arg.Level,
arg.OrgID,
arg.WorkspaceID,
arg.ObjectKind,
arg.ObjectID,
arg.PolicyID,
)
var text string
err := row.Scan(&text)
return text, err
}
const insertAccessPolicyAudit = `-- name: InsertAccessPolicyAudit :exec
INSERT INTO sys_audit (at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id)
VALUES (now(), 'access_policies', $1, 'text', $2, $3, $4, $5, $6, $7)
`
type InsertAccessPolicyAuditParams struct {
RecordKey string
OldValue []byte
NewValue []byte
RecordVersion int64
Actor string
Source string
RequestID string
}
// One audit row per policy change: the policy's old and new text
// (docs/prds/orgs-and-access.md, "Storing and changing policies").
func (q *Queries) InsertAccessPolicyAudit(ctx context.Context, arg InsertAccessPolicyAuditParams) error {
_, err := q.db.Exec(ctx, insertAccessPolicyAudit,
arg.RecordKey,
arg.OldValue,
arg.NewValue,
arg.RecordVersion,
arg.Actor,
arg.Source,
arg.RequestID,
)
return err
}
const insertAccessResetAudit = `-- name: InsertAccessResetAudit :exec
INSERT INTO sys_audit (at, table_name, record_key, field, record_version, actor, source, request_id)
VALUES (now(), 'access_policies', $1, 'reset', 1, 'archied access reset', 'archied', '')
`
// The one audit row a reset is recorded as; the reset's policy changes
// carry their own rows (docs/prds/orgs-and-access.md, "Recovering from a
// locked-out org").
func (q *Queries) InsertAccessResetAudit(ctx context.Context, recordKey string) error {
_, err := q.db.Exec(ctx, insertAccessResetAudit, recordKey)
return err
}
const listAccessPolicies = `-- name: ListAccessPolicies :many
SELECT level, org_id, workspace_id, object_kind, object_id, policy_id, text, updated_at
FROM access_policies ORDER BY level, org_id, workspace_id, object_kind, object_id, policy_id
`
// Access policies and denial records (internal/domain/access): the durable
// half of the policy-chain contract. Versioning is per level-scope; every
// policy change writes one sys_audit row naming who made it.
func (q *Queries) ListAccessPolicies(ctx context.Context) ([]AccessPolicy, error) {
rows, err := q.db.Query(ctx, listAccessPolicies)
if err != nil {
return nil, err
}
defer rows.Close()
var items []AccessPolicy
for rows.Next() {
var i AccessPolicy
if err := rows.Scan(
&i.Level,
&i.OrgID,
&i.WorkspaceID,
&i.ObjectKind,
&i.ObjectID,
&i.PolicyID,
&i.Text,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listDenials = `-- name: ListDenials :many
SELECT id, org_id, principal, action, resource_kind, resource_id, level, policies, minute_at, count, created_at, updated_at
FROM access_denials WHERE org_id = $1 ORDER BY id DESC LIMIT $2
`
type ListDenialsParams struct {
OrgID string
Limit int32
}
func (q *Queries) ListDenials(ctx context.Context, arg ListDenialsParams) ([]AccessDenial, error) {
rows, err := q.db.Query(ctx, listDenials, arg.OrgID, arg.Limit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []AccessDenial
for rows.Next() {
var i AccessDenial
if err := rows.Scan(
&i.ID,
&i.OrgID,
&i.Principal,
&i.Action,
&i.ResourceKind,
&i.ResourceID,
&i.Level,
&i.Policies,
&i.MinuteAt,
&i.Count,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const recordDenial = `-- name: RecordDenial :exec
INSERT INTO access_denials (org_id, principal, action, resource_kind, resource_id, level, policies)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (org_id, principal, action, resource_kind, resource_id, level, policies, minute_at)
DO UPDATE SET count = access_denials.count + 1, updated_at = now()
`
type RecordDenialParams struct {
OrgID string
Principal string
Action string
ResourceKind string
ResourceID string
Level string
Policies []string
}
// One row per (principal, action, resource, level, policies, minute);
// a repeat inside the minute bumps the count (docs/prds/orgs-and-access.md,
// "Audit retention").
func (q *Queries) RecordDenial(ctx context.Context, arg RecordDenialParams) error {
_, err := q.db.Exec(ctx, recordDenial,
arg.OrgID,
arg.Principal,
arg.Action,
arg.ResourceKind,
arg.ResourceID,
arg.Level,
arg.Policies,
)
return err
}
const resetInstancePolicies = `-- name: ResetInstancePolicies :exec
DELETE FROM access_policies WHERE level = 'instance'
`
func (q *Queries) ResetInstancePolicies(ctx context.Context) error {
_, err := q.db.Exec(ctx, resetInstancePolicies)
return err
}
const upsertAccessPolicy = `-- name: UpsertAccessPolicy :exec
INSERT INTO access_policies (level, org_id, workspace_id, object_kind, object_id, policy_id, text)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (level, org_id, workspace_id, object_kind, object_id, policy_id)
DO UPDATE SET text = excluded.text, updated_at = now()
`
type UpsertAccessPolicyParams struct {
Level string
OrgID string
WorkspaceID string
ObjectKind string
ObjectID string
PolicyID string
Text string
}
func (q *Queries) UpsertAccessPolicy(ctx context.Context, arg UpsertAccessPolicyParams) error {
_, err := q.db.Exec(ctx, upsertAccessPolicy,
arg.Level,
arg.OrgID,
arg.WorkspaceID,
arg.ObjectKind,
arg.ObjectID,
arg.PolicyID,
arg.Text,
)
return err
}
const upsertAccessPolicyVersion = `-- name: UpsertAccessPolicyVersion :one
INSERT INTO access_policy_versions (level, org_id, workspace_id, version) VALUES ($1, $2, $3, 2)
ON CONFLICT (level, org_id, workspace_id)
DO UPDATE SET version = access_policy_versions.version + 1, updated_at = now()
RETURNING version
`
type UpsertAccessPolicyVersionParams struct {
Level string
OrgID string
WorkspaceID string
}
func (q *Queries) UpsertAccessPolicyVersion(ctx context.Context, arg UpsertAccessPolicyVersionParams) (int64, error) {
row := q.db.QueryRow(ctx, upsertAccessPolicyVersion, arg.Level, arg.OrgID, arg.WorkspaceID)
var version int64
err := row.Scan(&version)
return version, err
}
@@ -10,6 +10,40 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
type AccessDenial struct {
ID int64
OrgID string
Principal string
Action string
ResourceKind string
ResourceID string
Level string
Policies []string
MinuteAt time.Time
Count int64
CreatedAt time.Time
UpdatedAt time.Time
}
type AccessPolicy struct {
Level string
OrgID string
WorkspaceID string
ObjectKind string
ObjectID string
PolicyID string
Text string
UpdatedAt time.Time
}
type AccessPolicyVersion struct {
Level string
OrgID string
WorkspaceID string
Version int64
UpdatedAt time.Time
}
type ApplyStatus struct {
Process string
Kind string
@@ -11,6 +11,22 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
const ensureAgentOrgMembership = `-- name: EnsureAgentOrgMembership :exec
INSERT INTO memberships (identity_id, org_id, role)
SELECT a.identity_id, a.org_id, 'developer' FROM org_agents a
ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO NOTHING
`
// Every agent identity serves its org with the shipped developer role: an
// agent is granted access the way a user is
// (docs/prds/orgs-and-access.md, "Identity"). Idempotent, so an operator's
// later role change survives a restart, and the shipped seed never
// overwrites it.
func (q *Queries) EnsureAgentOrgMembership(ctx context.Context) error {
_, err := q.db.Exec(ctx, ensureAgentOrgMembership)
return err
}
const ensureMembership = `-- name: EnsureMembership :exec
INSERT INTO memberships (identity_id, org_id, workspace_id, role)
VALUES ($1, $2, $3, $4)
@@ -0,0 +1,77 @@
-- Access policies and denial records (internal/domain/access): the durable
-- half of the policy-chain contract. Versioning is per level-scope; every
-- policy change writes one sys_audit row naming who made it.
-- name: ListAccessPolicies :many
SELECT level, org_id, workspace_id, object_kind, object_id, policy_id, text, updated_at
FROM access_policies ORDER BY level, org_id, workspace_id, object_kind, object_id, policy_id;
-- name: UpsertAccessPolicy :exec
INSERT INTO access_policies (level, org_id, workspace_id, object_kind, object_id, policy_id, text)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (level, org_id, workspace_id, object_kind, object_id, policy_id)
DO UPDATE SET text = excluded.text, updated_at = now();
-- name: GetAccessPolicy :one
SELECT text FROM access_policies
WHERE level = $1 AND org_id = $2 AND workspace_id = $3 AND object_kind = $4
AND object_id = $5 AND policy_id = $6;
-- name: DeleteAccessPolicy :execrows
DELETE FROM access_policies
WHERE level = $1 AND org_id = $2 AND workspace_id = $3 AND object_kind = $4
AND object_id = $5 AND policy_id = $6;
-- name: CountShippedOrgPolicies :one
-- How many of an org's shipped role policies are stored. The seeding runs
-- only when the org carries none of them, so a restart never overwrites an
-- edited role policy (the shipped IDs are reserved for the shipped text).
SELECT count(*) FROM access_policies
WHERE level = 'org' AND org_id = $1 AND policy_id = ANY($2::text[]);
-- name: DeleteOrgPoliciesNotShipped :exec
-- The org reset's removal half: every org-level policy except the shipped
-- role set.
DELETE FROM access_policies
WHERE level = 'org' AND org_id = $1 AND NOT (policy_id = ANY($2::text[]));
-- name: ResetInstancePolicies :exec
DELETE FROM access_policies WHERE level = 'instance';
-- name: UpsertAccessPolicyVersion :one
INSERT INTO access_policy_versions (level, org_id, workspace_id, version) VALUES ($1, $2, $3, 2)
ON CONFLICT (level, org_id, workspace_id)
DO UPDATE SET version = access_policy_versions.version + 1, updated_at = now()
RETURNING version;
-- name: DeleteAccessPolicyVersion :exec
-- Tidy a level-scope with no policies left: its version row has no reader.
DELETE FROM access_policy_versions v
WHERE v.level = $1 AND v.org_id = $2 AND v.workspace_id = $3
AND NOT EXISTS (SELECT 1 FROM access_policies p
WHERE p.level = v.level AND p.org_id = v.org_id AND p.workspace_id = v.workspace_id);
-- name: InsertAccessPolicyAudit :exec
-- One audit row per policy change: the policy's old and new text
-- (docs/prds/orgs-and-access.md, "Storing and changing policies").
INSERT INTO sys_audit (at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id)
VALUES (now(), 'access_policies', $1, 'text', $2, $3, $4, $5, $6, $7);
-- name: RecordDenial :exec
-- One row per (principal, action, resource, level, policies, minute);
-- a repeat inside the minute bumps the count (docs/prds/orgs-and-access.md,
-- "Audit retention").
INSERT INTO access_denials (org_id, principal, action, resource_kind, resource_id, level, policies)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (org_id, principal, action, resource_kind, resource_id, level, policies, minute_at)
DO UPDATE SET count = access_denials.count + 1, updated_at = now();
-- name: ListDenials :many
SELECT id, org_id, principal, action, resource_kind, resource_id, level, policies, minute_at, count, created_at, updated_at
FROM access_denials WHERE org_id = $1 ORDER BY id DESC LIMIT $2;
-- name: InsertAccessResetAudit :exec
-- The one audit row a reset is recorded as; the reset's policy changes
-- carry their own rows (docs/prds/orgs-and-access.md, "Recovering from a
-- locked-out org").
INSERT INTO sys_audit (at, table_name, record_key, field, record_version, actor, source, request_id)
VALUES (now(), 'access_policies', $1, 'reset', 1, 'archied access reset', 'archied', '');
@@ -40,4 +40,13 @@ SELECT COALESCE(
(SELECT m.org_id FROM memberships m WHERE m.identity_id = $1
ORDER BY m.created_at, m.org_id, m.workspace_id NULLS LAST LIMIT 1),
'default'
)::text AS org_id;
)::text AS org_id;
-- name: EnsureAgentOrgMembership :exec
-- Every agent identity serves its org with the shipped developer role: an
-- agent is granted access the way a user is
-- (docs/prds/orgs-and-access.md, "Identity"). Idempotent, so an operator's
-- later role change survives a restart, and the shipped seed never
-- overwrites it.
INSERT INTO memberships (identity_id, org_id, role)
SELECT a.identity_id, a.org_id, 'developer' FROM org_agents a
ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO NOTHING;
@@ -21,6 +21,7 @@ import (
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/health"
"github.com/samcharles93/archie-core/internal/infrastructure/access"
)
// --- state_db ---
@@ -93,6 +94,51 @@ func (p *ContractProbe) Check(ctx context.Context) health.Result {
return health.Result{Status: health.StatusOK}
}
// --- access policies ---
// PolicyProblems reports the stored access policies this process's engine
// could not validate. The policy chain is the source; a policy that failed
// startup re-validation denies its level and must be named here with its
// error (docs/prds/orgs-and-access.md, "Storing and changing policies").
type PolicyProblems interface {
Problems() []access.Problem
}
// ProblemProbe reports the stored policies the engine could not validate.
// It is a static probe: the engine is immutable for the life of the process,
// so the problems it names do not change under it.
type ProblemProbe struct {
ProbeName string
Source PolicyProblems
}
// NewProblemProbe returns an access_policies probe over a problem source.
// A nil source degrades the probe rather than lying about the chain.
func NewProblemProbe(name string, problems []access.Problem) *ProblemProbe {
return &ProblemProbe{ProbeName: name, Source: staticProblemSource(problems)}
}
type staticProblemSource []access.Problem
func (s staticProblemSource) Problems() []access.Problem { return s }
func (p *ProblemProbe) Name() string { return p.ProbeName }
func (p *ProblemProbe) Check(ctx context.Context) health.Result {
if p.Source == nil {
return health.Result{Status: health.StatusDegraded, Detail: "access engine not wired"}
}
problems := p.Source.Problems()
if len(problems) == 0 {
return health.Result{Status: health.StatusOK}
}
details := make([]string, 0, len(problems))
for _, problem := range problems {
details = append(details, problem.Policy.ID+": "+problem.Err.Error())
}
return health.Result{Status: health.StatusDegraded, Detail: strings.Join(details, "; ")}
}
// --- config ---
// ConfigProbe validates the running configuration. It is the same check the
+177
View File
@@ -0,0 +1,177 @@
// Access: the policy-chain and denial-record RPCs (docs/prds/orgs-and-access.md).
// The policies surface is the engine's snapshot plus the administrative
// writes; the denials surface is the two callers' write path and the
// operator's read.
package staterpc
import (
"context"
"errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
)
var (
errPoliciesUnavailable = status.Error(codes.Unavailable, "access policy store unavailable")
errDenialsUnavailable = status.Error(codes.Unavailable, "access denial store unavailable")
)
func accessPolicyProto(p access.Policy) *pb.AccessPolicy {
return &pb.AccessPolicy{
PolicyId: p.ID, Level: string(p.Level), OrgId: string(p.OrgID),
WorkspaceId: string(p.WorkspaceID), ObjectKind: string(p.ObjectKind),
ObjectId: p.ObjectID, Text: p.Text,
}
}
func accessPolicyValue(p *pb.AccessPolicy) access.Policy {
return access.Policy{
ID: p.GetPolicyId(), Level: access.Level(p.GetLevel()),
OrgID: org.OrgID(p.GetOrgId()), WorkspaceID: org.WorkspaceID(p.GetWorkspaceId()),
ObjectKind: access.ResourceKind(p.GetObjectKind()), ObjectID: p.GetObjectId(),
Text: p.GetText(),
}
}
func accessDenialProto(d access.Denial) *pb.AccessDenial {
out := &pb.AccessDenial{
OrgId: string(d.Org), Principal: string(d.Principal), Action: string(d.Action),
ResourceKind: string(d.Kind), ResourceId: d.ResourceID, Level: string(d.Level),
Policies: d.Policies, Count: d.Count,
}
if !d.At.IsZero() {
out.At = timestamp(d.At)
}
return out
}
func accessDenialValue(d *pb.AccessDenial) access.Denial {
value := access.Denial{
Org: org.OrgID(d.GetOrgId()),
Principal: identity.IdentityID(d.GetPrincipal()),
Action: access.Action(d.GetAction()),
Kind: access.ResourceKind(d.GetResourceKind()),
ResourceID: d.GetResourceId(),
Level: access.Level(d.GetLevel()),
Policies: d.GetPolicies(),
Count: d.GetCount(),
}
if d.GetAt() != nil {
value.At = d.GetAt().AsTime()
}
return value
}
func (s *server) GetPrincipal(ctx context.Context, request *pb.GetPrincipalRequest) (*pb.GetPrincipalResponse, error) {
if s.deps.Principals == nil {
return nil, status.Error(codes.Unavailable, "identity store unavailable")
}
value, err := s.deps.Principals.PrincipalFor(ctx, identity.IdentityID(request.IdentityId))
if err != nil {
return nil, identityStatus(err)
}
memberships := make([]*pb.PrincipalMembership, len(value.Memberships))
for i := range value.Memberships {
m := value.Memberships[i]
memberships[i] = &pb.PrincipalMembership{
OrgId: string(m.OrgID), WorkspaceId: string(m.WorkspaceID), Role: string(m.Role),
}
}
return &pb.GetPrincipalResponse{Principal: &pb.AccessPrincipal{
IdentityId: string(value.IdentityID),
OrgId: string(value.Org),
Memberships: memberships,
}}, nil
}
func (s *server) ListPolicies(ctx context.Context, _ *pb.ListPoliciesRequest) (*pb.ListPoliciesResponse, error) {
if s.deps.Policies == nil {
return nil, errPoliciesUnavailable
}
values, err := s.deps.Policies.ListPolicies(ctx)
if err != nil {
return nil, accessStatus(err)
}
out := make([]*pb.AccessPolicy, len(values))
for i := range values {
out[i] = accessPolicyProto(values[i])
}
return &pb.ListPoliciesResponse{Policies: out}, nil
}
func (s *server) PutPolicy(ctx context.Context, request *pb.PutPolicyRequest) (*pb.PutPolicyResponse, error) {
if s.deps.Policies == nil {
return nil, errPoliciesUnavailable
}
version, err := s.deps.Policies.PutPolicy(ctx, accessPolicyValue(request.Policy))
if err != nil {
return nil, accessStatus(err)
}
return &pb.PutPolicyResponse{Version: version}, nil
}
func (s *server) DeletePolicy(ctx context.Context, request *pb.DeletePolicyRequest) (*pb.DeletePolicyResponse, error) {
if s.deps.Policies == nil {
return nil, errPoliciesUnavailable
}
if err := s.deps.Policies.DeletePolicy(ctx, accessPolicyValue(request.Policy)); err != nil {
return nil, accessStatus(err)
}
return &pb.DeletePolicyResponse{}, nil
}
func (s *server) EnsureShippedOrgPolicies(ctx context.Context, request *pb.EnsureShippedOrgPoliciesRequest) (*pb.EnsureShippedOrgPoliciesResponse, error) {
if s.deps.Policies == nil {
return nil, errPoliciesUnavailable
}
if err := s.deps.Policies.EnsureShippedOrgPolicies(ctx, org.OrgID(request.OrgId)); err != nil {
return nil, accessStatus(err)
}
return &pb.EnsureShippedOrgPoliciesResponse{}, nil
}
func (s *server) RecordDenial(ctx context.Context, request *pb.RecordDenialRequest) (*pb.RecordDenialResponse, error) {
if s.deps.Denials == nil {
return nil, errDenialsUnavailable
}
if err := s.deps.Denials.RecordDenial(ctx, accessDenialValue(request.Denial)); err != nil {
return nil, accessStatus(err)
}
return &pb.RecordDenialResponse{}, nil
}
func (s *server) ListDenials(ctx context.Context, request *pb.ListDenialsRequest) (*pb.ListDenialsResponse, error) {
if s.deps.Denials == nil {
return nil, errDenialsUnavailable
}
limit := int(request.GetLimit())
if limit <= 0 || limit > 1000 {
limit = 100
}
values, err := s.deps.Denials.ListDenials(ctx, org.OrgID(request.OrgId), limit)
if err != nil {
return nil, accessStatus(err)
}
out := make([]*pb.AccessDenial, len(values))
for i := range values {
out[i] = accessDenialProto(values[i])
}
return &pb.ListDenialsResponse{Denials: out}, nil
}
// accessStatus maps an access sentinel to its gRPC status.
func accessStatus(err error) error {
if errors.Is(err, access.ErrPolicyNotFound) {
return status.Error(codes.NotFound, access.ErrPolicyNotFound.Error())
}
if errors.Is(err, access.ErrInvalidPolicy) {
return status.Error(codes.InvalidArgument, access.ErrInvalidPolicy.Error())
}
return mapError(err)
}
@@ -0,0 +1,90 @@
// Access: the client half of the policy-chain and denial-record RPCs
// (docs/prds/orgs-and-access.md). The reset surface is deliberately absent:
// `archied access reset` runs on the State Store host, never over the wire.
package staterpc
import (
"context"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// The Client satisfies the access contracts the two callers depend on.
var (
_ access.PolicyStore = (*Client)(nil)
_ access.DenialStore = (*Client)(nil)
_ access.PrincipalSource = (*Client)(nil)
)
func (c *Client) PrincipalFor(ctx context.Context, id identity.IdentityID) (access.Principal, error) {
r, err := c.client.GetPrincipal(ctx, &pb.GetPrincipalRequest{IdentityId: string(id)})
if err != nil {
return access.Principal{}, unmapError(err)
}
value := r.GetPrincipal()
memberships := make([]org.Membership, len(value.GetMemberships()))
for i := range value.GetMemberships() {
m := value.GetMemberships()[i]
memberships[i] = org.Membership{
IdentityID: id,
OrgID: org.OrgID(m.GetOrgId()),
WorkspaceID: org.WorkspaceID(m.GetWorkspaceId()),
Role: org.Role(m.GetRole()),
}
}
return access.Principal{
IdentityID: identity.IdentityID(value.GetIdentityId()),
Org: org.OrgID(value.GetOrgId()),
Memberships: memberships,
}, nil
}
func (c *Client) ListPolicies(ctx context.Context) ([]access.Policy, error) {
r, err := c.client.ListPolicies(ctx, &pb.ListPoliciesRequest{})
if err != nil {
return nil, unmapError(err)
}
out := make([]access.Policy, len(r.Policies))
for i := range r.Policies {
out[i] = accessPolicyValue(r.Policies[i])
}
return out, nil
}
func (c *Client) PutPolicy(ctx context.Context, p access.Policy) (int64, error) {
r, err := c.client.PutPolicy(ctx, &pb.PutPolicyRequest{Policy: accessPolicyProto(p)})
if err != nil {
return 0, unmapError(err)
}
return r.Version, nil
}
func (c *Client) DeletePolicy(ctx context.Context, p access.Policy) error {
_, err := c.client.DeletePolicy(ctx, &pb.DeletePolicyRequest{Policy: accessPolicyProto(p)})
return unmapError(err)
}
func (c *Client) EnsureShippedOrgPolicies(ctx context.Context, orgID org.OrgID) error {
_, err := c.client.EnsureShippedOrgPolicies(ctx, &pb.EnsureShippedOrgPoliciesRequest{OrgId: string(orgID)})
return unmapError(err)
}
func (c *Client) RecordDenial(ctx context.Context, d access.Denial) error {
_, err := c.client.RecordDenial(ctx, &pb.RecordDenialRequest{Denial: accessDenialProto(d)})
return unmapError(err)
}
func (c *Client) ListDenials(ctx context.Context, orgID org.OrgID, limit int) ([]access.Denial, error) {
r, err := c.client.ListDenials(ctx, &pb.ListDenialsRequest{OrgId: string(orgID), Limit: int32(limit)})
if err != nil {
return nil, unmapError(err)
}
out := make([]access.Denial, len(r.Denials))
for i := range r.Denials {
out[i] = accessDenialValue(r.Denials[i])
}
return out, nil
}
@@ -17,6 +17,7 @@ import (
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/mapping"
@@ -99,6 +100,18 @@ type Deps struct {
// (docs/prds/eda-playbook-engine.md gap 2). Optional: nil disables the
// two playbook dispatch RPCs with codes.Unavailable.
PlaybookDispatcher storecontract.PlaybookDispatcher
// Principals assembles the access principal for one identity: the org it
// serves and its memberships. Optional: nil answers GetPrincipal with
// codes.Unavailable.
Principals access.PrincipalSource
// Policies is the stored policy chain (docs/prds/orgs-and-access.md).
// Optional: nil answers the access RPCs with codes.Unavailable. The reset
// surface is deliberately not an RPC: `archied access reset` runs on the
// State Store host, never over the network.
Policies access.PolicyStore
// Denials records and lists denial records. Optional: nil disables the
// pair with codes.Unavailable.
Denials access.DenialStore
// TaskLogs reads one task attempt's persisted log out of the state
// directory this process owns. Optional, and nil is the honest default for
// a store service that shares no state directory with the daemon: