diff --git a/go.mod b/go.mod index 1e74e03c4..1f5a6c899 100644 --- a/go.mod +++ b/go.mod @@ -94,6 +94,7 @@ require ( cel.dev/cel-go v0.32.0 code.gitea.io/sdk/gitea v0.25.1 github.com/BurntSushi/toml v1.6.0 + github.com/cedar-policy/cedar-go v1.8.0 github.com/coreos/go-oidc/v3 v3.21.0 github.com/docker/sandbox-kit-spec/v3 v3.0.0-m.6 github.com/go-git/go-billy/v6 v6.0.0-alpha.2 diff --git a/go.sum b/go.sum index 09836e4da..9f075c6a8 100644 --- a/go.sum +++ b/go.sum @@ -26,6 +26,8 @@ github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYW github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= +github.com/cedar-policy/cedar-go v1.8.0 h1:9gcU7EHXwHC2RMdpph68yTAkdB3behTTssC+kt4GoS8= +github.com/cedar-policy/cedar-go v1.8.0/go.mod h1:h5+3CVW1oI5LXVskJG+my9TFCYI5yjh/+Ul3EJie6MI= github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= diff --git a/internal/domain/access/roles.go b/internal/domain/access/roles.go index f2e46a704..2b5497de1 100644 --- a/internal/domain/access/roles.go +++ b/internal/domain/access/roles.go @@ -31,31 +31,35 @@ const ( // 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 +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"];` + ["` + roleViewer + `", "` + roleDeveloper + `", "` + roleAdmin + `", "` + roleOwner + `"].contains(principal.role) && + 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 +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"];` + ["` + roleDeveloper + `", "` + roleAdmin + `", "` + roleOwner + `"].contains(principal.role) && + 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 +const orgAdminPolicy = `permit(principal, action, resource) when { resource.org == principal.org && - principal.role in ["` + roleAdmin + `", "` + roleOwner + `"] && - (action != Archie::Action::"delete" || resource.kind != "org");` + ["` + roleAdmin + `", "` + roleOwner + `"].contains(principal.role) && + (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 +const orgOwnerPolicy = `permit(principal, action, resource) when { resource.org == principal.org && - principal.role == "` + roleOwner + `";` + 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. @@ -77,5 +81,6 @@ const CrossOrgForbidID = PolicyCrossOrgID // 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;` +const CrossOrgForbidText = `forbid(principal, action, resource) when { + resource.org != principal.org; +};` diff --git a/internal/infrastructure/access/engine.go b/internal/infrastructure/access/engine.go new file mode 100644 index 000000000..460b8c3de --- /dev/null +++ b/internal/infrastructure/access/engine.go @@ -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 +} diff --git a/internal/infrastructure/access/engine_test.go b/internal/infrastructure/access/engine_test.go new file mode 100644 index 000000000..c852ff4ed --- /dev/null +++ b/internal/infrastructure/access/engine_test.go @@ -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) + } + } +} diff --git a/internal/infrastructure/access/entities.go b/internal/infrastructure/access/entities.go new file mode 100644 index 000000000..e79bcbfef --- /dev/null +++ b/internal/infrastructure/access/entities.go @@ -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 +}