package governance import ( "context" "fmt" "slices" "time" "github.com/samcharles93/archie-core/modules/governance/internal/store" ) var ( _ PolicyStore = (*Module)(nil) _ Resetter = (*Module)(nil) _ DecisionStore = (*Module)(nil) _ DecisionRecorder = (*Module)(nil) _ DecisionPruner = (*Module)(nil) ) const ( decisionPruneBatch = 10_000 defaultDecisions = 100 maxDecisions = 10_000 ) func shippedOrgPolicyIDs() []string { shipped := ShippedOrgPolicies("") ids := make([]string, 0, len(shipped)) for _, p := range shipped { ids = append(ids, p.ID) } return ids } // IsShippedPolicy reports whether p is one of the org policies Archie ships. // Shipped policies are the base the system runs on, and an org with no active // org policy denies every request, so they are edited and never deleted. func IsShippedPolicy(p Policy) bool { return p.Level == LevelOrg && slices.Contains(shippedOrgPolicyIDs(), p.ID) } 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. // A shipped policy is refused with ErrPolicyShipped. func (m *Module) DeletePolicy(ctx context.Context, p Policy) error { if err := p.Validate(); err != nil { return err } if IsShippedPolicy(p) { return ErrPolicyShipped } 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; a shipped policy that is present is // never rewritten, so an admin's edits persist across restarts. Shipped // policies cannot be deleted, so seeding only fills in policies the org lacks. // // The later shipped policies are seeded one by one, so an org that was seeded // before they existed still receives them. func seedShippedPolicies(ctx context.Context, s policySeedStore, orgID OrgID) error { roles := ShippedRolePolicies(orgID) rows := make([]store.PolicyRow, 0, len(roles)) ids := make([]string, 0, len(roles)) for _, p := range roles { rows = append(rows, policyToRow(p)) ids = append(ids, p.ID) } if err := s.SeedOrgPolicies(ctx, string(orgID), ids, rows); err != nil { return err } for _, p := range shippedExtraPolicies(orgID) { if err := s.SeedOrgPolicies(ctx, string(orgID), []string{p.ID}, []store.PolicyRow{policyToRow(p)}); err != nil { return err } } return nil } // 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) } // RecordDecision persists one coalesced access decision, allowed or denied. func (m *Module) RecordDecision(ctx context.Context, d DecisionRecord) error { if d.Org == "" || d.Principal == "" { return fmt.Errorf("%w: org and principal are required", ErrInvalidPolicy) } if d.Outcome != OutcomeAllowed && d.Outcome != OutcomeDenied { return fmt.Errorf("%w: unknown outcome %q", ErrInvalidPolicy, d.Outcome) } return m.store.RecordDecision(ctx, store.DecisionRow{ OrgID: string(d.Org), Principal: string(d.Principal), Action: string(d.Action), ResourceKind: string(d.Kind), ResourceID: d.ResourceID, Outcome: string(d.Outcome), Level: string(d.Level), Policies: d.Policies, }) } // ListDecisions returns an org's most recent decisions, newest first. func (m *Module) ListDecisions(ctx context.Context, orgID OrgID, limit int) ([]DecisionRecord, error) { return m.SearchDecisions(ctx, DecisionQuery{Org: orgID, Limit: limit}) } // DecisionQuery narrows SearchDecisions. A zero field matches everything. type DecisionQuery struct { Org OrgID Principal IdentityID Action Action Kind ResourceKind Outcome Outcome Since time.Time Until time.Time Limit int Offset int } // SearchDecisions returns the decisions matching q, newest first, at most // maxDecisions per call. func (m *Module) SearchDecisions(ctx context.Context, q DecisionQuery) ([]DecisionRecord, error) { if q.Limit <= 0 { q.Limit = defaultDecisions } else if q.Limit > maxDecisions { q.Limit = maxDecisions } rows, err := m.store.SearchDecisions(ctx, store.DecisionFilter{ OrgID: string(q.Org), Principal: string(q.Principal), Action: string(q.Action), ResourceKind: string(q.Kind), Outcome: string(q.Outcome), Since: q.Since, Until: q.Until, Limit: q.Limit, Offset: max(q.Offset, 0), }) if err != nil { return nil, err } return decisionsFromRows(rows), nil } func decisionsFromRows(rows []store.DecisionRow) []DecisionRecord { out := make([]DecisionRecord, 0, len(rows)) for _, r := range rows { out = append(out, DecisionRecord{ Principal: IdentityID(r.Principal), Org: OrgID(r.OrgID), Action: Action(r.Action), Kind: ResourceKind(r.ResourceKind), ResourceID: r.ResourceID, Outcome: Outcome(r.Outcome), Level: Level(r.Level), Policies: r.Policies, At: r.CreatedAt, Count: r.Count, }) } return out } // PruneDecisions deletes decision rows older than cutoff in bounded batches. func (m *Module) PruneDecisions(ctx context.Context, cutoff time.Time) (int64, error) { var total int64 for { removed, err := m.store.PruneDecisions(ctx, cutoff, decisionPruneBatch) if err != nil { return total, err } total += removed if removed < decisionPruneBatch { return total, nil } } }