Files
archie/modules/governance/access_test.go
T
sam 0218e4ec89 feat(governance): move identity, org and Cedar access engine into governance (#2017)
Copied from internal/domain/identity, internal/domain/org, internal/domain/access, internal/infrastructure/access and internal/infrastructure/postgres.
2026-11-18 02:09:29 +11:00

288 lines
11 KiB
Go

package governance
import (
"context"
"errors"
"log/slog"
"testing"
)
// TestInvalidInstancePolicy pins that an instance policy that no longer
// compiles closes the instance without locking the operator out: only an
// instance admin working on the policies passes, so the policy can be
// repaired from the dashboard.
func TestInvalidInstancePolicy(t *testing.T) {
broken := Policy{ID: "broken", Level: LevelInstance, Text: `permit(principal, action == Archie::Action::"nope", resource);`}
policies := append(ShippedOrgPolicies(DefaultOrgID), ShippedOrgPolicies("acme")...)
engine := NewEngine(append(policies, broken))
if len(engine.Problems()) != 1 {
t.Fatalf("problems = %v, want the broken instance policy", engine.Problems())
}
owner := func(id IdentityID, o OrgID) Principal {
return Principal{IdentityID: id, Org: o, Memberships: []Membership{{IdentityID: id, OrgID: o, Role: RoleOwner}}}
}
admin := owner("admin", DefaultOrgID)
tests := []struct {
name string
principal Principal
action Action
kind ResourceKind
allowed bool
}{
{"instance admin edits policies", admin, ActionManagePolicies, KindPolicy, true},
{"instance admin reads policies", admin, ActionRead, KindPolicy, true},
{"instance admin reads anything else", admin, ActionRead, KindDashboard, false},
{"another org's owner edits policies", owner("acme-owner", "acme"), ActionManagePolicies, KindPolicy, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := engine.Authorize(t.Context(), tt.principal, tt.action, Resource{Kind: tt.kind}, AccessContext{})
if got.Allowed != tt.allowed {
t.Fatalf("allowed = %v, want %v (%+v)", got.Allowed, tt.allowed, got)
}
})
}
}
// TestReadAuditRoleBoundary pins that the audit feed is an administrator's
// read: the dashboard's broad read grant (viewer and developer) must not open
// the instance's settings, access and identity history.
func TestReadAuditRoleBoundary(t *testing.T) {
const auditOrg = OrgID("acme")
engine := NewEngine(ShippedOrgPolicies(auditOrg))
tests := []struct {
role Role
allowed bool
}{
{RoleOwner, true},
{RoleAdmin, true},
{RoleDeveloper, false},
{RoleViewer, false},
}
for _, tt := range tests {
t.Run(string(tt.role), func(t *testing.T) {
p := Principal{
IdentityID: "person", Org: auditOrg,
Memberships: []Membership{{IdentityID: "person", OrgID: auditOrg, Role: tt.role}},
}
got := engine.Authorize(t.Context(), p, ActionReadAudit, Resource{Kind: KindAudit, Org: auditOrg}, AccessContext{})
if got.Allowed != tt.allowed {
t.Fatalf("allowed = %v, want %v (%+v)", got.Allowed, tt.allowed, got)
}
})
}
}
// TestWorkspaceEnvironment pins that a policy can read the environment of
// the workspace a resource is in: it validates on save and decides runs in
// that workspace only.
func TestWorkspaceEnvironment(t *testing.T) {
frozen := Policy{
ID: "no-prod-runs", Level: LevelOrg, OrgID: "acme",
Text: `forbid(principal, action == Archie::Action::"run", resource) when { resource.workspace.environment == "production" };`,
}
engine := NewEngine(append(ShippedOrgPolicies("acme"), frozen))
if err := engine.Validate(frozen); err != nil {
t.Fatalf("validate: %v", err)
}
dev := Principal{
IdentityID: "dev", Org: "acme",
Memberships: []Membership{{IdentityID: "dev", OrgID: "acme", Role: RoleDeveloper}},
Workspaces: []Workspace{{ID: "live", OrgID: "acme", Environment: "production"}, {ID: "stage", OrgID: "acme", Environment: "staging"}},
}
tests := []struct {
name string
action Action
workspace WorkspaceID
allowed bool
}{
{"run in a production workspace", ActionRun, "live", false},
{"other actions in it", ActionUpdate, "live", true},
{"run in another environment", ActionRun, "stage", true},
{"run on a record with no workspace", ActionRun, "", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
resource := Resource{Kind: KindWorkflow, ID: "triage", Org: "acme", Workspace: tt.workspace}
if got := engine.Authorize(t.Context(), dev, tt.action, resource, AccessContext{}); got.Allowed != tt.allowed {
t.Fatalf("allowed = %v, want %v (%+v)", got.Allowed, tt.allowed, got)
}
})
}
}
// TestPendingChainRefusesUntilLoaded pins that a chain built before its store
// is up refuses every request until the first load succeeds, then allows.
func TestPendingChainRefusesUntilLoaded(t *testing.T) {
loaded := false
live := NewPending(func(context.Context) (int64, error) {
return 1, nil
}, func(context.Context) ([]Policy, error) {
if !loaded {
return nil, errors.New("store down")
}
return nil, nil
}, slog.New(slog.DiscardHandler))
request := func() Decision {
return live.Authorize(t.Context(), SharedTokenOwner(), ActionRead,
Resource{Kind: KindDashboard}, AccessContext{})
}
if decision := request(); decision.Allowed || !errors.Is(decision.Err, ErrChainUnavailable) {
t.Fatalf("before load = %+v, want the not-loaded refusal", decision)
}
if live.Ready() {
t.Fatal("Ready before load = true, want false")
}
if got := live.Problems(); got != nil {
t.Fatalf("Problems before load = %v, want nil", got)
}
if decision := live.AuthorizeDelivery(t.Context(), "acme", "sources/x", "10.0.0.1"); decision.Allowed ||
!errors.Is(decision.Err, ErrChainUnavailable) {
t.Fatalf("delivery before load = %+v, want the not-loaded refusal", decision)
}
loaded = true
if err := live.Reload(t.Context()); err != nil {
t.Fatal(err)
}
if !live.Ready() {
t.Fatal("Ready after load = false, want true")
}
if decision := request(); !decision.Allowed {
t.Fatalf("after load = %+v, want allowed", decision)
}
}
type fakePolicyStore struct {
version int64
policies []Policy
versionErr error
listErr error
}
func (s *fakePolicyStore) PoliciesVersion(context.Context) (int64, error) {
if s.versionErr != nil {
return 0, s.versionErr
}
return s.version, nil
}
func (s *fakePolicyStore) ListPolicies(context.Context) ([]Policy, error) {
if s.listErr != nil {
return nil, s.listErr
}
return s.policies, nil
}
// TestLiveAppliesAPolicyEditBeforeTheNextDecision pins the ordering guarantee a
// policy edit gets: the next decision after a write returns is decided by the
// edited chain, and a store failure in between refuses rather than standing on
// the chain the process happens to hold.
func TestLiveAppliesAPolicyEditBeforeTheNextDecision(t *testing.T) {
forbidAll := Policy{ID: "forbid-all", Level: LevelInstance, Text: `forbid(principal, action, resource);`}
storeDown := errors.New("state store down")
request := func(live *Live) Decision {
return live.Authorize(t.Context(), SharedTokenOwner(), ActionRead,
Resource{Kind: KindDashboard}, AccessContext{})
}
tests := []struct {
name string
write func(store *fakePolicyStore)
wantAllowed bool
wantUnavailable bool
}{
{
name: "an unchanged version keeps the chain",
write: func(store *fakePolicyStore) { store.policies = []Policy{forbidAll} },
wantAllowed: true,
},
{
name: "a bumped version applies the forbid",
write: func(store *fakePolicyStore) { store.policies = []Policy{forbidAll}; store.version++ },
},
{
name: "a failed version read refuses",
write: func(store *fakePolicyStore) {
store.policies = []Policy{forbidAll}
store.version++
store.versionErr = storeDown
},
wantUnavailable: true,
},
{
name: "a failed list read after a bump refuses instead of keeping the old chain",
write: func(store *fakePolicyStore) { store.version++; store.listErr = storeDown },
wantUnavailable: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
store := &fakePolicyStore{version: 1}
live := NewPending(store.PoliciesVersion, store.ListPolicies, slog.New(slog.DiscardHandler))
if err := live.Reload(t.Context()); err != nil {
t.Fatal(err)
}
if decision := request(live); !decision.Allowed {
t.Fatalf("before the edit = %+v, want allowed so the edit is what refuses", decision)
}
tt.write(store)
decision := request(live)
if decision.Allowed != tt.wantAllowed {
t.Fatalf("after the edit = %+v, want allowed %v", decision, tt.wantAllowed)
}
if unavailable := errors.Is(decision.Err, ErrChainUnavailable); unavailable != tt.wantUnavailable {
t.Fatalf("after the edit = %+v, want unavailable %v", decision, tt.wantUnavailable)
}
})
}
}
// TestAuthorizeDelivery guards network and object policy evaluation for inbound deliveries.
func TestAuthorizeDelivery(t *testing.T) {
permitAll := Policy{ID: "all", Level: LevelInstance, Text: `permit(principal, action, resource);`}
lanOnly := Policy{ID: "lan-only", Level: LevelInstance, Text: `forbid(principal, action == Archie::Action::"deliver", resource) unless { context.addr.isInRange(ip("10.0.0.0/8")) };`}
sourceOnly := Policy{
ID: "github-only", Level: LevelObject, OrgID: DefaultOrgID, ObjectKind: KindSource, ObjectID: "github",
Text: `permit(principal, action == Archie::Action::"deliver", resource) when { context.addr.isInRange(ip("140.82.112.0/20")) };`,
}
acmeOnly := Policy{
ID: "acme-only", Level: LevelObject, OrgID: "acme", ObjectKind: KindSource, ObjectID: "hook",
Text: `permit(principal, action == Archie::Action::"deliver", resource) when { context.addr.isInRange(ip("10.0.0.0/8")) };`,
}
shipped := ShippedOrgPolicies(DefaultOrgID)
tests := []struct {
name string
org OrgID
policies []Policy
source string
addr string
allowed bool
}{
{name: "no rules admits every sender", policies: shipped, source: "github", addr: "203.0.113.9", allowed: true},
{name: "network rule admits its range", policies: append(shipped, permitAll, lanOnly), source: "ci", addr: "10.1.2.3", allowed: true},
{name: "network rule refuses outside its range", policies: append(shipped, permitAll, lanOnly), source: "ci", addr: "203.0.113.9"},
{name: "source policy refuses another sender", policies: append(shipped, sourceOnly), source: "github", addr: "203.0.113.9"},
{name: "source policy admits its sender", policies: append(shipped, sourceOnly), source: "github", addr: "140.82.112.5", allowed: true},
{name: "source policy leaves other sources alone", policies: append(shipped, sourceOnly), source: "ci", addr: "203.0.113.9", allowed: true},
{name: "other org's source policy refuses an out-of-range sender", org: "acme", policies: append(shipped, acmeOnly), source: "hook", addr: "203.0.113.9"},
{name: "other org's source policy admits its sender", org: "acme", policies: append(shipped, acmeOnly), source: "hook", addr: "10.1.2.3", allowed: true},
{name: "other org's source policy leaves the default org alone", policies: append(shipped, acmeOnly), source: "hook", addr: "203.0.113.9", allowed: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
engine := NewEngine(tt.policies)
acting := tt.org
if acting == "" {
acting = DefaultOrgID
}
if got := engine.AuthorizeDelivery(t.Context(), acting, tt.source, tt.addr); got.Allowed != tt.allowed {
t.Fatalf("allowed = %v, want %v (%+v)", got.Allowed, tt.allowed, got)
}
})
}
}