Files
archie/modules/governance/store_access.go
T

304 lines
8.5 KiB
Go

package governance
import (
"context"
"fmt"
"slices"
"time"
"github.com/samcharles93/archie-core/modules/governance/internal/store"
)
var (
_ PolicyStore = (*Module)(nil)
_ Resetter = (*Module)(nil)
_ DenialStore = (*Module)(nil)
_ DenialRecorder = (*Module)(nil)
_ DenialPruner = (*Module)(nil)
)
const (
denialPruneBatch = 10_000
defaultDenials = 100
maxDenials = 10_000
)
func shippedOrgPolicyIDs() []string {
shipped := ShippedOrgPolicies("")
ids := make([]string, 0, len(shipped))
for _, p := range shipped {
ids = append(ids, p.ID)
}
return ids
}
func policyToRow(p Policy) store.PolicyRow {
return store.PolicyRow{
Level: string(p.Level),
OrgID: string(p.OrgID),
WorkspaceID: string(p.WorkspaceID),
ObjectKind: string(p.ObjectKind),
ObjectID: p.ObjectID,
PolicyID: p.ID,
Text: p.Text,
}
}
func policyFromRow(r store.PolicyRow) Policy {
return Policy{
ID: r.PolicyID,
Level: Level(r.Level),
OrgID: OrgID(r.OrgID),
WorkspaceID: WorkspaceID(r.WorkspaceID),
ObjectKind: ResourceKind(r.ObjectKind),
ObjectID: r.ObjectID,
Text: r.Text,
}
}
// ListPolicies returns stored Cedar policies visible to the caller's scope.
func (m *Module) ListPolicies(ctx context.Context) ([]Policy, error) {
var scopeOrg *string
if id, ok := Scope(ctx); ok {
s := string(id)
scopeOrg = &s
}
rows, err := m.store.ListAccessPolicies(ctx, scopeOrg, InstanceScope(ctx))
if err != nil {
return nil, err
}
out := make([]Policy, 0, len(rows))
for _, r := range rows {
out = append(out, policyFromRow(r))
}
return out, nil
}
// PoliciesVersion returns the instance-wide monotonic policy revision.
func (m *Module) PoliciesVersion(ctx context.Context) (int64, error) {
return m.store.AccessPolicyRevision(ctx)
}
// 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 := 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 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
}
if !found {
return ErrPolicyNotFound
}
return nil
}
// EnsureShippedOrgPolicies seeds the shipped role policies when the org has none
// of them.
func (m *Module) EnsureShippedOrgPolicies(ctx context.Context, orgID OrgID) error {
return seedShippedPolicies(ctx, m.store, orgID)
}
// policySeedStore is the part of the store that seeds the shipped policies.
type policySeedStore interface {
SeedOrgPolicies(context.Context, string, []string, []store.PolicyRow) error
}
// seedShippedPolicies writes the whole shipped set in one call, so a failure
// leaves none of it behind and the next attempt writes all of it. The store
// decides whether the seed already ran; an org that has any shipped policy is
// left alone, so a deletion or an edit an admin made stands across restarts.
func seedShippedPolicies(ctx context.Context, s policySeedStore, orgID OrgID) error {
shipped := ShippedOrgPolicies(orgID)
rows := make([]store.PolicyRow, 0, len(shipped))
for _, p := range shipped {
rows = append(rows, policyToRow(p))
}
return s.SeedOrgPolicies(ctx, string(orgID), shippedOrgPolicyIDs(), rows)
}
// ResetOrgPolicies removes non-shipped org policies and restores the shipped role policies.
func (m *Module) ResetOrgPolicies(ctx context.Context, orgID OrgID) error {
if orgID == "" {
return fmt.Errorf("%w: no org", ErrInvalidPolicy)
}
if err := m.store.DeleteOrgPoliciesNotShipped(ctx, string(orgID), shippedOrgPolicyIDs()); err != nil {
return err
}
for _, p := range ShippedOrgPolicies(orgID) {
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)
}
// RecordDenial persists one coalesced access denial.
func (m *Module) RecordDenial(ctx context.Context, d Denial) error {
if d.Org == "" || d.Principal == "" {
return fmt.Errorf("%w: org and principal are required", ErrInvalidPolicy)
}
return m.store.RecordDenial(ctx, store.DenialRow{
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 (m *Module) ListDenials(ctx context.Context, orgID OrgID, limit int) ([]Denial, error) {
if limit <= 0 {
limit = defaultDenials
} else if limit > maxDenials {
limit = maxDenials
}
rows, err := m.store.ListDenials(ctx, string(orgID), limit)
if err != nil {
return nil, err
}
out := make([]Denial, 0, len(rows))
for _, r := range rows {
out = append(out, Denial{
Principal: IdentityID(r.Principal),
Org: OrgID(r.OrgID),
Action: Action(r.Action),
Kind: ResourceKind(r.ResourceKind),
ResourceID: r.ResourceID,
Level: Level(r.Level),
Policies: r.Policies,
At: r.CreatedAt,
Count: r.Count,
})
}
return out, nil
}
// PruneDenials deletes denial rows older than cutoff in bounded batches.
func (m *Module) PruneDenials(ctx context.Context, cutoff time.Time) (int64, error) {
var total int64
for {
removed, err := m.store.PruneDenials(ctx, cutoff, denialPruneBatch)
if err != nil {
return total, err
}
total += removed
if removed < denialPruneBatch {
return total, nil
}
}
}