Files
archie/modules/governance/access.go
T
sam 073959b4f9 feat(memory): scope chat notes and preserve deletions on restore (#2069)
Keep personal notes private by default and require review before publishing shared notes. Restore backups and replay forgotten notes in one transaction, and retain the installed release when an unattended rollback could bring back forgotten notes.
2026-11-21 13:20:31 +11:00

462 lines
14 KiB
Go

package governance
import (
"context"
"errors"
"fmt"
"slices"
"strings"
"time"
)
// Level is one level of the policy chain. A level's policies govern the
// requests the levels below it see: a lower level narrows and never widens.
type Level string
const (
// LevelInstance holds across every org.
LevelInstance Level = "instance"
// LevelOrg is an org's policies, including the shipped role policies.
LevelOrg Level = "org"
// LevelWorkspace is one workspace's stored policies.
LevelWorkspace Level = "workspace"
// LevelObject attaches to one object.
LevelObject Level = "object"
)
// Validate reports whether l is one of the stored levels.
func (l Level) Validate() error {
switch l {
case LevelInstance, LevelOrg, LevelWorkspace, LevelObject:
return nil
}
return fmt.Errorf("%w: %q", ErrInvalidLevel, l)
}
// Action is the access vocabulary: what a principal may do to a resource.
type Action string
const (
ActionRead Action = "read"
ActionCreate Action = "create"
ActionUpdate Action = "update"
ActionDelete Action = "delete"
ActionApprove Action = "approve"
ActionRun Action = "run"
ActionDeliver Action = "deliver"
ActionReadLogs Action = "read_logs"
ActionReadSecret Action = "read_secret"
ActionManageMembers Action = "manage_members"
ActionManageIdentities Action = "manage_identities"
ActionManagePolicies Action = "manage_policies"
ActionReadAudit Action = "read_audit"
ActionReadUsage Action = "read_usage"
)
// Actions returns every action in vocabulary order.
func Actions() []Action {
return []Action{
ActionRead, ActionCreate, ActionUpdate, ActionDelete, ActionApprove,
ActionRun, ActionDeliver, ActionReadLogs, ActionReadSecret,
ActionManageMembers, ActionManageIdentities, ActionManagePolicies,
ActionReadAudit, ActionReadUsage,
}
}
// Validate reports whether a is one of the shipped actions.
func (a Action) Validate() error {
if slices.Contains(Actions(), a) {
return nil
}
return fmt.Errorf("%w: %q", ErrInvalidAction, a)
}
// ResourceKind is what a resource record is in the policy vocabulary.
type ResourceKind string
const (
KindOrg ResourceKind = "org"
KindWorkspace ResourceKind = "workspace"
KindSource ResourceKind = "source"
KindEventType ResourceKind = "event_type"
KindMapping ResourceKind = "mapping"
KindBinding ResourceKind = "binding"
KindWorkflow ResourceKind = "workflow"
KindTask ResourceKind = "task"
KindCapture ResourceKind = "capture"
KindSecret ResourceKind = "secret"
KindIdentity ResourceKind = "identity"
KindPolicy ResourceKind = "policy"
KindMember ResourceKind = "member"
KindSchedule ResourceKind = "schedule"
KindDashboard ResourceKind = "dashboard"
KindEventIngest ResourceKind = "event"
KindAudit ResourceKind = "audit"
KindConnector ResourceKind = "connector"
KindGuard ResourceKind = "guard"
KindSecretEngine ResourceKind = "secret_engine"
KindMCPServer ResourceKind = "mcp_server"
KindTrigger ResourceKind = "trigger"
KindGroup ResourceKind = "group"
KindRun ResourceKind = "run"
KindApproval ResourceKind = "approval"
KindClass ResourceKind = "class"
KindDraft ResourceKind = "draft"
KindDelivery ResourceKind = "delivery"
KindIncident ResourceKind = "incident"
KindMemory ResourceKind = "memory"
KindSettings ResourceKind = "settings"
KindInstance ResourceKind = "instance"
)
// Policy is one stored Cedar policy.
type Policy struct {
ID string `json:"id"`
Level Level `json:"level"`
OrgID OrgID `json:"org_id,omitempty"`
WorkspaceID WorkspaceID `json:"workspace_id,omitempty"`
ObjectKind ResourceKind `json:"object_kind,omitempty"`
ObjectID string `json:"object_id,omitempty"`
Text string `json:"text"`
}
// Validate checks a policy's structural shape.
func (p Policy) Validate() error {
if err := p.validateScope(); err != nil {
return err
}
if strings.TrimSpace(p.Text) == "" {
return fmt.Errorf("%w: no text", ErrInvalidPolicy)
}
return nil
}
func (p Policy) validateScope() error {
if strings.TrimSpace(p.ID) == "" {
return fmt.Errorf("%w: no ID", ErrInvalidPolicy)
}
if err := p.Level.Validate(); err != nil {
return err
}
if strings.Contains(string(p.OrgID), "/") || strings.Contains(string(p.WorkspaceID), "/") {
return fmt.Errorf("%w: org and workspace IDs must not contain a slash", ErrInvalidPolicy)
}
switch p.Level {
case LevelInstance:
case LevelOrg:
if p.OrgID == "" {
return fmt.Errorf("%w: org policy carries no org", ErrInvalidPolicy)
}
case LevelWorkspace:
if p.OrgID == "" || p.WorkspaceID == "" {
return fmt.Errorf("%w: workspace policy carries no org or workspace", ErrInvalidPolicy)
}
case LevelObject:
if p.OrgID == "" || p.ObjectKind == "" || p.ObjectID == "" {
return fmt.Errorf("%w: object policy carries no org, kind or ID", ErrInvalidPolicy)
}
}
return nil
}
// Governs reports whether p attaches to the level and scope of r.
func (p Policy) Governs(r Resource) bool {
if p.Level != LevelInstance && p.OrgID != r.Org {
return false
}
switch p.Level {
case LevelWorkspace, LevelObject:
if p.WorkspaceID != r.Workspace {
return false
}
}
if p.Level == LevelObject && (p.ObjectKind != r.Kind || p.ObjectID != r.ID) {
return false
}
return true
}
var (
ErrInvalidLevel = errors.New("access: invalid level")
ErrInvalidAction = errors.New("access: invalid action")
ErrInvalidPolicy = errors.New("access: invalid policy")
ErrPolicyNotFound = errors.New("access: policy not found")
ErrPolicyInvalidText = errors.New("access: policy text does not parse")
ErrPolicyLockout = errors.New("access: change leaves no owner able to manage policies")
ErrChainUnavailable = errors.New("access: policy chain not loaded")
ErrNotMember = errors.New("not a member of that org")
)
const (
Namespace = "Archie"
EntityTypeIdentity = Namespace + "::Identity"
EntityTypeOrg = Namespace + "::Org"
EntityTypeWorkspace = Namespace + "::Workspace"
EntityTypeObject = Namespace + "::Object"
EntityTypeAction = Namespace + "::Action"
AttributeOrg = "org"
AttributeRole = "role"
AttributeKind = "kind"
AttributeOwner = "owner"
AttributeState = "state"
)
// Principal is who acts: an identity with the memberships that give it roles.
type Principal struct {
IdentityID IdentityID
Kind Kind
Org OrgID
Memberships []Membership
Workspaces []Workspace
}
// Environment returns the environment of ws in the principal's org.
func (p Principal) Environment(ws WorkspaceID) string {
for _, w := range p.Workspaces {
if w.ID == ws {
return w.Environment
}
}
return ""
}
// Role returns the principal's effective role for a resource: the workspace
// membership role when one exists, else the org-wide membership role.
func (p Principal) Role(ws WorkspaceID) Role {
var orgRole Role
for _, m := range p.Memberships {
if m.OrgID != p.Org {
continue
}
if m.WorkspaceID == "" {
orgRole = m.Role
}
if m.WorkspaceID == ws {
return m.Role
}
}
return orgRole
}
// RoleIn returns the principal's org-wide role in id, or "" when it holds no
// org-wide membership there. A workspace membership does not count.
func (p Principal) RoleIn(id OrgID) Role {
for _, m := range p.Memberships {
if m.OrgID == id && m.WorkspaceID == "" {
return m.Role
}
}
return ""
}
// InstanceAdmin reports whether the principal owns the default operating org.
func (p Principal) InstanceAdmin() bool {
for _, m := range p.Memberships {
if m.OrgID == DefaultOrgID && m.WorkspaceID == "" && m.Role == RoleOwner {
return true
}
}
return false
}
// WorkspaceLister reads an org's workspaces.
type WorkspaceLister interface {
ListWorkspaces(context.Context, OrgID) ([]Workspace, error)
}
// Select returns the principal acting in org id, refusing non-members.
func (p Principal) Select(ctx context.Context, id OrgID, workspaces WorkspaceLister) (Principal, error) {
if id == "" || id == p.Org {
return p, nil
}
if !p.Member(id) {
return Principal{}, ErrNotMember
}
if workspaces == nil {
return Principal{}, errors.New("org selection unavailable")
}
list, err := workspaces.ListWorkspaces(ctx, id)
if err != nil {
return Principal{}, err
}
p.Org, p.Workspaces = id, list
return p, nil
}
// Member reports whether the principal holds any membership in org id.
func (p Principal) Member(id OrgID) bool {
for _, m := range p.Memberships {
if m.OrgID == id {
return true
}
}
return false
}
// SharedTokenOwner is the principal the single-operator shared token acts as.
func SharedTokenOwner() Principal {
return Principal{
IdentityID: SystemID,
Kind: KindSystem,
Org: DefaultOrgID,
Memberships: []Membership{{IdentityID: SystemID, OrgID: DefaultOrgID, Role: RoleOwner}},
}
}
// Resource is the record acted on.
type Resource struct {
Kind ResourceKind
ID string
Org OrgID
Workspace WorkspaceID
Owner IdentityID
State string
}
// AccessContext carries request attributes evaluated by Cedar conditions.
type AccessContext struct {
Signature string
Addr string
Time time.Time
Run string
Step string
}
// Decision is the outcome of one Authorize call.
type Decision struct {
Allowed bool
Level Level
Policies []string
Err error
}
// Allowed returns a permit decision.
func Allowed() Decision { return Decision{Allowed: true} }
// Unavailable returns an availability refusal when the policy chain is not loaded.
func Unavailable() Decision {
return Decision{Level: LevelInstance, Err: ErrChainUnavailable}
}
// DeniedAt returns a denial decided at level by the named policies.
func DeniedAt(level Level, policies []string) Decision {
return Decision{Level: level, Policies: policies}
}
// PrincipalSource assembles the Principal for an identity.
type PrincipalSource interface {
PrincipalFor(context.Context, IdentityID) (Principal, error)
}
// Denial is one recorded access refusal.
type Denial struct {
Principal IdentityID `json:"principal"`
Org OrgID `json:"org"`
Action Action `json:"action"`
Kind ResourceKind `json:"kind"`
ResourceID string `json:"resource"`
Level Level `json:"level"`
Policies []string `json:"policies"`
At time.Time `json:"at"`
Count int64 `json:"count"`
}
// Authorizer evaluates the policy chain for a request.
type Authorizer interface {
Authorize(ctx context.Context, p Principal, a Action, r Resource, c AccessContext) Decision
}
// Validator checks a policy's Cedar syntax and entity vocabulary.
type Validator interface {
Validate(p Policy) error
}
// SenderID is the principal an inbound event's sender is evaluated as.
const SenderID IdentityID = "sender"
// DeliveryAuthorizer decides whether an address may deliver an event to a source.
type DeliveryAuthorizer interface {
AuthorizeDelivery(ctx context.Context, orgID OrgID, sourcePath, addr string) Decision
}
// PolicyStore persists stored Cedar policies and their instance-wide revision.
type PolicyStore interface {
ListPolicies(ctx context.Context) ([]Policy, error)
PoliciesVersion(ctx context.Context) (int64, error)
PutPolicy(ctx context.Context, p Policy) (int64, error)
DeletePolicy(ctx context.Context, p Policy) error
EnsureShippedOrgPolicies(ctx context.Context, orgID OrgID) error
}
// Resetter restores access for a locked-out org or broken instance policy.
type Resetter interface {
ResetOrgPolicies(ctx context.Context, orgID OrgID) error
ResetInstancePolicies(ctx context.Context) error
}
// DenialRecorder records one access refusal.
type DenialRecorder interface {
RecordDenial(ctx context.Context, d Denial) error
}
// DenialStore records and lists coalesced denial records.
type DenialStore interface {
DenialRecorder
ListDenials(ctx context.Context, orgID OrgID, limit int) ([]Denial, error)
}
// DenialPruner deletes denial records older than a cutoff.
type DenialPruner interface {
PruneDenials(ctx context.Context, cutoff time.Time) (int64, error)
}
type (
actorContextKey struct{}
sourceContextKey struct{}
principalContextKey struct{}
)
// WithActor attaches the caller name recorded in audit rows.
func WithActor(ctx context.Context, actor string) context.Context {
return context.WithValue(ctx, actorContextKey{}, actor)
}
// ActorFromContext returns the caller WithActor attached, or "unknown".
func ActorFromContext(ctx context.Context) string {
if actor, ok := ctx.Value(actorContextKey{}).(string); ok && actor != "" {
return actor
}
return "unknown"
}
// WithSource attaches the surface a call came through.
func WithSource(ctx context.Context, source string) context.Context {
return context.WithValue(ctx, sourceContextKey{}, source)
}
// SourceFromContext returns the surface WithSource attached, or "unknown".
func SourceFromContext(ctx context.Context) string {
if source, ok := ctx.Value(sourceContextKey{}).(string); ok && source != "" {
return source
}
return "unknown"
}
// WithPrincipal attaches the Principal a request acts as.
func WithPrincipal(ctx context.Context, p Principal) context.Context {
return context.WithValue(ctx, principalContextKey{}, p)
}
// WithoutPrincipal drops the Principal from ctx so background checks run as
// the service itself.
func WithoutPrincipal(ctx context.Context) context.Context {
return context.WithValue(ctx, principalContextKey{}, nil)
}
// PrincipalFromContext returns the Principal WithPrincipal attached.
func PrincipalFromContext(ctx context.Context) (Principal, bool) {
p, ok := ctx.Value(principalContextKey{}).(Principal)
return p, ok
}