Files
archie/modules/governance/access_test.go
T
sam 6c59d6b742 feat(httpapi): refuse every API operation that does not declare its access (#2078)
Operations register through httpapi.Register with Public, Authorized or
AdminAuthorized, and the guard asks the policy chain for the declared
action and resource kind before the handler runs. An undeclared operation
and an undecidable chain are refused. The workload principal, its shipped
policy, a self-service policy and Recording for denials are added in
governance.
2026-11-22 02:15:02 +11:00

499 lines
18 KiB
Go

package governance
import (
"context"
"errors"
"log/slog"
"slices"
"testing"
"github.com/samcharles93/archie-core/modules/governance/internal/store"
)
// 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)
}
})
}
}
// TestPolicyGuard pins that policy edits validate against the Cedar schema and
// refuse any change that leaves an org without an active member permitted to
// manage policies, regardless of role name.
func TestPolicyGuard(t *testing.T) {
const testOrg = OrgID("org-sys")
const customOrg = OrgID("acme")
shipped := ShippedOrgPolicies(testOrg)
orgPolicy := func(orgID OrgID, id, text string) Policy {
return Policy{ID: id, Level: LevelOrg, OrgID: orgID, Text: text}
}
sreReadPolicy := orgPolicy(customOrg, "sre-read", `permit(principal, action == Archie::Action::"read", resource) when {
resource.org == principal.org &&
principal.role == "sre"
};`)
srePolicy := orgPolicy(customOrg, "sre-manage", `permit(principal, action, resource) when {
resource.org == principal.org &&
principal.role == "sre"
};`)
basePolicies := append(slices.Clone(shipped), sreReadPolicy, srePolicy)
principals := func(_ context.Context, id OrgID) ([]Principal, error) {
switch id {
case testOrg:
return []Principal{{
IdentityID: "sam", Org: testOrg,
Memberships: []Membership{{IdentityID: "sam", OrgID: testOrg, Role: RoleOwner}},
}}, nil
case customOrg:
return []Principal{{
IdentityID: "pat", Org: customOrg,
Memberships: []Membership{{IdentityID: "pat", OrgID: customOrg, Role: Role("sre")}},
}}, nil
}
return nil, nil
}
orgs := []Org{{ID: testOrg}, {ID: customOrg}}
tests := []struct {
name string
put *Policy
delete *Policy
want error
}{
{
name: "harmless addition",
put: new(orgPolicy(testOrg, "viewers-read", `permit(principal, action == Archie::Action::"read", resource);`)),
},
{
name: "text that does not compile",
put: new(orgPolicy(testOrg, "broken", `permit(principal, action == Archie::Action::"nope", resource);`)),
want: ErrPolicyInvalidText,
},
{
name: "forbid locks owners out",
put: new(orgPolicy(testOrg, "lock", `forbid(principal, action == Archie::Action::"manage_policies", resource);`)),
want: ErrPolicyLockout,
},
{
name: "deleting the owner policy while the admin policy still covers owners",
delete: &shipped[3],
},
{
name: "deleting the read policy",
delete: &shipped[0],
},
{
name: "custom role org keeps manage_policies on harmless edit",
put: new(orgPolicy(customOrg, "sre-logs", `permit(principal, action == Archie::Action::"read_logs", resource);`)),
},
{
name: "deleting the custom role policy locks out custom role org",
delete: &srePolicy,
want: ErrPolicyLockout,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var err error
if tt.put != nil {
err = NewEngine(nil).Validate(*tt.put)
if err == nil {
p := *tt.put
err = CheckPolicyChange(t.Context(), basePolicies, func(cur []Policy) []Policy {
return append(slices.DeleteFunc(cur, func(c Policy) bool { return samePolicy(c, p) }), p)
}, orgs, principals)
}
} else {
d := *tt.delete
err = CheckPolicyChange(t.Context(), basePolicies, func(cur []Policy) []Policy {
return slices.DeleteFunc(cur, func(c Policy) bool { return samePolicy(c, d) })
}, orgs, principals)
}
if !errors.Is(err, tt.want) {
t.Fatalf("err = %v, want %v", err, tt.want)
}
})
}
}
// TestCustomRoleAndMemberStatePolicy pins that Role accepts any stable
// identifier and that starter admin vs owner member management boundaries live
// in the Cedar policy rather than Go code.
func TestCustomRoleAndMemberStatePolicy(t *testing.T) {
for _, tc := range []struct {
role Role
valid bool
}{
{Role("sre"), true},
{Role("secops"), true},
{Role("on-call.lead"), true},
{Role("Admin"), false},
{Role("bad/role"), false},
{Role(""), false},
} {
err := tc.role.Validate()
if (err == nil) != tc.valid {
t.Fatalf("Role(%q).Validate() = %v, want valid=%v", tc.role, err, tc.valid)
}
if !tc.valid && !errors.Is(err, ErrInvalidRole) {
t.Fatalf("Role(%q).Validate() = %v, want ErrInvalidRole", tc.role, err)
}
}
const acme = OrgID("acme")
engine := NewEngine(ShippedOrgPolicies(acme))
principal := func(id IdentityID, role Role) Principal {
return Principal{
IdentityID: id,
Org: acme,
Memberships: []Membership{{IdentityID: id, OrgID: acme, Role: role}},
}
}
tests := []struct {
name string
role Role
target string
wantAllow bool
}{
{"admin grants developer", RoleAdmin, string(RoleDeveloper), true},
{"admin cannot grant owner", RoleAdmin, string(RoleOwner), false},
{"owner grants developer", RoleOwner, string(RoleDeveloper), true},
{"owner grants owner", RoleOwner, string(RoleOwner), true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
res := Resource{Kind: KindMember, Org: acme, State: tt.target}
got := engine.Authorize(t.Context(), principal("actor", tt.role), ActionManageMembers, res, AccessContext{})
if got.Allowed != tt.wantAllow {
t.Fatalf("allowed = %v, want %v (%+v)", got.Allowed, tt.wantAllow, got)
}
})
}
}
// fakePolicySeed records the one atomic seed the module asks for.
type fakePolicySeed struct {
calls int
ids []string
rows []store.PolicyRow
err error
// later holds the policy IDs of every seed after the first.
later []string
}
func (f *fakePolicySeed) SeedOrgPolicies(_ context.Context, _ string, shippedIDs []string, rows []store.PolicyRow) error {
f.calls++
if f.calls == 1 {
f.ids, f.rows = shippedIDs, rows
} else {
f.later = append(f.later, shippedIDs...)
}
return f.err
}
// TestSeedShippedPolicies guards that the role policies are written in one call
// rather than one policy at a time, which is what left an org holding only some
// of them, and that each later shipped policy is seeded on its own so an org
// seeded before it existed still receives it. The transaction, the zero-count check under the lock and
// how deletions and edits survive are proven against Postgres in the binary's
// smoke test.
func TestSeedShippedPolicies(t *testing.T) {
seeder := &fakePolicySeed{}
if err := seedShippedPolicies(t.Context(), seeder, DefaultOrgID); err != nil {
t.Fatalf("seed: %v", err)
}
shipped := ShippedRolePolicies(DefaultOrgID)
extras := shippedExtraPolicies(DefaultOrgID)
if seeder.calls != 1+len(extras) {
t.Fatalf("seed calls = %d, want the role policies in one call and %d more", seeder.calls, len(extras))
}
for i, p := range extras {
if seeder.later[i] != p.ID {
t.Fatalf("later seed %d = %s, want %s", i, seeder.later[i], p.ID)
}
}
if len(seeder.rows) != len(shipped) || len(seeder.ids) != len(shipped) {
t.Fatalf("seeded %d rows and %d ids, want %d of each", len(seeder.rows), len(seeder.ids), len(shipped))
}
for i, p := range shipped {
if seeder.rows[i].PolicyID != p.ID || seeder.ids[i] != p.ID {
t.Fatalf("row %d = %s, want %s", i, seeder.rows[i].PolicyID, p.ID)
}
}
if err := seedShippedPolicies(t.Context(), &fakePolicySeed{err: errors.New("connection reset by peer")}, DefaultOrgID); err == nil {
t.Fatal("a failed seed returned no error")
}
}