refactor(governance): open role identifiers and guard policy lockout with Cedar (#2017)
Carried policy lockout guard from internal/app/statestore/policy_guard.go.
This commit is contained in:
5 files changed
+268
-14
No files matched your search
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -285,3 +286,157 @@ func TestAuthorizeDelivery(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/stableid"
|
||||
)
|
||||
|
||||
// OrgID and WorkspaceID identify an organisation and a workspace.
|
||||
@@ -36,7 +38,7 @@ var (
|
||||
// Role is a member's role in an organisation or one of its workspaces.
|
||||
type Role string
|
||||
|
||||
// Role values carried in principal attributes and evaluated by Cedar policies.
|
||||
// Default role names used by the starter org policies seeded at org creation.
|
||||
const (
|
||||
RoleOwner Role = "owner"
|
||||
RoleAdmin Role = "admin"
|
||||
@@ -44,13 +46,12 @@ const (
|
||||
RoleViewer Role = "viewer"
|
||||
)
|
||||
|
||||
// Validate reports whether r is one of the shipped roles.
|
||||
// Validate reports whether r is a valid role identifier.
|
||||
func (r Role) Validate() error {
|
||||
switch r {
|
||||
case RoleOwner, RoleAdmin, RoleDeveloper, RoleViewer:
|
||||
return nil
|
||||
if !stableid.Valid(string(r)) {
|
||||
return fmt.Errorf("%w: %q (must match %s)", ErrInvalidRole, r, stableid.Pattern)
|
||||
}
|
||||
return fmt.Errorf("%w: %q", ErrInvalidRole, r)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Org is a tenant.
|
||||
|
||||
@@ -31,7 +31,8 @@ const orgEditPolicy = `permit(principal, action, resource) when {
|
||||
const orgAdminPolicy = `permit(principal, action, resource) when {
|
||||
resource.org == principal.org &&
|
||||
["` + roleAdmin + `", "` + roleOwner + `"].contains(principal.role) &&
|
||||
(action != Archie::Action::"delete" || resource.kind != "org")
|
||||
(action != Archie::Action::"delete" || resource.kind != "org") &&
|
||||
(resource.kind != "member" || resource.state != "` + roleOwner + `")
|
||||
};`
|
||||
|
||||
const orgOwnerPolicy = `permit(principal, action, resource) when {
|
||||
|
||||
@@ -3,6 +3,7 @@ package governance
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/modules/governance/internal/store"
|
||||
@@ -78,19 +79,30 @@ func (m *Module) PoliciesVersion(ctx context.Context) (int64, error) {
|
||||
return m.store.AccessPolicyRevision(ctx)
|
||||
}
|
||||
|
||||
// PutPolicy validates, stores or replaces p, and returns the scope's new version.
|
||||
// PutPolicy validates p against the Cedar schema, checks for lockout, stores or
|
||||
// replaces p, and returns the scope's new version.
|
||||
func (m *Module) PutPolicy(ctx context.Context, p Policy) (int64, error) {
|
||||
if err := p.Validate(); err != nil {
|
||||
if err := NewEngine(nil).Validate(p); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err := m.checkLockout(ctx, func(current []Policy) []Policy {
|
||||
return append(slices.DeleteFunc(current, func(c Policy) bool { return samePolicy(c, p) }), p)
|
||||
}); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return m.store.PutAccessPolicy(ctx, policyToRow(p))
|
||||
}
|
||||
|
||||
// DeletePolicy removes one stored policy or returns ErrPolicyNotFound.
|
||||
// DeletePolicy removes one stored policy after verifying no org is locked out.
|
||||
func (m *Module) DeletePolicy(ctx context.Context, p Policy) error {
|
||||
if err := p.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.checkLockout(ctx, func(current []Policy) []Policy {
|
||||
return slices.DeleteFunc(current, func(c Policy) bool { return samePolicy(c, p) })
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
found, err := m.store.DeleteAccessPolicy(ctx, policyToRow(p))
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -111,7 +123,7 @@ func (m *Module) EnsureShippedOrgPolicies(ctx context.Context, orgID OrgID) erro
|
||||
return nil
|
||||
}
|
||||
for _, p := range ShippedOrgPolicies(orgID) {
|
||||
if _, err := m.PutPolicy(ctx, p); err != nil {
|
||||
if _, err := m.store.PutAccessPolicy(ctx, policyToRow(p)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -127,13 +139,98 @@ func (m *Module) ResetOrgPolicies(ctx context.Context, orgID OrgID) error {
|
||||
return err
|
||||
}
|
||||
for _, p := range ShippedOrgPolicies(orgID) {
|
||||
if _, err := m.PutPolicy(ctx, p); err != nil {
|
||||
if _, err := m.store.PutAccessPolicy(ctx, policyToRow(p)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CheckPolicyChange evaluates a candidate policy change against the Cedar schema
|
||||
// and ensures every org with members still has at least one principal permitted
|
||||
// to manage policies.
|
||||
func CheckPolicyChange(
|
||||
ctx context.Context,
|
||||
current []Policy,
|
||||
change func([]Policy) []Policy,
|
||||
orgs []Org,
|
||||
principalsForOrg func(context.Context, OrgID) ([]Principal, error),
|
||||
) error {
|
||||
engine := NewEngine(change(slices.Clone(current)))
|
||||
for _, o := range orgs {
|
||||
principals, err := principalsForOrg(ctx, o.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if o.ID == DefaultOrgID {
|
||||
principals = append([]Principal{SharedTokenOwner()}, principals...)
|
||||
}
|
||||
if len(principals) == 0 {
|
||||
continue
|
||||
}
|
||||
if !anyCanManagePolicies(ctx, engine, o.ID, principals) {
|
||||
return ErrPolicyLockout
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func anyCanManagePolicies(ctx context.Context, engine *Engine, orgID OrgID, principals []Principal) bool {
|
||||
resource := Resource{Kind: KindPolicy, Org: orgID}
|
||||
for _, principal := range principals {
|
||||
if engine.Authorize(ctx, principal, ActionManagePolicies, resource, AccessContext{}).Allowed {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (m *Module) checkLockout(ctx context.Context, change func([]Policy) []Policy) error {
|
||||
current, err := m.ListPolicies(WithoutScope(ctx))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
orgs, err := m.ListOrgs(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return CheckPolicyChange(ctx, current, change, orgs, m.activeOrgPrincipals)
|
||||
}
|
||||
|
||||
func (m *Module) activeOrgPrincipals(ctx context.Context, orgID OrgID) ([]Principal, error) {
|
||||
members, err := m.ListMembers(ctx, orgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
seen := make(map[IdentityID]bool, len(members))
|
||||
principals := make([]Principal, 0, len(members))
|
||||
for _, member := range members {
|
||||
if seen[member.IdentityID] {
|
||||
continue
|
||||
}
|
||||
seen[member.IdentityID] = true
|
||||
id, err := m.store.GetIdentity(ctx, string(member.IdentityID))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if id.Lifecycle != string(LifecycleActive) {
|
||||
continue
|
||||
}
|
||||
p, err := m.PrincipalFor(ctx, member.IdentityID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.Org = orgID
|
||||
principals = append(principals, p)
|
||||
}
|
||||
return principals, nil
|
||||
}
|
||||
|
||||
func samePolicy(a, b Policy) bool {
|
||||
return a.ID == b.ID && a.Level == b.Level && a.OrgID == b.OrgID &&
|
||||
a.WorkspaceID == b.WorkspaceID && a.ObjectKind == b.ObjectKind && a.ObjectID == b.ObjectID
|
||||
}
|
||||
|
||||
// ResetInstancePolicies deletes every stored instance policy.
|
||||
func (m *Module) ResetInstancePolicies(ctx context.Context) error {
|
||||
return m.store.ResetInstancePolicies(ctx)
|
||||
|
||||
@@ -400,8 +400,8 @@ func registrationScope(ctx context.Context, r *AccountRegistration, bootstrap bo
|
||||
return "", "", ErrCredentialRejected
|
||||
}
|
||||
role := Role(r.Role)
|
||||
if role != RoleAdmin && role != RoleDeveloper && role != RoleViewer {
|
||||
return "", "", ErrInvalidIdentity
|
||||
if err := role.Validate(); err != nil {
|
||||
return "", "", fmt.Errorf("%w: %w", ErrInvalidIdentity, err)
|
||||
}
|
||||
return role, orgID, nil
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user