diff --git a/internal/platform/pg/migrations/00035_governance_access.sql b/internal/platform/pg/migrations/00035_governance_access.sql new file mode 100644 index 000000000..fc0fcb637 --- /dev/null +++ b/internal/platform/pg/migrations/00035_governance_access.sql @@ -0,0 +1,211 @@ +-- +goose Up +-- Free governance.identities for the persistent identity table while keeping +-- the existing people-to-channel-identity table working until later slices +-- retire it. +ALTER TABLE governance.identities RENAME TO person_identities; +ALTER INDEX governance.identities_pkey RENAME TO person_identities_pkey; +ALTER TABLE governance.person_identities + RENAME CONSTRAINT identities_person_id_fkey TO person_identities_person_id_fkey; + +CREATE TABLE governance.identities ( + id text PRIMARY KEY, + kind text NOT NULL, + display_name text NOT NULL, + lifecycle text NOT NULL, + version bigint NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE governance.identity_aliases ( + alias text PRIMARY KEY, + identity_id text NOT NULL REFERENCES governance.identities (id) +); +CREATE UNIQUE INDEX idx_governance_identity_aliases_alias + ON governance.identity_aliases (lower(alias)); + +CREATE TABLE governance.identity_events ( + id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + identity_id text NOT NULL, + event_type text NOT NULL, + from_lifecycle text NOT NULL, + to_lifecycle text NOT NULL, + display_name text NOT NULL, + actor_id text NOT NULL, + source text NOT NULL, + request_id text NOT NULL UNIQUE, + at timestamptz NOT NULL, + org_id text CHECK (org_id IS NULL OR org_id <> '') +); +CREATE INDEX idx_governance_identity_events_identity + ON governance.identity_events (identity_id, id); +CREATE INDEX idx_governance_identity_events_org_at + ON governance.identity_events (org_id, at DESC, id DESC); + +CREATE TABLE governance.identity_subjects ( + issuer text NOT NULL, + subject text NOT NULL, + identity_id text NOT NULL REFERENCES governance.identities (id), + bound_at timestamptz NOT NULL, + name text NOT NULL DEFAULT '', + expires_at timestamptz, + last_used_at timestamptz, + PRIMARY KEY (issuer, subject) +); +CREATE INDEX idx_governance_identity_subjects_identity + ON governance.identity_subjects (identity_id); + +CREATE TABLE governance.orgs ( + id text PRIMARY KEY, + name text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE governance.workspaces ( + id text NOT NULL, + org_id text NOT NULL REFERENCES governance.orgs (id), + name text NOT NULL, + environment text NOT NULL DEFAULT '', + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (org_id, id) +); + +CREATE TABLE governance.memberships ( + identity_id text NOT NULL REFERENCES governance.identities (id), + org_id text NOT NULL REFERENCES governance.orgs (id), + workspace_id text, + role text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); +CREATE UNIQUE INDEX idx_governance_memberships_identity + ON governance.memberships (identity_id, org_id, COALESCE(workspace_id, '')); +CREATE INDEX idx_governance_memberships_org + ON governance.memberships (org_id); + +CREATE TABLE governance.org_agents ( + identity_id text PRIMARY KEY REFERENCES governance.identities (id), + org_id text NOT NULL REFERENCES governance.orgs (id), + created_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX idx_governance_org_agents_org + ON governance.org_agents (org_id); + +CREATE TABLE governance.accounts ( + identity_id text PRIMARY KEY REFERENCES governance.identities (id), + email text NOT NULL UNIQUE CHECK (email = lower(email)), + password_hash text NOT NULL, + recovery_hash text, + failed_attempts integer NOT NULL DEFAULT 0, + locked_until timestamptz +); + +CREATE TABLE governance.account_sessions ( + token_hash text PRIMARY KEY, + identity_id text NOT NULL REFERENCES governance.identities (id) ON DELETE CASCADE, + expires_at timestamptz NOT NULL, + issued_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX idx_governance_account_sessions_identity + ON governance.account_sessions (identity_id); +CREATE INDEX idx_governance_account_sessions_expiry + ON governance.account_sessions (expires_at); + +CREATE TABLE governance.authentication_settings ( + singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton), + public_url text NOT NULL, + oidc_issuer text NOT NULL DEFAULT '', + oidc_audience text NOT NULL DEFAULT '', + oidc_client_id text NOT NULL DEFAULT '' +); + +CREATE TABLE governance.passkeys ( + credential_id text PRIMARY KEY, + identity_id text NOT NULL REFERENCES governance.identities (id), + name text NOT NULL, + credential jsonb NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX idx_governance_passkeys_identity + ON governance.passkeys (identity_id); + +CREATE TABLE governance.passkey_ceremonies ( + token_hash text PRIMARY KEY, + identity_id text NOT NULL, + registration boolean NOT NULL, + session_data jsonb NOT NULL, + expires_at timestamptz NOT NULL +); +CREATE INDEX idx_governance_passkey_ceremonies_expiry + ON governance.passkey_ceremonies (expires_at); + +CREATE TABLE governance.access_policies ( + level text NOT NULL CHECK (level IN ('instance', 'org', 'workspace', 'object')), + org_id text NOT NULL DEFAULT '', + workspace_id text NOT NULL DEFAULT '', + object_kind text NOT NULL DEFAULT '', + object_id text NOT NULL DEFAULT '', + policy_id text NOT NULL, + text text NOT NULL, + updated_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (level, org_id, workspace_id, object_kind, object_id, policy_id) +); + +CREATE TABLE governance.access_policy_versions ( + level text NOT NULL CHECK (level IN ('instance', 'org', 'workspace', 'object')), + org_id text NOT NULL DEFAULT '', + workspace_id text NOT NULL DEFAULT '', + version bigint NOT NULL DEFAULT 1, + updated_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (level, org_id, workspace_id) +); + +CREATE TABLE governance.access_policy_revision ( + only_row boolean PRIMARY KEY DEFAULT true CHECK (only_row), + version bigint NOT NULL DEFAULT 1, + updated_at timestamptz NOT NULL DEFAULT now() +); +INSERT INTO governance.access_policy_revision (only_row) VALUES (true); + +CREATE TABLE governance.access_denials ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + org_id text NOT NULL, + principal text NOT NULL, + action text NOT NULL, + resource_kind text NOT NULL, + resource_id text NOT NULL, + level text NOT NULL, + policies text[] NOT NULL DEFAULT '{}', + minute_at timestamptz NOT NULL DEFAULT date_trunc('minute', now()), + count bigint NOT NULL DEFAULT 1, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); +CREATE UNIQUE INDEX idx_governance_access_denials_dedup + ON governance.access_denials (org_id, principal, action, resource_kind, resource_id, level, policies, minute_at); + +-- +goose Down +DROP INDEX governance.idx_governance_access_denials_dedup; +DROP TABLE governance.access_denials; +DROP TABLE governance.access_policy_revision; +DROP TABLE governance.access_policy_versions; +DROP TABLE governance.access_policies; +DROP TABLE governance.passkey_ceremonies; +DROP TABLE governance.passkeys; +DROP TABLE governance.authentication_settings; +DROP TABLE governance.account_sessions; +DROP TABLE governance.accounts; +DROP TABLE governance.org_agents; +DROP TABLE governance.memberships; +DROP TABLE governance.workspaces; +DROP TABLE governance.orgs; +DROP TABLE governance.identity_subjects; +DROP TABLE governance.identity_events; +DROP TABLE governance.identity_aliases; +DROP TABLE governance.identities; + +ALTER TABLE governance.person_identities + RENAME CONSTRAINT person_identities_person_id_fkey TO identities_person_id_fkey; +ALTER INDEX governance.person_identities_pkey RENAME TO identities_pkey; +ALTER TABLE governance.person_identities RENAME TO identities; diff --git a/modules/governance/access.go b/modules/governance/access.go new file mode 100644 index 000000000..fa96ff270 --- /dev/null +++ b/modules/governance/access.go @@ -0,0 +1,449 @@ +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" + 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 +} + +// 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 +} diff --git a/modules/governance/access_test.go b/modules/governance/access_test.go new file mode 100644 index 000000000..b9ca6804c --- /dev/null +++ b/modules/governance/access_test.go @@ -0,0 +1,287 @@ +package governance + +import ( + "context" + "errors" + "log/slog" + "testing" +) + +// 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) + } + }) + } +} diff --git a/modules/governance/common_passwords.go b/modules/governance/common_passwords.go new file mode 100644 index 000000000..c618ea234 --- /dev/null +++ b/modules/governance/common_passwords.go @@ -0,0 +1,354 @@ +package governance + +// Known common passwords at or above the minimum length, from the NCSC +// list in SecLists. Shorter entries are rejected by the length rule. +// Source: https://github.com/danielmiessler/SecLists/blob/master/Passwords/Common-Credentials/100k-most-used-passwords-NCSC.txt +// +// MIT License +// +// Copyright (c) 2018 Daniel Miessler +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +//nolint:gosec // G101: the list of passwords sign-up refuses. +const commonPasswords = ` +000000000000000 +00000000000000000000 +010203040506070809 +102030405060708090 +111111111111111 +11111111111111111111 +111222333444555 +1122334455667788 +112233445566778899 +11223344556677889900 +1213141516171819 +122333444455555 +123123123123123 +123451234512345 +1234567812345678 +1234567887654321 +12345678900987654321 +123456789012345 +1234567890123456 +12345678901234567890 +1234567890987654321 +1234567890qwert +1234567890qwerty +1234567890qwertyuiop +123456789101112 +123456789123456 +1234567891234567 +123456789123456789 +12345678987654321 +123456789987654 +1234567899876543 +123456789987654321 +123456789qwerty +123456789qwertyuio +123456789qwertyuiop +123456789zxcvbnm +12345678qwertyui +12345qwertasdfg +1234qwerasdfzxcv +1324354657687980 +1q2w3e4r5t6y7u8 +1q2w3e4r5t6y7u8i +1q2w3e4r5t6y7u8i9o +1q2w3e4r5t6y7u8i9o0p +1qa2ws3ed4rf5tg +1qaz2wsx3edc4rfv +1qaz2wsx3edc4rfv5tgb +1qazxsw23edcvfr4 +30secondstomars +5.254.105.20:test +5.254.105.20:test1 +555555555555555 +6666666666empulgara +79621601378.kirill +827ccb0eea8a706c4c +9121318barssuki +987654321123456789 +??????????????? +@elit-centr.com.ua +aaaaaaaaaaaaaaa +aaaaaaaaaaaaaaaa +abuse_123456_abuse +aleksandr.ustinov.2012 +aleksej.shorin.86 +alena_plotnikova_1995 +aliya.mutallapova +andrey.shalanov +andreyka.gorshkov.98 +andreyka.zhilin.1981 +anna.savickaya.1986 +antsiferova1973 +antusenok_zhekonya +apalkova.tatiana +aqwleeb_6e0pk59 +arina-sharapova-80 +arividerchi_shatalov +armyach-aleksandra +arsik-di-noxcho95 +asdfghjkl:': +asdfghjkl;' +asdfghjklzxcvbnm +asil.dovlatov.1982 +avengedsevenfold +azefirov.inno1987.r +bad_boys_adience +bakuman.manga.drawing +beloved_a_devil +blackangel09021 +blckd_sa_unpaidfee_oct06 +californication +ceckbrcerfkbxyjcnm2 +cod12qw75rqyi59n +constance626boilard1987 +cristianoronaldo +d1bd6bc58c1d74df41a957489c9942f5 +d41d8cd98f00b204e980 +damira.shagabutdinova +default_password +demon1q2w3e4r5t +denis_nazarenko +dimulya.vasilenko +dmitrij.mironov2014 +doomsayer.2.7mords.v +doomsayer.2.7mords.vv +dovbeshkosushova.1972 +drm199019902323 +e10adc3949ba59abbe56 +eremei_vasechkin +etravelmoleoptin +evgenii-shenderovich +familiyafamiliya +fiammalex1@hotmail.it +fjodorova-natashenka +friendofarriane +friendofearning$1 +friendofeveryemailyouproc +friendofthenext18peoplew +friendofyoucanmake$200- +gadjieva.gulmira +galatasaray1905 +galina-davidyuk +galinka_korneeva +gayassfagpastebinleaks +goderdzikarxjxv +golovizina_elena +guldaniya.galina +gygypyfyyyposhy +hallucinationse +hd764nw5d7e1vb1 +hermina617berno1990f6i +holidaysecure123 +holidaysecure123$ +htt//members.cumfiesta.com/ +hugo854lataille1988 +ignatova_1978_09 +ijfrnhf7yhcy54bhy0cd +inactive1996aug +ivankaterinchenko +jafjkshf7y6w34rjd +john!20130605at1753 +julia_eduardovna +juliadronina1996 +kamazist.tsobenko +kartoffelpuffer +kikugalanetroot +kinyabuzova.eleonora +kirienko_svetlana +kirik26trimyasov +kirill.kirillov.2013 +korostelev_3333 +kotovichvalentina +ksyusha.kulagina.91 +kudryavcevavalya +kurmangazieva_gulmira +kuznecovviktorr +lady.procenko71 +len_rin_kagamine_02 +lexaafanasiev84 +lhbjkjubz2957704 +lightpower12345 +linkedinlinkedin +linkedinpassword +listopad.iuliia +macegorova.mariya +maitland571ka1994 +maks.abramov.99.99 +maksim.bychkov.1986 +maksimilian_nasirov +malhotra493ozzy1991282151 +manchesterunited +mandds1mg6bv8re +maria-demidchik +mariagoncharenko +marina.shapovalo +marina.ushakovaznuv +marina_stryazhkova +marinadeduxinaa +marinaorlova1991 +marinochka.zhelannaya +masloboinikova1987 +maximova_elena77 +migrationsandeep +migrationschool +mihail_alekseevskiy406 +mihailpezhemskii +milankasanakoeva +mirellabroersma1987570 +miss-evgeniya-93 +miss.marina.nikolaeva.2013 +mknaxhxeh8yp3tf +morozovavalya28 +mozellbranou81e +mutalim.gusenov +mychemicalromance +narashchivaiunoghti +nastyaanciferova +natalya.dmitrieva.1978 +nati.beridze.92 +never_desponding +neworleans12345 +nikolay_thebest +oksanaorgadykova +olesya.kolchina +olga.kazakova_85 +olga.ponomarenko.2012 +olga.rumyanceva.1985 +olgha.pietrova.1979 +password1234567 +password12345678 +password123456789 +passwordpassword +pletnevakaterina +polniypizdec0211 +polniypizdec1102 +polniypizdec110211 +professionaltools +prosto_chelkynchik +q1w2e3r4t5y6u7i8 +q1w2e3r4t5y6u7i8o9 +q1w2e3r4t5y6u7i8o9p0 +qazwsxedcrfvtgb +qwertasdfgzxcvb +qwerty123456789 +qwerty1234567890 +qwertyuiop12345 +qwertyuiop123456 +qwertyuiop123456789 +qwertyuiop1234567890 +qwertyuiopasdfg +qwertyuiopasdfghjkl +qwertyuiopasdfghjkl151515 +qwertyuiopasdfghjklzxcvbnm +r6a50de3ujwtog4 +rachelle289ariyoshi5251987 +rashaun966krager1993 +raymonde336schwegel7331987 +regawf7ss1dm7rn +rendakova_sveta +riwr2hky4w3tjgg +rkamkin.karoli1988mp +romanova.natalya.96 +rtertuy77ijyhu7i +sataieva.elinka +sdf7asdf6asdg8df +sdf7asdf6asdg8df1 +sergeevna_10.10.91 +sergey-personal +sergey.lushnikoff +sergey.melnik-1996 +sergio-emperior +shakmakovataisiya1992 +shaquillesecx10 +sharmaine005foskett6071988 +shea019bernabei1992 +sheba417yorck1986vxm7 +shukurova-ismigu +siiifonjiknalivai +silakova.nadezhda.2012 +simonova_lyudmila_73 +simonovskiy1970 +sirazhdinov.shamil +slava_kulbidyuk +sofya.kulikova.87 +soloveibormalei +somanypickles27 +sorokina-999-01 +spiridonmarkin1982 +spring938burston0001990 +srcuqq1_2j1h3rbf +stalker_lemurrr +stas.gorodissky +stas_the_best.ru +stefangreil1983 +stepanov_georgij +sulamifcherenchikova1979 +svetik_kryuchkov +svetlana-mironova-13 +tagesgruppe2010 +thisismypassword +travelmoleoptin +vadyusha.isaev.83 +valentina.victoria +valya-valya-1982 +valya.klimenko.87 +valya.korobeynik +valya.kryuchkova.1990 +valya.lantux.83 +varfolomeeva0990 +varida.alibaeva +veralipatnikova +victor_evdokimov +victor_sakhalin1990-20 +victoria-berkat-energo +victoria-dyatlova +victoria392eliezrie1992frp +victoria_shkurco +vika.krivonos.1995 +vkovshut_annab1988fg +vks1zz9v_7ceu69 +vladcherktecktonik +volfram.kozlov123633 +volfram.kozlov173902 +volgograd.orlovka +volkova.elena.13 +volkova.ksyusha.89 +volodina.elena66 +volodya-ivanov-63 +volokitina.olga +voroshilova.liliya +worldofwarcraft +wwwksenechkawww +yegbpltw2012lol +yfdbufnjh10305070 +yulia-dubrovina +yushinazena2009 +zabloczkaya2012 +zabolotneva_ira +zabolotnova31337 +zarina_sabirova +zarinaismailova +zxcvbnm123456789 +zxcvbnmasdfghjkl +пїѕпїѕпїѕпїѕпїѕпїѕ@mail.ru +` diff --git a/modules/governance/engine.go b/modules/governance/engine.go new file mode 100644 index 000000000..6658a05f1 --- /dev/null +++ b/modules/governance/engine.go @@ -0,0 +1,257 @@ +package governance + +import ( + "context" + "fmt" + "sync" + + cedar "github.com/cedar-policy/cedar-go" + "github.com/cedar-policy/cedar-go/types" + expast "github.com/cedar-policy/cedar-go/x/exp/ast" + schema "github.com/cedar-policy/cedar-go/x/exp/schema" + validate "github.com/cedar-policy/cedar-go/x/exp/schema/validate" +) + +const schemaText = `namespace Archie { + entity Identity in [Org] = {"org": String, "role": String}; + entity Org; + entity Workspace in [Org] = {"org": String, "environment": String}; + entity Object in [Org, Workspace] = {"org": String, "workspace": Workspace, "kind": String, "owner": String, "state": String}; + action read appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action create appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action update appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action delete appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action approve appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action run appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action read_logs appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action read_secret appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action manage_members appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action manage_identities appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action deliver appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action manage_policies appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action read_audit appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action read_usage appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; +}` + +// Problem is one stored policy the engine could not validate. +type Problem struct { + Policy Policy + Err error +} + +type levelSet struct { + at Level + ids []string + set *cedar.PolicySet + invalid error +} + +func (l *levelSet) active() bool { return l != nil && (len(l.ids) > 0 || l.invalid != nil) } + +// Engine evaluates the instance -> org -> workspace -> object Cedar policy chain. +type Engine struct { + instance *levelSet + orgs map[OrgID]*levelSet + spaces map[spaceKey]*levelSet + objects map[objectKey]*levelSet + problems []Problem + pending bool +} + +var pendingEngine = &Engine{pending: true} + +type ( + spaceKey struct { + org OrgID + ws WorkspaceID + } + objectKey struct { + org OrgID + kind ResourceKind + id string + } +) + +var ( + _ Authorizer = (*Engine)(nil) + _ Validator = (*Engine)(nil) +) + +// NewEngine builds an engine from the stored policies. An invalid policy makes +// its level deny everything and is reported in Problems. +func NewEngine(policies []Policy) *Engine { + e := &Engine{ + orgs: map[OrgID]*levelSet{}, + spaces: map[spaceKey]*levelSet{}, + objects: map[objectKey]*levelSet{}, + } + for _, p := range policies { + lvl := e.level(p) + policy, err := compile(p) + if err != nil { + lvl.ids = append(lvl.ids, p.ID) + lvl.invalid = err + e.problems = append(e.problems, Problem{Policy: p, Err: err}) + continue + } + lvl.ids = append(lvl.ids, p.ID) + lvl.set.Add(types.PolicyID(p.ID), policy) + } + return e +} + +// Ready reports whether the engine was built from stored policies. +func (e *Engine) Ready() bool { return !e.pending } + +// Problems reports every stored policy the engine could not compile. +func (e *Engine) Problems() []Problem { return e.problems } + +func (e *Engine) level(p Policy) *levelSet { + switch p.Level { + case LevelInstance: + if e.instance == nil { + e.instance = &levelSet{at: p.Level, set: cedar.NewPolicySet()} + } + return e.instance + case LevelOrg: + id := p.OrgID + if lvl, ok := e.orgs[id]; ok { + return lvl + } + lvl := &levelSet{at: p.Level, set: cedar.NewPolicySet()} + e.orgs[id] = lvl + return lvl + case LevelWorkspace: + id := spaceKey{p.OrgID, p.WorkspaceID} + if lvl, ok := e.spaces[id]; ok { + return lvl + } + lvl := &levelSet{at: p.Level, set: cedar.NewPolicySet()} + e.spaces[id] = lvl + return lvl + case LevelObject: + id := objectKey{p.OrgID, p.ObjectKind, p.ObjectID} + if lvl, ok := e.objects[id]; ok { + return lvl + } + lvl := &levelSet{at: p.Level, set: cedar.NewPolicySet()} + e.objects[id] = lvl + return lvl + } + return nil +} + +// Validate checks one policy against the Cedar schema. +func (e *Engine) Validate(p Policy) error { + _, err := compile(p) + return err +} + +func compile(p Policy) (*cedar.Policy, error) { + if err := p.Validate(); err != nil { + return nil, err + } + pls, err := cedar.NewPolicyListFromBytes(p.ID, []byte(p.Text)) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrPolicyInvalidText, err) + } + if len(pls) != 1 { + return nil, fmt.Errorf("%w: %s carries %d policies, want exactly one", ErrPolicyInvalidText, p.ID, len(pls)) + } + v, err := schemaValidator() + if err != nil { + return nil, err + } + if err := v.Policy(p.ID, (*expast.Policy)(pls[0].AST())); err != nil { + return nil, fmt.Errorf("%w: %w", ErrPolicyInvalidText, err) + } + return pls[0], nil +} + +// Authorize evaluates the policy chain for one request. +func (e *Engine) Authorize(_ context.Context, p Principal, a Action, r Resource, c AccessContext) Decision { + if e.pending { + return Unavailable() + } + resOrg := r.Org + if resOrg == "" { + resOrg = p.Org + } + if p.Org == "" || resOrg != p.Org { + return DeniedAt(LevelInstance, []string{CrossOrgForbidID}) + } + return evaluate(e.chain(p, r), buildEntities(p, r), buildRequest(p, a, r, c)) +} + +// AuthorizeDelivery decides whether addr may deliver an event to a source. +func (e *Engine) AuthorizeDelivery(_ context.Context, orgID OrgID, sourcePath, addr string) Decision { + if e.pending { + return Unavailable() + } + sender := Principal{IdentityID: SenderID, Org: orgID} + resource := Resource{Kind: KindSource, ID: sourcePath, Org: orgID} + levels := []*levelSet{e.instance} + if l, ok := e.objects[objectKey{orgID, KindSource, sourcePath}]; ok { + levels = append(levels, l) + } + return evaluate(levels, buildEntities(sender, resource), buildRequest(sender, ActionDeliver, resource, AccessContext{Addr: addr})) +} + +func evaluate(levels []*levelSet, entities types.EntityMap, request types.Request) Decision { + for _, lvl := range levels { + if !lvl.active() { + continue + } + if lvl.invalid != nil { + decision := DeniedAt(lvl.at, lvl.ids) + decision.Err = lvl.invalid + return decision + } + decision, diag := cedar.Authorize(lvl.set, entities, request) + if decision == cedar.Allow { + continue + } + ids := make([]string, 0, len(diag.Reasons)) + for _, reason := range diag.Reasons { + ids = append(ids, string(reason.PolicyID)) + } + if len(ids) == 0 { + ids = lvl.ids + } + return DeniedAt(lvl.at, ids) + } + return Allowed() +} + +func (e *Engine) chain(p Principal, r Resource) []*levelSet { + var out []*levelSet + if e.instance == nil || e.instance.invalid == nil || r.Kind != KindPolicy || !p.InstanceAdmin() { + out = append(out, e.instance) + } + if l, ok := e.orgs[r.Org]; ok { + out = append(out, l) + } + if r.Workspace != "" { + if l, ok := e.spaces[spaceKey{r.Org, r.Workspace}]; ok { + out = append(out, l) + } + } + if r.Org != "" && r.ID != "" { + if l, ok := e.objects[objectKey{r.Org, r.Kind, r.ID}]; ok { + out = append(out, l) + } + } + return out +} + +var schemaValidator = sync.OnceValues(func() (*validate.Validator, error) { + var sch schema.Schema + if err := sch.UnmarshalCedar([]byte(schemaText)); err != nil { + return nil, err + } + resolved, err := sch.Resolve() + if err != nil { + return nil, err + } + return validate.New(resolved), nil +}) diff --git a/modules/governance/entities.go b/modules/governance/entities.go new file mode 100644 index 000000000..5098f5e42 --- /dev/null +++ b/modules/governance/entities.go @@ -0,0 +1,90 @@ +package governance + +import ( + "time" + + cedar "github.com/cedar-policy/cedar-go" + "github.com/cedar-policy/cedar-go/types" +) + +func buildRequest(p Principal, a Action, r Resource, c AccessContext) types.Request { + record := types.RecordMap{} + if c.Signature != "" { + record["signature"] = types.String(c.Signature) + } + if c.Addr != "" { + if addr, err := types.ParseIPAddr(c.Addr); err == nil { + record["addr"] = addr + } + } + if c.Run != "" { + record["run"] = types.String(c.Run) + } + if c.Step != "" { + record["step"] = types.String(c.Step) + } + at := c.Time + if at.IsZero() { + at = time.Now().UTC() + } + record["time"] = types.NewDatetime(at) + + return types.Request{ + Principal: types.NewEntityUID(EntityTypeIdentity, types.String(p.IdentityID)), + Action: types.NewEntityUID(EntityTypeAction, types.String(string(a))), + Resource: types.NewEntityUID(EntityTypeObject, types.String(r.ID)), + Context: types.NewRecord(record), + } +} + +func buildEntities(p Principal, r Resource) cedar.EntityMap { + resOrg := r.Org + if resOrg == "" { + resOrg = p.Org + } + entities := cedar.EntityMap{} + orgUID := types.NewEntityUID(EntityTypeOrg, types.String(resOrg)) + entities[orgUID] = cedar.Entity{UID: orgUID} + + principalUID := types.NewEntityUID(EntityTypeIdentity, types.String(p.IdentityID)) + entities[principalUID] = cedar.Entity{ + UID: principalUID, + Parents: cedar.NewEntityUIDSet(orgUID), + Attributes: types.NewRecord(types.RecordMap{ + "org": types.String(resOrg), + "role": types.String(string(p.Role(r.Workspace))), + }), + } + + parents := []types.EntityUID{orgUID} + resUID := types.NewEntityUID(EntityTypeObject, types.String(r.ID)) + attrs := types.RecordMap{ + "org": types.String(resOrg), + "kind": types.String(string(r.Kind)), + } + if r.Workspace != "" { + wsUID := types.NewEntityUID(EntityTypeWorkspace, types.String(r.Workspace)) + entities[wsUID] = cedar.Entity{ + UID: wsUID, + Parents: cedar.NewEntityUIDSet(orgUID), + Attributes: types.NewRecord(types.RecordMap{ + "org": types.String(resOrg), + "environment": types.String(p.Environment(r.Workspace)), + }), + } + parents = append(parents, wsUID) + attrs["workspace"] = wsUID + } + if r.Owner != "" { + attrs["owner"] = types.String(string(r.Owner)) + } + if r.State != "" { + attrs["state"] = types.String(r.State) + } + entities[resUID] = cedar.Entity{ + UID: resUID, + Parents: cedar.NewEntityUIDSet(parents...), + Attributes: types.NewRecord(attrs), + } + return entities +} diff --git a/modules/governance/identity.go b/modules/governance/identity.go new file mode 100644 index 000000000..19049c99b --- /dev/null +++ b/modules/governance/identity.go @@ -0,0 +1,497 @@ +package governance + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "net/mail" + "net/url" + "strings" + "time" + + "github.com/google/uuid" +) + +type ( + IdentityID string + Kind string + Lifecycle string + CommandType string +) + +const ( + SystemID IdentityID = "00000000-0000-5000-8000-000000000001" + KindSystem Kind = "system" + KindBot Kind = "bot" + KindServiceAccount Kind = "service_account" + KindUser Kind = "user" + LifecycleActive Lifecycle = "active" + LifecycleSuspended Lifecycle = "suspended" + LifecycleRetired Lifecycle = "retired" + CommandRename CommandType = "rename" + CommandSuspend CommandType = "suspend" + CommandReactivate CommandType = "reactivate" + CommandRetire CommandType = "retire" +) + +var ( + ErrInvalidIdentity = errors.New("invalid identity") + ErrIdentityNotFound = errors.New("identity not found") + ErrIdentityConflict = errors.New("identity version conflict") + ErrSystemImmutable = errors.New("system identity is immutable") + ErrIllegalTransition = errors.New("illegal identity lifecycle transition") + ErrNoCredential = errors.New("no credential presented") + ErrCredentialRejected = errors.New("credential rejected") + ErrProviderUnavailable = errors.New("identity provider unavailable") + ErrSubjectUnbound = errors.New("credential subject is not bound to an identity") + ErrIdentityInactive = errors.New("identity may not act") + ErrSetupComplete = errors.New("administrator has already been set up") +) + +// Identity is a persistent actor (user, bot, service account, or system) and +// its lifecycle state. +type Identity struct { + ID IdentityID `json:"id"` + Kind Kind `json:"kind"` + DisplayName string `json:"display_name"` + Lifecycle Lifecycle `json:"lifecycle"` + Version int64 `json:"version"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +// IdentityCommand is a lifecycle or rename mutation applied to an Identity. +type IdentityCommand struct { + Type CommandType + DisplayName string +} + +// IdentityEvent records one applied IdentityCommand. +type IdentityEvent struct { + IdentityID IdentityID + Type CommandType + From Lifecycle + To Lifecycle + DisplayName string + At time.Time +} + +// IdentityAudit attributes an identity change to an actor and source. +type IdentityAudit struct { + ActorID IdentityID + Source, RequestID string + At time.Time +} + +// IdentityRepository persists identities and their lifecycle events. +type IdentityRepository interface { + List(context.Context) ([]Identity, error) + Get(context.Context, IdentityID) (Identity, error) + ResolveLegacyName(context.Context, string) (Identity, error) + Create(context.Context, Identity, IdentityAudit) (Identity, error) + Apply(context.Context, IdentityID, int64, IdentityCommand, IdentityAudit) (Identity, error) +} + +// SystemIdentity returns the singleton built-in system identity. +func SystemIdentity() Identity { + return Identity{ID: SystemID, Kind: KindSystem, DisplayName: "System", Lifecycle: LifecycleActive, Version: 1} +} + +// StableID derives a version 5 UUID from legacyName using SHA-256 so fixed +// identities resolve deterministically across restarts. +func StableID(legacyName string) IdentityID { + sum := sha256.Sum256([]byte("archie.identity.v1\x00" + strings.ToLower(strings.TrimSpace(legacyName)))) + var id uuid.UUID + copy(id[:], sum[:16]) + id[6] = id[6]&0x0f | 0x50 + id[8] = id[8]&0x3f | 0x80 + return IdentityID(id.String()) +} + +// OperatorID is the person identity used by an instance operator. +func OperatorID() IdentityID { return StableID("operator") } + +// AgentID is the bot identity workflows run as. +func AgentID() IdentityID { return StableID("agent") } + +// NewIdentity validates and constructs an active Identity at version 1. +func NewIdentity(id IdentityID, kind Kind, displayName string) (Identity, error) { + value := Identity{ + ID: id, + Kind: kind, + DisplayName: strings.TrimSpace(displayName), + Lifecycle: LifecycleActive, + Version: 1, + } + if err := value.Validate(); err != nil { + return Identity{}, err + } + return value, nil +} + +// FromLegacyName builds the bot identity for a configured name. +func FromLegacyName(legacyName string) (Identity, error) { + return NewIdentity(StableID(legacyName), KindBot, legacyName) +} + +// Agent reports whether k acts on its own rather than for a person: an agent +// serves one organisation. +func (k Kind) Agent() bool { return k == KindBot || k == KindServiceAccount } + +// ValidDisplayName reports whether name is non-empty after trimming. +func ValidDisplayName(name string) bool { return strings.TrimSpace(name) != "" } + +// Validate checks that i has a valid id, display name, kind, and lifecycle. +func (i Identity) Validate() error { + if i.ID == "" || !ValidDisplayName(i.DisplayName) { + return fmt.Errorf("%w: ID and display name are required", ErrInvalidIdentity) + } + switch i.Kind { + case KindSystem, KindBot, KindServiceAccount, KindUser: + default: + return fmt.Errorf("%w: unknown kind %q", ErrInvalidIdentity, i.Kind) + } + switch i.Lifecycle { + case LifecycleActive, LifecycleSuspended, LifecycleRetired: + default: + return fmt.Errorf("%w: unknown lifecycle %q", ErrInvalidIdentity, i.Lifecycle) + } + if i.Kind == KindSystem && (i.ID != SystemID || i.Lifecycle != LifecycleActive) { + return ErrSystemImmutable + } + if i.ID == SystemID && i.Kind != KindSystem { + return ErrSystemImmutable + } + return nil +} + +// CanAct reports whether an identity may perform actions. +func (i Identity) CanAct() bool { return i.Lifecycle == LifecycleActive } + +// ApplyIdentity applies command to i and returns the updated identity and event. +func ApplyIdentity(i Identity, command IdentityCommand) (Identity, IdentityEvent, error) { + if i.ID == SystemID || i.Kind == KindSystem { + return Identity{}, IdentityEvent{}, ErrSystemImmutable + } + event := IdentityEvent{IdentityID: i.ID, Type: command.Type, From: i.Lifecycle, To: i.Lifecycle, At: time.Now().UTC()} + switch command.Type { + case CommandRename: + name := strings.TrimSpace(command.DisplayName) + if name == "" { + return Identity{}, IdentityEvent{}, fmt.Errorf("%w: display name is required", ErrInvalidIdentity) + } + i.DisplayName, event.DisplayName = name, name + case CommandSuspend: + if i.Lifecycle != LifecycleActive { + return Identity{}, IdentityEvent{}, ErrIllegalTransition + } + i.Lifecycle, event.To = LifecycleSuspended, LifecycleSuspended + case CommandReactivate: + if i.Lifecycle != LifecycleSuspended { + return Identity{}, IdentityEvent{}, ErrIllegalTransition + } + i.Lifecycle, event.To = LifecycleActive, LifecycleActive + case CommandRetire: + if i.Lifecycle != LifecycleActive && i.Lifecycle != LifecycleSuspended { + return Identity{}, IdentityEvent{}, ErrIllegalTransition + } + i.Lifecycle, event.To = LifecycleRetired, LifecycleRetired + default: + return Identity{}, IdentityEvent{}, fmt.Errorf("%w: unknown command %q", ErrInvalidIdentity, command.Type) + } + i.Version++ + return i, event, nil +} + +// Subject is what an identity provider asserts about a caller. Issuer is part +// of the key because two providers can assert the same subject string for +// different people. +type Subject struct { + Issuer string `json:"issuer"` + Subject string `json:"subject"` +} + +// EmailSubject is the placeholder binding of a person added by email until +// their first sign-in claims it. +func EmailSubject(issuer, email string) Subject { + return Subject{Issuer: issuer, Subject: "email:" + strings.ToLower(strings.TrimSpace(email))} +} + +// Validate checks that s names both an issuer and a subject. +func (s Subject) Validate() error { + if strings.TrimSpace(s.Issuer) == "" || strings.TrimSpace(s.Subject) == "" { + return fmt.Errorf("%w: issuer and subject are required", ErrInvalidIdentity) + } + return nil +} + +// Credential is what a provider-issued token proved. +type Credential struct { + Subject Subject + Email string + Scopes []string + Expires time.Time +} + +// Verifier checks a presented bearer token against an identity provider. +type Verifier interface { + Verify(ctx context.Context, rawToken string) (Credential, error) +} + +// SubjectResolver resolves a provider subject to its bound identity. +type SubjectResolver interface { + ResolveSubject(context.Context, Subject) (Identity, error) + ClaimSubject(ctx context.Context, placeholder, subject Subject) (Identity, error) +} + +// SubjectBinding resolves and binds verified provider subjects to identities. +type SubjectBinding interface { + SubjectResolver + BindSubject(context.Context, IdentityID, Subject, IdentityAudit) error +} + +// LoginFlow is the browser authorization flow an identity provider requires. +type LoginFlow interface { + AuthCodeURL(ctx context.Context, state string) (string, string, error) + Exchange(ctx context.Context, code, codeVerifier string) (ProviderSession, error) +} + +// ProviderSession is what a completed provider authorization flow yields. +type ProviderSession struct { + Credential Credential + Token string + Expires time.Time +} + +// AuthenticateCredential verifies rawToken and resolves it to an active identity. +func AuthenticateCredential(ctx context.Context, subjects SubjectResolver, verifier Verifier, rawToken string) (Identity, Credential, error) { + if strings.TrimSpace(rawToken) == "" { + return Identity{}, Credential{}, ErrNoCredential + } + if verifier == nil { + return Identity{}, Credential{}, fmt.Errorf("%w: no identity provider is configured", ErrCredentialRejected) + } + credential, err := verifier.Verify(ctx, rawToken) + if err != nil { + return Identity{}, Credential{}, fmt.Errorf("%w: %w", ErrCredentialRejected, err) + } + value, err := ResolveCredential(ctx, subjects, credential) + if err != nil { + return Identity{}, Credential{}, err + } + return value, credential, nil +} + +// ResolveCredential maps a verified credential to its active identity. +func ResolveCredential(ctx context.Context, subjects SubjectResolver, credential Credential) (Identity, error) { + if err := credential.Subject.Validate(); err != nil { + return Identity{}, fmt.Errorf("%w: %w", ErrCredentialRejected, err) + } + value, err := subjects.ResolveSubject(ctx, credential.Subject) + if errors.Is(err, ErrIdentityNotFound) && credential.Email != "" { + value, err = subjects.ClaimSubject(ctx, EmailSubject(credential.Subject.Issuer, credential.Email), credential.Subject) + } + if err != nil { + if errors.Is(err, ErrIdentityNotFound) { + return Identity{}, fmt.Errorf("%w: %s", ErrSubjectUnbound, credential.Subject.Subject) + } + return Identity{}, err + } + if !value.CanAct() { + return Identity{}, fmt.Errorf("%w: %s is %s", ErrIdentityInactive, value.ID, value.Lifecycle) + } + return value, nil +} + +// PersonalTokenIssuer is the subject issuer a personal API token binds under. +// The subject is the token's SHA-256, so the store never holds the token. +const PersonalTokenIssuer = "archie-token" + +const ( + personalTokenPrefix = "archie_pat_" + lastUsedGranularity = time.Minute +) + +// NewPersonalToken returns a fresh personal API token and the subject it binds as. +func NewPersonalToken() (string, Subject, error) { + var secret [32]byte + if _, err := rand.Read(secret[:]); err != nil { + return "", Subject{}, err + } + raw := personalTokenPrefix + hex.EncodeToString(secret[:]) + subject, _ := PersonalTokenSubject(raw) + return raw, subject, nil +} + +// PersonalTokenSubject returns the subject a presented token binds as, or +// false when the credential is not a personal token. +func PersonalTokenSubject(raw string) (Subject, bool) { + if !strings.HasPrefix(raw, personalTokenPrefix) { + return Subject{}, false + } + sum := sha256.Sum256([]byte(raw)) + return Subject{Issuer: PersonalTokenIssuer, Subject: hex.EncodeToString(sum[:])}, true +} + +// PersonalToken is one personal API token as its owner sees it. +type PersonalToken struct { + ID string `json:"id"` + Name string `json:"name"` + CreatedAt time.Time `json:"created_at"` + ExpiresAt *time.Time `json:"expires_at"` + LastUsedAt *time.Time `json:"last_used_at"` +} + +// PersonalTokenStore persists personal API tokens for an identity. +type PersonalTokenStore interface { + BindPersonalToken(ctx context.Context, id IdentityID, subject Subject, name string, expiresAt *time.Time, audit IdentityAudit) error + SubjectsOf(ctx context.Context, id IdentityID, issuer string) ([]PersonalToken, error) + UnbindSubject(context.Context, IdentityID, Subject, IdentityAudit) error + PersonalTokenOf(context.Context, Subject) (PersonalToken, error) + TouchPersonalToken(context.Context, Subject, time.Time) error +} + +// UsePersonalToken admits a presented token, refusing expired tokens and +// recording last use at most once per minute. +func UsePersonalToken(ctx context.Context, store PersonalTokenStore, subject Subject, now time.Time) error { + token, err := store.PersonalTokenOf(ctx, subject) + if err != nil { + return err + } + if token.ExpiresAt != nil && !now.Before(*token.ExpiresAt) { + return ErrIdentityNotFound + } + if token.LastUsedAt == nil || now.Sub(*token.LastUsedAt) >= lastUsedGranularity { + return store.TouchPersonalToken(ctx, subject, now) + } + return nil +} + +// PersonalTokens manages personal API tokens for the authenticated principal. +type PersonalTokens interface { + AddPersonalToken(ctx context.Context, subject Subject, name string, expiresAt *time.Time) error + ListPersonalTokens(ctx context.Context) ([]PersonalToken, error) + RevokePersonalToken(ctx context.Context, id string) error +} + +// AccountSessionLifetime bounds a password or passkey account session. +const AccountSessionLifetime = 7 * 24 * time.Hour + +// AccountRegistration carries the fields needed to register an account or +// bootstrap the instance owner. +type AccountRegistration struct { + PublicURL string `json:"public_url"` + WorkspaceName string `json:"workspace_name"` + OrganisationName string `json:"organisation_name"` + Email string `json:"email"` + DisplayName string `json:"display_name"` + Password string `json:"password"` + Role string `json:"role"` +} + +// Validate normalises email and display name and checks their bounds. +func (r *AccountRegistration) Validate() error { + r.Email = strings.ToLower(strings.TrimSpace(r.Email)) + address, err := mail.ParseAddress(r.Email) + r.DisplayName = strings.TrimSpace(r.DisplayName) + if err != nil || address.Address != r.Email || len(r.Email) > 254 || r.DisplayName == "" || len(r.DisplayName) > 200 { + return ErrInvalidIdentity + } + return nil +} + +// AccountSession is an authenticated user session issued after sign-in. +type AccountSession struct { + Identity Identity + Token string + Expires time.Time +} + +// Accounts manages local password accounts and sessions. +type Accounts interface { + AccountSetupRequired(context.Context) (bool, error) + RegisterAccount(context.Context, AccountRegistration, bool) (Identity, error) + SignInAccount(ctx context.Context, email, password string) (AccountSession, error) + ResolveAccountSession(context.Context, string) (Identity, error) + SignOutAccount(context.Context, string) error + ChangeAccountPassword(ctx context.Context, current, next string) error +} + +// AccountSecurity guards authenticator changes with recent authentication and +// single-use recovery codes. +type AccountSecurity interface { + OpenAccountSession(context.Context, time.Time) (AccountSession, error) + RequireFreshAccountSession(context.Context, string) error + CreateAccountRecovery(context.Context) (string, error) + RecoverAccount(ctx context.Context, email, code, password string) error +} + +// AuthenticationSettings stores instance public origin and OIDC parameters. +type AuthenticationSettings struct { + PublicURL string `json:"public_url"` + OIDCIssuer string `json:"oidc_issuer"` + OIDCAudience string `json:"oidc_audience"` + OIDCClientID string `json:"oidc_client_id"` +} + +// Validate checks that PublicURL is a valid origin and OIDC fields are paired. +func (s AuthenticationSettings) Validate() error { + if !validInstanceOrigin(s.PublicURL) { + return ErrInvalidIdentity + } + if s.OIDCIssuer == "" { + if s.OIDCClientID != "" || s.OIDCAudience != "" { + return ErrInvalidIdentity + } + return nil + } + if !validProviderIssuer(s.OIDCIssuer) || strings.TrimSpace(s.OIDCClientID) == "" || strings.TrimSpace(s.OIDCAudience) == "" { + return ErrInvalidIdentity + } + return nil +} + +func validInstanceOrigin(raw string) bool { + u, err := url.Parse(raw) + if err != nil || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" { + return false + } + return (u.Path == "" || u.Path == "/") && (u.Scheme == "https" || u.Scheme == "http") +} + +func validProviderIssuer(raw string) bool { + u, err := url.Parse(raw) + if err != nil || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" { + return false + } + return u.Scheme == "https" || (u.Scheme == "http" && u.Hostname() == "localhost") +} + +// AuthenticationSettingsStore reads and saves instance authentication settings. +type AuthenticationSettingsStore interface { + AuthenticationSettings(context.Context) (AuthenticationSettings, error) + SaveAuthenticationSettings(context.Context, AuthenticationSettings) error +} + +// Passkey is a registered WebAuthn credential. +type Passkey struct { + ID string `json:"id"` + Name string `json:"name"` +} + +// PasskeyCeremony is an in-flight WebAuthn registration or login ceremony. +type PasskeyCeremony struct { + Token string + Options []byte +} + +// Passkeys manages WebAuthn passkey registration and sign-in. +type Passkeys interface { + BeginPasskey(context.Context, bool) (PasskeyCeremony, error) + FinishPasskey(ctx context.Context, token string, response []byte, registration bool, name string) (AccountSession, error) + ListPasskeys(context.Context) ([]Passkey, error) + DeletePasskey(context.Context, string) error +} diff --git a/modules/governance/identity_test.go b/modules/governance/identity_test.go new file mode 100644 index 000000000..1f9005af6 --- /dev/null +++ b/modules/governance/identity_test.go @@ -0,0 +1,123 @@ +package governance + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/google/uuid" +) + +func TestAuthenticationSettingsRejectUntrustedOrigins(t *testing.T) { + for _, tc := range []struct { + name, url, issuer, client, audience string + want bool + }{ + {name: "public TLS", url: "https://archie.example", want: true}, + {name: "localhost", url: "http://localhost:8484", want: true}, + {name: "userinfo is not an origin", url: "https://user:password@archie.example", want: false}, //nolint:gosec // G101: a fake URL with userinfo, which must be refused. + {name: "URL path cannot change the RP origin", url: "https://archie.example/subpath", want: false}, + {name: "query is not an origin", url: "https://archie.example?token=1", want: false}, + {name: "complete provider", url: "https://archie.example", issuer: "https://identity.example", client: "archie", audience: "archie", want: true}, + {name: "remote insecure provider", url: "https://archie.example", issuer: "http://identity.example", client: "archie", audience: "archie", want: false}, + {name: "issuer without client", url: "https://archie.example", issuer: "https://identity.example", audience: "archie", want: false}, + {name: "audience without provider", url: "https://archie.example", audience: "archie", want: false}, + } { + t.Run(tc.name, func(t *testing.T) { + err := (AuthenticationSettings{PublicURL: tc.url, OIDCIssuer: tc.issuer, OIDCClientID: tc.client, OIDCAudience: tc.audience}).Validate() + if (err == nil) != tc.want { + t.Fatalf("validation err=%v, allowed=%v", err, tc.want) + } + }) + } +} + +func TestPasswordVerification(t *testing.T) { + hash, err := HashPassword("a sufficiently long password") + if err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + name, password, hash string + want bool + }{ + {"correct", "a sufficiently long password", hash, true}, + {"wrong", "a different long password", hash, false}, + {"malformed", "a sufficiently long password", "bad", false}, + {"unbounded parameters", "password", "$argon2id$v=19$m=999999999,t=2,p=1$c2FsdA$aGFzaA", false}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := VerifyPassword(tc.password, tc.hash); got != tc.want { + t.Fatalf("verification = %v, want %v", got, tc.want) + } + }) + } + for _, password := range []string{"short", strings.Repeat("a", 1025), "123456789012345", "passwordpassword"} { + if _, err := HashPassword(password); err == nil { + t.Fatal("accepted invalid password length") + } + } + second, err := HashPassword("a sufficiently long password") + if err != nil { + t.Fatal(err) + } + if hash == second { + t.Fatal("password hashes reuse salts") + } +} + +func TestStableIDIsRFC4122(t *testing.T) { + for _, name := range []string{"agent", "operator", "archie", "Some Bot", ""} { + got := string(StableID(name)) + id, err := uuid.Parse(got) + if err != nil || id.String() != got || id.Version() != 5 || id.Variant() != uuid.RFC4122 { + t.Errorf("StableID(%q) = %q, not an RFC 4122 v5 UUID (err %v)", name, got, err) + } + } +} + +type tokenFake struct { + PersonalTokenStore + token PersonalToken + touched int +} + +func (f *tokenFake) PersonalTokenOf(context.Context, Subject) (PersonalToken, error) { + return f.token, nil +} + +func (f *tokenFake) TouchPersonalToken(context.Context, Subject, time.Time) error { + f.touched++ + return nil +} + +// TestUsePersonalToken pins that an expired token is refused and that last use +// is written at most once a minute. +func TestUsePersonalToken(t *testing.T) { + now := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC) + at := func(d time.Duration) *time.Time { v := now.Add(d); return &v } + tests := []struct { + name string + token PersonalToken + wantErr error + wantTouched int + }{ + {"valid", PersonalToken{ExpiresAt: at(time.Hour)}, nil, 1}, + {"expired", PersonalToken{ExpiresAt: at(-time.Second)}, ErrIdentityNotFound, 0}, + {"expires now", PersonalToken{ExpiresAt: at(0)}, ErrIdentityNotFound, 0}, + {"no expiry", PersonalToken{}, nil, 1}, + {"used seconds ago", PersonalToken{LastUsedAt: at(-10 * time.Second)}, nil, 0}, + {"used minutes ago", PersonalToken{LastUsedAt: at(-2 * time.Minute)}, nil, 1}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f := &tokenFake{token: tt.token} + err := UsePersonalToken(t.Context(), f, Subject{}, now) + if !errors.Is(err, tt.wantErr) || f.touched != tt.wantTouched { + t.Fatalf("err %v touched %d, want %v and %d", err, f.touched, tt.wantErr, tt.wantTouched) + } + }) + } +} diff --git a/modules/governance/internal/store/access.go b/modules/governance/internal/store/access.go new file mode 100644 index 000000000..73f0f9bf0 --- /dev/null +++ b/modules/governance/internal/store/access.go @@ -0,0 +1,275 @@ +package store + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "github.com/jackc/pgx/v5/pgconn" + "github.com/jmoiron/sqlx" +) + +var ( + // ErrNotFound means the requested row does not exist. + ErrNotFound = errors.New("not found") + // ErrAlreadyExists means a unique constraint rejected the insert. + ErrAlreadyExists = errors.New("already exists") + // ErrLastOwner means a membership or lifecycle change would leave an org without an active owner. + ErrLastOwner = errors.New("last active owner") + // ErrSetupComplete means the instance already has a registered owner account. + ErrSetupComplete = errors.New("setup complete") + // ErrCredentialRejected means presented credentials were invalid, locked, or inactive. + ErrCredentialRejected = errors.New("credential rejected") + // ErrIdentityInactive means the identity's lifecycle is not active. + ErrIdentityInactive = errors.New("identity inactive") +) + +func isUniqueViolation(err error) bool { + pgerr, ok := errors.AsType[*pgconn.PgError](err) + return ok && pgerr.Code == "23505" +} + +func (s *Store) withTx(ctx context.Context, fn func(*sqlx.Tx) error) error { + tx, err := s.db.BeginTxx(ctx, nil) + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + if err := fn(tx); err != nil { + return err + } + return tx.Commit() +} + +// PolicyRow is a stored Cedar policy in governance.access_policies. +type PolicyRow struct { + Level string `db:"level"` + OrgID string `db:"org_id"` + WorkspaceID string `db:"workspace_id"` + ObjectKind string `db:"object_kind"` + ObjectID string `db:"object_id"` + PolicyID string `db:"policy_id"` + Text string `db:"text"` + UpdatedAt time.Time `db:"updated_at"` +} + +// DenialRow is a coalesced access refusal in governance.access_denials. +type DenialRow struct { + ID int64 `db:"id"` + OrgID string `db:"org_id"` + Principal string `db:"principal"` + Action string `db:"action"` + ResourceKind string `db:"resource_kind"` + ResourceID string `db:"resource_id"` + Level string `db:"level"` + Policies []string `db:"policies"` + MinuteAt time.Time `db:"minute_at"` + Count int64 `db:"count"` + CreatedAt time.Time `db:"created_at"` + UpdatedAt time.Time `db:"updated_at"` +} + +func policyLockKey(p PolicyRow) string { + joined := strings.Join([]string{p.Level, p.OrgID, p.WorkspaceID, p.ObjectKind, p.ObjectID, p.PolicyID}, "/") + return strings.Trim(joined, "/") +} + +func bumpPolicyRevision(ctx context.Context, tx *sqlx.Tx) error { + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.access_policy_revision (only_row, version) VALUES (true, 1) + ON CONFLICT (only_row) + DO UPDATE SET version = governance.access_policy_revision.version + 1, updated_at = now()`); err != nil { + return fmt.Errorf("bump access policy revision: %w", err) + } + return nil +} + +func cleanEmptyPolicyVersion(ctx context.Context, tx *sqlx.Tx, level, orgID, wsID string) error { + _, err := tx.ExecContext(ctx, ` + DELETE FROM governance.access_policy_versions v + WHERE v.level = $1 AND v.org_id = $2 AND v.workspace_id = $3 + AND NOT EXISTS ( + SELECT 1 FROM governance.access_policies p + WHERE p.level = v.level AND p.org_id = v.org_id AND p.workspace_id = v.workspace_id + )`, level, orgID, wsID) + return err +} + +// ListAccessPolicies returns stored policies visible to scopeOrg (or all when nil). +func (s *Store) ListAccessPolicies(ctx context.Context, scopeOrg *string, instanceScope bool) ([]PolicyRow, error) { + var out []PolicyRow + if err := s.db.SelectContext(ctx, &out, ` + SELECT level, org_id, workspace_id, object_kind, object_id, policy_id, text, updated_at + FROM governance.access_policies + WHERE $1::text IS NULL + OR (level = 'instance' AND $2::bool) + OR (level <> 'instance' AND org_id = $1::text) + ORDER BY level, org_id, workspace_id, object_kind, object_id, policy_id`, scopeOrg, instanceScope); err != nil { + return nil, fmt.Errorf("list access policies: %w", err) + } + return out, nil +} + +// AccessPolicyRevision returns the instance-wide monotonic policy revision. +func (s *Store) AccessPolicyRevision(ctx context.Context) (int64, error) { + var version int64 + if err := s.db.GetContext(ctx, &version, `SELECT version FROM governance.access_policy_revision`); err != nil { + return 0, fmt.Errorf("read access policy revision: %w", err) + } + return version, nil +} + +// PutAccessPolicy upserts p, bumps its scope version and the instance revision in one transaction. +func (s *Store) PutAccessPolicy(ctx context.Context, p PolicyRow) (int64, error) { + var version int64 + err := s.withTx(ctx, func(tx *sqlx.Tx) error { + if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, policyLockKey(p)); err != nil { + return err + } + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.access_policies (level, org_id, workspace_id, object_kind, object_id, policy_id, text) + VALUES ($1, $2, $3, $4, $5, $6, $7) + ON CONFLICT (level, org_id, workspace_id, object_kind, object_id, policy_id) + DO UPDATE SET text = EXCLUDED.text, updated_at = now()`, + p.Level, p.OrgID, p.WorkspaceID, p.ObjectKind, p.ObjectID, p.PolicyID, p.Text); err != nil { + return err + } + if err := tx.GetContext(ctx, &version, ` + INSERT INTO governance.access_policy_versions (level, org_id, workspace_id, version) + VALUES ($1, $2, $3, 2) + ON CONFLICT (level, org_id, workspace_id) + DO UPDATE SET version = governance.access_policy_versions.version + 1, updated_at = now() + RETURNING version`, p.Level, p.OrgID, p.WorkspaceID); err != nil { + return err + } + return bumpPolicyRevision(ctx, tx) + }) + if err != nil { + return 0, fmt.Errorf("put access policy: %w", err) + } + return version, nil +} + +// DeleteAccessPolicy removes one policy; found is false when absent. +func (s *Store) DeleteAccessPolicy(ctx context.Context, p PolicyRow) (found bool, err error) { + err = s.withTx(ctx, func(tx *sqlx.Tx) error { + if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, policyLockKey(p)); err != nil { + return err + } + res, err := tx.ExecContext(ctx, ` + DELETE FROM governance.access_policies + WHERE level = $1 AND org_id = $2 AND workspace_id = $3 + AND object_kind = $4 AND object_id = $5 AND policy_id = $6`, + p.Level, p.OrgID, p.WorkspaceID, p.ObjectKind, p.ObjectID, p.PolicyID) + if err != nil { + return err + } + n, err := res.RowsAffected() + if err != nil || n == 0 { + return err + } + found = true + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.access_policy_versions (level, org_id, workspace_id, version) + VALUES ($1, $2, $3, 2) + ON CONFLICT (level, org_id, workspace_id) + DO UPDATE SET version = governance.access_policy_versions.version + 1, updated_at = now()`, + p.Level, p.OrgID, p.WorkspaceID); err != nil { + return err + } + if err := cleanEmptyPolicyVersion(ctx, tx, p.Level, p.OrgID, p.WorkspaceID); err != nil { + return err + } + return bumpPolicyRevision(ctx, tx) + }) + if err != nil { + return false, fmt.Errorf("delete access policy: %w", err) + } + return found, nil +} + +// CountShippedOrgPolicies returns how many of policyIDs are present at org level for orgID. +func (s *Store) CountShippedOrgPolicies(ctx context.Context, orgID string, policyIDs []string) (int64, error) { + var count int64 + if err := s.db.GetContext(ctx, &count, ` + SELECT count(*) FROM governance.access_policies + WHERE level = 'org' AND org_id = $1 AND policy_id = ANY($2::text[])`, orgID, policyIDs); err != nil { + return 0, fmt.Errorf("count shipped org policies: %w", err) + } + return count, nil +} + +// DeleteOrgPoliciesNotShipped removes non-shipped org policies and bumps revision. +func (s *Store) DeleteOrgPoliciesNotShipped(ctx context.Context, orgID string, shippedIDs []string) error { + return s.withTx(ctx, func(tx *sqlx.Tx) error { + if _, err := tx.ExecContext(ctx, ` + DELETE FROM governance.access_policies + WHERE level = 'org' AND org_id = $1 AND NOT (policy_id = ANY($2::text[]))`, + orgID, shippedIDs); err != nil { + return err + } + if err := cleanEmptyPolicyVersion(ctx, tx, "org", orgID, ""); err != nil { + return err + } + return bumpPolicyRevision(ctx, tx) + }) +} + +// ResetInstancePolicies deletes every stored instance-level policy and bumps revision. +func (s *Store) ResetInstancePolicies(ctx context.Context) error { + return s.withTx(ctx, func(tx *sqlx.Tx) error { + if _, err := tx.ExecContext(ctx, `DELETE FROM governance.access_policies WHERE level = 'instance'`); err != nil { + return err + } + if err := cleanEmptyPolicyVersion(ctx, tx, "instance", "", ""); err != nil { + return err + } + return bumpPolicyRevision(ctx, tx) + }) +} + +// RecordDenial stores or increments a per-minute coalesced access refusal. +func (s *Store) RecordDenial(ctx context.Context, d DenialRow) error { + policies := d.Policies + if policies == nil { + policies = []string{} + } + if _, err := s.db.ExecContext(ctx, ` + INSERT INTO governance.access_denials (org_id, principal, action, resource_kind, resource_id, level, policies) + VALUES ($1, $2, $3, $4, $5, $6, $7) + ON CONFLICT (org_id, principal, action, resource_kind, resource_id, level, policies, minute_at) + DO UPDATE SET count = governance.access_denials.count + 1, updated_at = now()`, + d.OrgID, d.Principal, d.Action, d.ResourceKind, d.ResourceID, d.Level, policies); err != nil { + return fmt.Errorf("record denial: %w", err) + } + return nil +} + +// ListDenials returns an org's most recent denials, newest first. +func (s *Store) ListDenials(ctx context.Context, orgID string, limit int) ([]DenialRow, error) { + var out []DenialRow + if err := s.db.SelectContext(ctx, &out, ` + SELECT id, org_id, principal, action, resource_kind, resource_id, level, policies, minute_at, count, created_at, updated_at + FROM governance.access_denials WHERE org_id = $1 ORDER BY id DESC LIMIT $2`, orgID, limit); err != nil { + return nil, fmt.Errorf("list denials: %w", err) + } + return out, nil +} + +// PruneDenials deletes up to batch denial rows created before cutoff. +func (s *Store) PruneDenials(ctx context.Context, cutoff time.Time, batch int) (int64, error) { + res, err := s.db.ExecContext(ctx, ` + DELETE FROM governance.access_denials + WHERE id IN ( + SELECT id FROM governance.access_denials + WHERE created_at < $1 + ORDER BY created_at + LIMIT $2 + )`, cutoff.UTC(), batch) + if err != nil { + return 0, fmt.Errorf("prune denials: %w", err) + } + return res.RowsAffected() +} diff --git a/modules/governance/internal/store/accounts.go b/modules/governance/internal/store/accounts.go new file mode 100644 index 000000000..9f933fe19 --- /dev/null +++ b/modules/governance/internal/store/accounts.go @@ -0,0 +1,363 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "fmt" + "strings" + "time" + + "github.com/jmoiron/sqlx" +) + +const setupAdvisoryLock = 484726231 + +// AccountRow is a local password account in governance.accounts. +type AccountRow struct { + IdentityID string `db:"identity_id"` + Email string `db:"email"` + PasswordHash string `db:"password_hash"` + RecoveryHash sql.NullString `db:"recovery_hash"` + FailedAttempts int `db:"failed_attempts"` + LockedUntil sql.NullTime `db:"locked_until"` +} + +// AuthSettingsRow stores instance public URL and OIDC configuration. +type AuthSettingsRow struct { + PublicURL string `db:"public_url"` + OIDCIssuer string `db:"oidc_issuer"` + OIDCAudience string `db:"oidc_audience"` + OIDCClientID string `db:"oidc_client_id"` +} + +// RegisterAccountParams carries the validated inputs to create a user account. +type RegisterAccountParams struct { + IdentityID string + Email string + DisplayName string + PasswordHash string + OrgID string + OrgName string + WorkspaceID string + WorkspaceName string + PublicURL string + Role string + ActorID string + RequestID string + Bootstrap bool + Now time.Time +} + +// AccountSetupRequired reports whether no local accounts exist yet. +func (s *Store) AccountSetupRequired(ctx context.Context) (bool, error) { + var required bool + err := s.db.GetContext(ctx, &required, `SELECT NOT EXISTS (SELECT 1 FROM governance.accounts)`) + return required, err +} + +// RegisterAccount creates a local user account and its organisation membership. +func (s *Store) RegisterAccount(ctx context.Context, p RegisterAccountParams) (IdentityRow, error) { + var out IdentityRow + err := s.withTx(ctx, func(tx *sqlx.Tx) error { + if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock($1)`, setupAdvisoryLock); err != nil { + return err + } + var anyAccounts bool + if err := tx.GetContext(ctx, &anyAccounts, `SELECT EXISTS (SELECT 1 FROM governance.accounts)`); err != nil { + return err + } + if p.Bootstrap && anyAccounts { + return ErrSetupComplete + } + if !p.Bootstrap && !anyAccounts { + return ErrCredentialRejected + } + if p.Bootstrap { + if err := bootstrapOrgAndSettings(ctx, tx, p); err != nil { + return err + } + } + return writeAccountTx(ctx, tx, p, &out) + }) + return out, err +} + +func bootstrapOrgAndSettings(ctx context.Context, tx *sqlx.Tx, p RegisterAccountParams) error { + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.orgs (id, name, created_at, updated_at) VALUES ($1, $2, $3, $3) + ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, updated_at = EXCLUDED.updated_at`, + p.OrgID, p.OrgName, p.Now); err != nil { + return err + } + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.workspaces (id, org_id, name, created_at, updated_at) VALUES ($1, $2, $3, $4, $4) + ON CONFLICT (org_id, id) DO UPDATE SET name = EXCLUDED.name, updated_at = EXCLUDED.updated_at`, + p.WorkspaceID, p.OrgID, p.WorkspaceName, p.Now); err != nil { + return err + } + _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.authentication_settings (singleton, public_url) VALUES (true, $1) + ON CONFLICT (singleton) DO UPDATE SET public_url = EXCLUDED.public_url`, p.PublicURL) + return err +} + +func writeAccountTx(ctx context.Context, tx *sqlx.Tx, p RegisterAccountParams, out *IdentityRow) error { + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.identities (id, kind, display_name, lifecycle, version, created_at, updated_at) + VALUES ($1, 'user', $2, 'active', 1, $3, $3) + ON CONFLICT (id) DO UPDATE + SET display_name = EXCLUDED.display_name, lifecycle = 'active', + version = governance.identities.version + 1, updated_at = EXCLUDED.updated_at`, + p.IdentityID, p.DisplayName, p.Now); err != nil { + return err + } + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.identity_aliases (alias, identity_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`, + p.DisplayName, p.IdentityID); err != nil { + return err + } + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.accounts (identity_id, email, password_hash) VALUES ($1, $2, $3)`, + p.IdentityID, p.Email, p.PasswordHash); err != nil { + if isUniqueViolation(err) { + return ErrAlreadyExists + } + return err + } + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.memberships (identity_id, org_id, role) VALUES ($1, $2, $3) + ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO UPDATE SET role = EXCLUDED.role`, + p.IdentityID, p.OrgID, p.Role); err != nil { + return err + } + if err := insertIdentityEvent(ctx, tx, IdentityEventRow{ + IdentityID: p.IdentityID, EventType: "create", ToLifecycle: "active", + DisplayName: p.DisplayName, ActorID: p.ActorID, Source: "accounts", + RequestID: p.RequestID, At: p.Now, OrgID: sql.NullString{String: p.OrgID, Valid: true}, + }); err != nil { + return err + } + return tx.GetContext(ctx, out, `SELECT `+identityCols+` FROM governance.identities WHERE id = $1`, p.IdentityID) +} + +// SignInAccount authenticates email with verify, applies lockout rules, and opens a session. +func (s *Store) SignInAccount( + ctx context.Context, + email, tokenHash string, + expires time.Time, + verify func(passwordHash string) bool, +) (IdentityRow, error) { + tx, err := s.db.BeginTxx(ctx, nil) + if err != nil { + return IdentityRow{}, err + } + defer func() { _ = tx.Rollback() }() + + var acc AccountRow + err = tx.GetContext(ctx, &acc, ` + SELECT identity_id, email, password_hash, recovery_hash, failed_attempts, locked_until + FROM governance.accounts WHERE email = $1 FOR UPDATE`, + strings.ToLower(strings.TrimSpace(email))) + if errors.Is(err, sql.ErrNoRows) { + _ = verify("") + return IdentityRow{}, ErrCredentialRejected + } + if err != nil { + return IdentityRow{}, err + } + valid := verify(acc.PasswordHash) + if acc.LockedUntil.Valid && time.Now().Before(acc.LockedUntil.Time) { + return IdentityRow{}, ErrCredentialRejected + } + if !valid { + return IdentityRow{}, recordFailedLogin(ctx, tx, acc) + } + var id IdentityRow + if err := tx.GetContext(ctx, &id, `SELECT `+identityCols+` FROM governance.identities WHERE id = $1`, acc.IdentityID); err != nil { + return IdentityRow{}, err + } + if id.Lifecycle != "active" { + return IdentityRow{}, ErrCredentialRejected + } + if err := openSignInSessionTx(ctx, tx, acc.IdentityID, tokenHash, expires); err != nil { + return IdentityRow{}, err + } + return id, tx.Commit() +} + +func recordFailedLogin(ctx context.Context, tx *sqlx.Tx, acc AccountRow) error { + attempts := acc.FailedAttempts + if acc.LockedUntil.Valid { + attempts = 0 + } + if _, err := tx.ExecContext(ctx, ` + UPDATE governance.accounts + SET failed_attempts = $2, + locked_until = CASE WHEN $2 >= 5 THEN now() + interval '15 minutes' ELSE NULL END + WHERE identity_id = $1`, acc.IdentityID, attempts+1); err != nil { + return err + } + if err := tx.Commit(); err != nil { + return err + } + return ErrCredentialRejected +} + +func openSignInSessionTx(ctx context.Context, tx *sqlx.Tx, identityID, tokenHash string, expires time.Time) error { + if _, err := tx.ExecContext(ctx, ` + UPDATE governance.accounts SET failed_attempts = 0, locked_until = NULL WHERE identity_id = $1`, + identityID); err != nil { + return err + } + if _, err := tx.ExecContext(ctx, `DELETE FROM governance.account_sessions WHERE expires_at <= now()`); err != nil { + return err + } + _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.account_sessions (token_hash, identity_id, expires_at) VALUES ($1, $2, $3)`, + tokenHash, identityID, expires) + return err +} + +// ResolveAccountSession resolves a session token hash to its active identity. +func (s *Store) ResolveAccountSession(ctx context.Context, tokenHash string) (IdentityRow, error) { + var out IdentityRow + err := s.db.GetContext(ctx, &out, ` + SELECT i.id, i.kind, i.display_name, i.lifecycle, i.version, i.created_at, i.updated_at + FROM governance.account_sessions s + JOIN governance.identities i ON i.id = s.identity_id + WHERE s.token_hash = $1 AND s.expires_at > now() AND i.lifecycle = 'active'`, tokenHash) + if errors.Is(err, sql.ErrNoRows) { + return IdentityRow{}, ErrCredentialRejected + } + return out, err +} + +// DeleteAccountSession removes a session token. +func (s *Store) DeleteAccountSession(ctx context.Context, tokenHash string) error { + _, err := s.db.ExecContext(ctx, `DELETE FROM governance.account_sessions WHERE token_hash = $1`, tokenHash) + return err +} + +// ChangeAccountPassword verifies the current password, updates the hash, and ends sessions. +func (s *Store) ChangeAccountPassword(ctx context.Context, identityID string, verify func(oldHash string) bool, newHash string) error { + return s.withTx(ctx, func(tx *sqlx.Tx) error { + var oldHash string + err := tx.GetContext(ctx, &oldHash, ` + SELECT password_hash FROM governance.accounts WHERE identity_id = $1 FOR UPDATE`, identityID) + if errors.Is(err, sql.ErrNoRows) { + return ErrCredentialRejected + } + if err != nil { + return err + } + if !verify(oldHash) { + return ErrCredentialRejected + } + if _, err := tx.ExecContext(ctx, ` + UPDATE governance.accounts SET password_hash = $2, failed_attempts = 0, locked_until = NULL + WHERE identity_id = $1`, identityID, newHash); err != nil { + return err + } + _, err = tx.ExecContext(ctx, `DELETE FROM governance.account_sessions WHERE identity_id = $1`, identityID) + return err + }) +} + +// OpenAccountSession opens an account session for an active user identity. +func (s *Store) OpenAccountSession(ctx context.Context, identityID, tokenHash string, expires time.Time) (IdentityRow, error) { + row, err := s.GetIdentity(ctx, identityID) + if err != nil { + return IdentityRow{}, err + } + if row.Kind != "user" || row.Lifecycle != "active" { + return IdentityRow{}, ErrCredentialRejected + } + if _, err := s.db.ExecContext(ctx, ` + INSERT INTO governance.account_sessions (token_hash, identity_id, expires_at) VALUES ($1, $2, $3)`, + tokenHash, identityID, expires); err != nil { + return IdentityRow{}, err + } + return row, nil +} + +// IsFreshAccountSession reports whether tokenHash belongs to identityID and was issued within 10 minutes. +func (s *Store) IsFreshAccountSession(ctx context.Context, identityID, tokenHash string) (bool, error) { + var fresh bool + err := s.db.GetContext(ctx, &fresh, ` + SELECT EXISTS( + SELECT 1 FROM governance.account_sessions + WHERE token_hash = $1 AND identity_id = $2 + AND expires_at > now() AND issued_at > now() - interval '10 minutes' + )`, tokenHash, identityID) + return fresh, err +} + +// SetAccountRecoveryHash stores a single-use recovery secret hash on identityID's account. +func (s *Store) SetAccountRecoveryHash(ctx context.Context, identityID, recoveryHash string) error { + res, err := s.db.ExecContext(ctx, ` + UPDATE governance.accounts SET recovery_hash = $2 WHERE identity_id = $1`, identityID, recoveryHash) + if err != nil { + return err + } + n, err := res.RowsAffected() + if err != nil { + return err + } + if n != 1 { + return ErrNotFound + } + return nil +} + +// RecoverAccount consumes a recovery secret, sets newPasswordHash, and revokes sessions. +func (s *Store) RecoverAccount(ctx context.Context, email, recoveryHash, newPasswordHash string) error { + return s.withTx(ctx, func(tx *sqlx.Tx) error { + var id string + err := tx.GetContext(ctx, &id, ` + UPDATE governance.accounts a + SET password_hash = $3, recovery_hash = NULL, failed_attempts = 0, locked_until = NULL + FROM governance.identities i + WHERE a.identity_id = i.id AND i.lifecycle = 'active' + AND a.email = $1 AND a.recovery_hash = $2 + RETURNING a.identity_id`, + strings.ToLower(strings.TrimSpace(email)), recoveryHash, newPasswordHash) + if errors.Is(err, sql.ErrNoRows) { + return ErrCredentialRejected + } + if err != nil { + return err + } + _, err = tx.ExecContext(ctx, `DELETE FROM governance.account_sessions WHERE identity_id = $1`, id) + return err + }) +} + +// AuthenticationSettings returns the singleton authentication settings row. +func (s *Store) AuthenticationSettings(ctx context.Context) (AuthSettingsRow, error) { + var out AuthSettingsRow + err := s.db.GetContext(ctx, &out, ` + SELECT public_url, oidc_issuer, oidc_audience, oidc_client_id + FROM governance.authentication_settings WHERE singleton`) + if errors.Is(err, sql.ErrNoRows) { + return AuthSettingsRow{}, nil + } + if err != nil { + return AuthSettingsRow{}, fmt.Errorf("read authentication settings: %w", err) + } + return out, nil +} + +// SaveAuthenticationSettings updates authentication settings, refusing origin changes when passkeys exist. +func (s *Store) SaveAuthenticationSettings(ctx context.Context, row AuthSettingsRow) (updated bool, err error) { + res, err := s.db.ExecContext(ctx, ` + UPDATE governance.authentication_settings + SET public_url = $1, oidc_issuer = $2, oidc_audience = $3, oidc_client_id = $4 + WHERE singleton AND (public_url = $1 OR NOT EXISTS (SELECT 1 FROM governance.passkeys))`, + row.PublicURL, row.OIDCIssuer, row.OIDCAudience, row.OIDCClientID) + if err != nil { + return false, fmt.Errorf("save authentication settings: %w", err) + } + n, err := res.RowsAffected() + return n == 1, err +} diff --git a/modules/governance/internal/store/identities.go b/modules/governance/internal/store/identities.go new file mode 100644 index 000000000..4478cc8ca --- /dev/null +++ b/modules/governance/internal/store/identities.go @@ -0,0 +1,388 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "fmt" + "time" + + "github.com/jmoiron/sqlx" +) + +// IdentityRow is a persistent actor in governance.identities. +type IdentityRow struct { + ID string `db:"id"` + Kind string `db:"kind"` + DisplayName string `db:"display_name"` + Lifecycle string `db:"lifecycle"` + Version int64 `db:"version"` + CreatedAt time.Time `db:"created_at"` + UpdatedAt time.Time `db:"updated_at"` +} + +// IdentityEventRow is an audit event in governance.identity_events. +type IdentityEventRow struct { + IdentityID string `db:"identity_id"` + EventType string `db:"event_type"` + FromLifecycle string `db:"from_lifecycle"` + ToLifecycle string `db:"to_lifecycle"` + DisplayName string `db:"display_name"` + ActorID string `db:"actor_id"` + Source string `db:"source"` + RequestID string `db:"request_id"` + At time.Time `db:"at"` + OrgID sql.NullString `db:"org_id"` +} + +// SubjectRow is a provider or personal-token subject binding in governance.identity_subjects. +type SubjectRow struct { + Issuer string `db:"issuer"` + Subject string `db:"subject"` + IdentityID string `db:"identity_id"` + BoundAt time.Time `db:"bound_at"` + Name string `db:"name"` + ExpiresAt sql.NullTime `db:"expires_at"` + LastUsedAt sql.NullTime `db:"last_used_at"` +} + +const identityCols = `id, kind, display_name, lifecycle, version, created_at, updated_at` + +func auditSubjectOrg(ctx context.Context, tx *sqlx.Tx, fallbackOrg, identityID string) (sql.NullString, error) { + var single string + err := tx.GetContext(ctx, &single, ` + SELECT min(org_id)::text AS org_id + FROM ( + SELECT m.org_id FROM governance.memberships m WHERE m.identity_id = $1 + UNION + SELECT a.org_id FROM governance.org_agents a WHERE a.identity_id = $1 + ) belonging + HAVING count(DISTINCT org_id) = 1`, identityID) + switch { + case err == nil && single != "": + return sql.NullString{String: single, Valid: true}, nil + case errors.Is(err, sql.ErrNoRows) || err == nil: + if fallbackOrg == "" { + return sql.NullString{}, nil + } + return sql.NullString{String: fallbackOrg, Valid: true}, nil + default: + return sql.NullString{}, fmt.Errorf("identity audit org: %w", err) + } +} + +func insertIdentityEvent(ctx context.Context, tx *sqlx.Tx, ev IdentityEventRow) error { + _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.identity_events + (identity_id, event_type, from_lifecycle, to_lifecycle, display_name, actor_id, source, request_id, at, org_id) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`, + ev.IdentityID, ev.EventType, ev.FromLifecycle, ev.ToLifecycle, ev.DisplayName, + ev.ActorID, ev.Source, ev.RequestID, ev.At, ev.OrgID) + return err +} + +func getVisibleIdentityTx(ctx context.Context, q sqlx.ExtContext, id string, scopeOrg *string) (IdentityRow, error) { + var out IdentityRow + err := sqlx.GetContext(ctx, q, &out, ` + SELECT `+identityCols+` FROM governance.identities + WHERE id = $1 AND ($2::text IS NULL + OR EXISTS (SELECT 1 FROM governance.memberships m WHERE m.identity_id = governance.identities.id AND m.org_id = $2::text) + OR EXISTS (SELECT 1 FROM governance.org_agents a WHERE a.identity_id = governance.identities.id AND a.org_id = $2::text))`, + id, scopeOrg) + if errors.Is(err, sql.ErrNoRows) { + return IdentityRow{}, ErrNotFound + } + return out, err +} + +// ListIdentities returns identities visible to scopeOrg (or all when nil). +func (s *Store) ListIdentities(ctx context.Context, scopeOrg *string) ([]IdentityRow, error) { + var out []IdentityRow + if err := s.db.SelectContext(ctx, &out, ` + SELECT `+identityCols+` FROM governance.identities + WHERE ($1::text IS NULL + OR EXISTS (SELECT 1 FROM governance.memberships m WHERE m.identity_id = governance.identities.id AND m.org_id = $1::text) + OR EXISTS (SELECT 1 FROM governance.org_agents a WHERE a.identity_id = governance.identities.id AND a.org_id = $1::text)) + ORDER BY created_at, id`, scopeOrg); err != nil { + return nil, fmt.Errorf("list identities: %w", err) + } + return out, nil +} + +// GetIdentity returns one identity by ID without org filtering. +func (s *Store) GetIdentity(ctx context.Context, id string) (IdentityRow, error) { + var out IdentityRow + err := s.db.GetContext(ctx, &out, `SELECT `+identityCols+` FROM governance.identities WHERE id = $1`, id) + if errors.Is(err, sql.ErrNoRows) { + return IdentityRow{}, ErrNotFound + } + return out, err +} + +// GetVisibleIdentity returns one identity if visible to scopeOrg. +func (s *Store) GetVisibleIdentity(ctx context.Context, id string, scopeOrg *string) (IdentityRow, error) { + return getVisibleIdentityTx(ctx, s.db, id, scopeOrg) +} + +// ResolveIdentityAlias resolves a display-name alias case-insensitively within scopeOrg. +func (s *Store) ResolveIdentityAlias(ctx context.Context, alias string, scopeOrg *string) (IdentityRow, error) { + var out IdentityRow + err := s.db.GetContext(ctx, &out, ` + SELECT i.id, i.kind, i.display_name, i.lifecycle, i.version, i.created_at, i.updated_at + FROM governance.identities i + JOIN governance.identity_aliases a ON a.identity_id = i.id + WHERE lower(a.alias) = lower($1) AND ($2::text IS NULL + OR EXISTS (SELECT 1 FROM governance.memberships m WHERE m.identity_id = i.id AND m.org_id = $2::text) + OR EXISTS (SELECT 1 FROM governance.org_agents a WHERE a.identity_id = i.id AND a.org_id = $2::text))`, + alias, scopeOrg) + if errors.Is(err, sql.ErrNoRows) { + return IdentityRow{}, ErrNotFound + } + return out, err +} + +// CreateIdentity inserts an identity, its alias, its create event, and optionally assigns an agent. +func (s *Store) CreateIdentity(ctx context.Context, row IdentityRow, ev IdentityEventRow, fallbackOrg string, assignAgent bool) error { + return s.withTx(ctx, func(tx *sqlx.Tx) error { + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.identities (id, kind, display_name, lifecycle, version, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7)`, + row.ID, row.Kind, row.DisplayName, row.Lifecycle, row.Version, row.CreatedAt, row.UpdatedAt); err != nil { + if isUniqueViolation(err) { + return ErrAlreadyExists + } + return err + } + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.identity_aliases (alias, identity_id) VALUES ($1, $2)`, + row.DisplayName, row.ID); err != nil { + return err + } + orgID, err := auditSubjectOrg(ctx, tx, fallbackOrg, row.ID) + if err != nil { + return err + } + ev.OrgID = orgID + if err := insertIdentityEvent(ctx, tx, ev); err != nil { + return err + } + if !assignAgent { + return nil + } + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.org_agents (identity_id, org_id) VALUES ($1, $2) + ON CONFLICT (identity_id) DO UPDATE SET org_id = EXCLUDED.org_id`, row.ID, fallbackOrg); err != nil { + return err + } + _, err = tx.ExecContext(ctx, ` + INSERT INTO governance.memberships (identity_id, org_id, role) + VALUES ($1, $2, 'developer') + ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO UPDATE SET role = EXCLUDED.role`, + row.ID, fallbackOrg) + return err + }) +} + +// ApplyIdentityTransition mutates an identity under an optimistic version guard. +func (s *Store) ApplyIdentityTransition( + ctx context.Context, + id string, + expectedVersion int64, + scopeOrg *string, + transition func(IdentityRow) (IdentityRow, IdentityEventRow, error), +) (IdentityRow, error) { + var out IdentityRow + err := s.withTx(ctx, func(tx *sqlx.Tx) error { + cur, err := getVisibleIdentityTx(ctx, tx, id, scopeOrg) + if err != nil { + return err + } + if cur.Version != expectedVersion { + return ErrAlreadyExists + } + next, ev, err := transition(cur) + if err != nil { + return err + } + if err := guardLeavingActive(ctx, tx, id, cur.Lifecycle, next.Lifecycle); err != nil { + return err + } + res, err := tx.ExecContext(ctx, ` + UPDATE governance.identities + SET display_name = $2, lifecycle = $3, version = $4, updated_at = $5 + WHERE id = $1 AND version = $6`, + id, next.DisplayName, next.Lifecycle, next.Version, next.UpdatedAt, expectedVersion) + if err != nil { + return err + } + n, err := res.RowsAffected() + if err != nil || n != 1 { + return ErrAlreadyExists + } + if ev.EventType == "rename" { + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.identity_aliases (alias, identity_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`, + next.DisplayName, id); err != nil { + return err + } + } + orgID, err := auditSubjectOrg(ctx, tx, "", id) + if err != nil { + return err + } + ev.OrgID = orgID + if err := insertIdentityEvent(ctx, tx, ev); err != nil { + return err + } + out = next + return nil + }) + return out, err +} + +func guardLeavingActive(ctx context.Context, tx *sqlx.Tx, id, from, to string) error { + if to == "active" { + return nil + } + if from == "active" { + if err := keepActiveOwner(ctx, tx, id, ""); err != nil { + return err + } + } + _, err := tx.ExecContext(ctx, `DELETE FROM governance.account_sessions WHERE identity_id = $1`, id) + return err +} + +// ResolveIdentitySubject returns the identity bound to a provider subject. +func (s *Store) ResolveIdentitySubject(ctx context.Context, issuer, subject string) (IdentityRow, error) { + var out IdentityRow + err := s.db.GetContext(ctx, &out, ` + SELECT i.id, i.kind, i.display_name, i.lifecycle, i.version, i.created_at, i.updated_at + FROM governance.identities i + JOIN governance.identity_subjects b ON b.identity_id = i.id + WHERE b.issuer = $1 AND b.subject = $2`, issuer, subject) + if errors.Is(err, sql.ErrNoRows) { + return IdentityRow{}, ErrNotFound + } + return out, err +} + +// ClaimIdentitySubject moves a placeholder subject binding onto a verified subject. +func (s *Store) ClaimIdentitySubject(ctx context.Context, issuer, placeholder, subject, reqID string, boundAt time.Time) (IdentityRow, error) { + var claimed IdentityRow + err := s.withTx(ctx, func(tx *sqlx.Tx) error { + var id string + err := tx.GetContext(ctx, &id, ` + UPDATE governance.identity_subjects SET subject = $3, bound_at = $4 + WHERE issuer = $1 AND subject = $2 + RETURNING identity_id`, issuer, placeholder, subject, boundAt) + if errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } + if err != nil { + return err + } + if err := tx.GetContext(ctx, &claimed, `SELECT `+identityCols+` FROM governance.identities WHERE id = $1`, id); err != nil { + return err + } + orgID, err := auditSubjectOrg(ctx, tx, "", claimed.ID) + if err != nil { + return err + } + return insertIdentityEvent(ctx, tx, IdentityEventRow{ + IdentityID: claimed.ID, EventType: "claim_subject", + FromLifecycle: claimed.Lifecycle, ToLifecycle: claimed.Lifecycle, + DisplayName: subject, ActorID: claimed.ID, Source: "sign-in", + RequestID: reqID, At: boundAt, OrgID: orgID, + }) + }) + return claimed, err +} + +// UpsertIdentitySubject binds a subject or personal token to an identity. +func (s *Store) UpsertIdentitySubject(ctx context.Context, id string, scopeOrg *string, sub SubjectRow, ev IdentityEventRow) error { + return s.withTx(ctx, func(tx *sqlx.Tx) error { + cur, err := getVisibleIdentityTx(ctx, tx, id, scopeOrg) + if err != nil { + return err + } + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.identity_subjects (issuer, subject, identity_id, bound_at, name, expires_at) + VALUES ($1, $2, $3, $4, $5, $6) + ON CONFLICT (issuer, subject) DO UPDATE + SET identity_id = EXCLUDED.identity_id, bound_at = EXCLUDED.bound_at, + name = EXCLUDED.name, expires_at = EXCLUDED.expires_at`, + sub.Issuer, sub.Subject, id, sub.BoundAt, sub.Name, sub.ExpiresAt); err != nil { + return err + } + orgID, err := auditSubjectOrg(ctx, tx, "", id) + if err != nil { + return err + } + ev.IdentityID, ev.FromLifecycle, ev.ToLifecycle, ev.OrgID = id, cur.Lifecycle, cur.Lifecycle, orgID + return insertIdentityEvent(ctx, tx, ev) + }) +} + +// ListIdentitySubjects lists an identity's subject bindings for issuer, newest first. +func (s *Store) ListIdentitySubjects(ctx context.Context, id, issuer string) ([]SubjectRow, error) { + var out []SubjectRow + if err := s.db.SelectContext(ctx, &out, ` + SELECT issuer, subject, identity_id, bound_at, name, expires_at, last_used_at + FROM governance.identity_subjects + WHERE identity_id = $1 AND issuer = $2 + ORDER BY bound_at DESC`, id, issuer); err != nil { + return nil, fmt.Errorf("list identity subjects: %w", err) + } + return out, nil +} + +// GetIdentitySubject returns one subject binding row. +func (s *Store) GetIdentitySubject(ctx context.Context, issuer, subject string) (SubjectRow, error) { + var out SubjectRow + err := s.db.GetContext(ctx, &out, ` + SELECT issuer, subject, identity_id, bound_at, name, expires_at, last_used_at + FROM governance.identity_subjects + WHERE issuer = $1 AND subject = $2`, issuer, subject) + if errors.Is(err, sql.ErrNoRows) { + return SubjectRow{}, ErrNotFound + } + return out, err +} + +// TouchIdentitySubject updates last_used_at on a subject binding. +func (s *Store) TouchIdentitySubject(ctx context.Context, issuer, subject string, at time.Time) error { + _, err := s.db.ExecContext(ctx, ` + UPDATE governance.identity_subjects SET last_used_at = $3 WHERE issuer = $1 AND subject = $2`, + issuer, subject, at) + return err +} + +// DeleteIdentitySubject unbinds a subject or personal token from an identity. +func (s *Store) DeleteIdentitySubject(ctx context.Context, id string, scopeOrg *string, issuer, subject string, ev IdentityEventRow) error { + return s.withTx(ctx, func(tx *sqlx.Tx) error { + cur, err := getVisibleIdentityTx(ctx, tx, id, scopeOrg) + if err != nil { + return err + } + res, err := tx.ExecContext(ctx, ` + DELETE FROM governance.identity_subjects WHERE identity_id = $1 AND issuer = $2 AND subject = $3`, + id, issuer, subject) + if err != nil { + return err + } + n, err := res.RowsAffected() + if err != nil || n == 0 { + if err != nil { + return err + } + return ErrNotFound + } + orgID, err := auditSubjectOrg(ctx, tx, "", id) + if err != nil { + return err + } + ev.IdentityID, ev.FromLifecycle, ev.ToLifecycle, ev.OrgID = id, cur.Lifecycle, cur.Lifecycle, orgID + return insertIdentityEvent(ctx, tx, ev) + }) +} diff --git a/modules/governance/internal/store/orgs.go b/modules/governance/internal/store/orgs.go new file mode 100644 index 000000000..ff2a18d1c --- /dev/null +++ b/modules/governance/internal/store/orgs.go @@ -0,0 +1,297 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "fmt" + "time" + + "github.com/jmoiron/sqlx" +) + +// OrgRow is a tenant row in governance.orgs. +type OrgRow struct { + ID string `db:"id"` + Name string `db:"name"` + CreatedAt time.Time `db:"created_at"` + UpdatedAt time.Time `db:"updated_at"` +} + +// WorkspaceRow is a workspace row in governance.workspaces. +type WorkspaceRow struct { + ID string `db:"id"` + OrgID string `db:"org_id"` + Name string `db:"name"` + Environment string `db:"environment"` + CreatedAt time.Time `db:"created_at"` + UpdatedAt time.Time `db:"updated_at"` +} + +// MembershipRow is a role assignment in governance.memberships. +type MembershipRow struct { + IdentityID string `db:"identity_id"` + OrgID string `db:"org_id"` + WorkspaceID sql.NullString `db:"workspace_id"` + Role string `db:"role"` + CreatedAt time.Time `db:"created_at"` +} + +// MemberRow joins a membership with its identity's kind and display name. +type MemberRow struct { + IdentityID string `db:"identity_id"` + Kind string `db:"kind"` + DisplayName string `db:"display_name"` + WorkspaceID sql.NullString `db:"workspace_id"` + Role string `db:"role"` +} + +// AgentAssignmentRow is an agent's owning org in governance.org_agents. +type AgentAssignmentRow struct { + IdentityID string `db:"identity_id"` + OrgID string `db:"org_id"` +} + +// CreateOrg inserts an org, its default workspace, and its initial owner membership. +func (s *Store) CreateOrg(ctx context.Context, id, name, defaultWorkspaceID, ownerIdentityID string) error { + return s.withTx(ctx, func(tx *sqlx.Tx) error { + if _, err := tx.ExecContext(ctx, `INSERT INTO governance.orgs (id, name) VALUES ($1, $2)`, id, name); err != nil { + if isUniqueViolation(err) { + return fmt.Errorf("%w: %s", ErrAlreadyExists, id) + } + return fmt.Errorf("insert org: %w", err) + } + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.workspaces (id, org_id, name) VALUES ($1, $2, 'Default')`, + defaultWorkspaceID, id); err != nil { + return fmt.Errorf("insert default workspace: %w", err) + } + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.memberships (identity_id, org_id, role) + VALUES ($1, $2, 'owner') + ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO UPDATE SET role = EXCLUDED.role`, + ownerIdentityID, id); err != nil { + return fmt.Errorf("insert org owner: %w", err) + } + return nil + }) +} + +// GetOrg returns one org row; ok is false when not found. +func (s *Store) GetOrg(ctx context.Context, id string) (OrgRow, bool, error) { + var out OrgRow + err := s.db.GetContext(ctx, &out, `SELECT id, name, created_at, updated_at FROM governance.orgs WHERE id = $1`, id) + if errors.Is(err, sql.ErrNoRows) { + return OrgRow{}, false, nil + } + if err != nil { + return OrgRow{}, false, fmt.Errorf("read org: %w", err) + } + return out, true, nil +} + +// ListOrgs returns every org row, oldest first. +func (s *Store) ListOrgs(ctx context.Context) ([]OrgRow, error) { + var out []OrgRow + if err := s.db.SelectContext(ctx, &out, ` + SELECT id, name, created_at, updated_at FROM governance.orgs ORDER BY created_at, id`); err != nil { + return nil, fmt.Errorf("list orgs: %w", err) + } + return out, nil +} + +// CreateWorkspace inserts a workspace into an existing org. +func (s *Store) CreateWorkspace(ctx context.Context, w WorkspaceRow) error { + if _, ok, err := s.GetOrg(ctx, w.OrgID); err != nil { + return err + } else if !ok { + return ErrNotFound + } + if _, err := s.db.ExecContext(ctx, ` + INSERT INTO governance.workspaces (id, org_id, name, environment) VALUES ($1, $2, $3, $4)`, + w.ID, w.OrgID, w.Name, w.Environment); err != nil { + if isUniqueViolation(err) { + return fmt.Errorf("%w: %s/%s", ErrAlreadyExists, w.OrgID, w.ID) + } + return fmt.Errorf("create workspace: %w", err) + } + return nil +} + +// ListWorkspaces returns an org's workspaces, oldest first. +func (s *Store) ListWorkspaces(ctx context.Context, orgID string) ([]WorkspaceRow, error) { + var out []WorkspaceRow + if err := s.db.SelectContext(ctx, &out, ` + SELECT id, org_id, name, environment, created_at, updated_at + FROM governance.workspaces WHERE org_id = $1 ORDER BY created_at, id`, orgID); err != nil { + return nil, fmt.Errorf("list workspaces: %w", err) + } + return out, nil +} + +// keepActiveOwner refuses, inside tx, a change after which an org leaving owns +// org-wide (scoped to orgID when non-empty) has no other active owner. +func keepActiveOwner(ctx context.Context, tx *sqlx.Tx, leaving, orgID string) error { + var orgIDs []string + if err := tx.SelectContext(ctx, &orgIDs, ` + SELECT org_id FROM governance.memberships + WHERE identity_id = $1 AND workspace_id IS NULL AND role = 'owner' AND ($2 = '' OR org_id = $2)`, + leaving, orgID); err != nil { + return err + } + if len(orgIDs) == 0 { + return nil + } + if _, err := tx.ExecContext(ctx, ` + SELECT 1 FROM governance.memberships + WHERE org_id = ANY($1::text[]) AND workspace_id IS NULL AND role = 'owner' + ORDER BY org_id, identity_id FOR UPDATE`, orgIDs); err != nil { + return err + } + var stranded int + if err := tx.GetContext(ctx, &stranded, ` + SELECT count(*) FROM unnest($1::text[]) AS o(org_id) + WHERE NOT EXISTS ( + SELECT 1 FROM governance.memberships m + JOIN governance.identities i ON i.id = m.identity_id + WHERE m.org_id = o.org_id AND m.workspace_id IS NULL AND m.role = 'owner' + AND i.lifecycle = 'active' AND m.identity_id <> $2 + )`, orgIDs, leaving); err != nil { + return err + } + if stranded > 0 { + return ErrLastOwner + } + return nil +} + +// EnsureMembership grants or updates a membership role while preserving at least one active org owner. +func (s *Store) EnsureMembership(ctx context.Context, m MembershipRow) error { + if _, ok, err := s.GetOrg(ctx, m.OrgID); err != nil { + return err + } else if !ok { + return ErrNotFound + } + return s.withTx(ctx, func(tx *sqlx.Tx) error { + if (!m.WorkspaceID.Valid || m.WorkspaceID.String == "") && m.Role != "owner" { + if err := keepActiveOwner(ctx, tx, m.IdentityID, m.OrgID); err != nil { + return err + } + } + _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.memberships (identity_id, org_id, workspace_id, role) + VALUES ($1, $2, NULLIF($3, ''), $4) + ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO UPDATE SET role = EXCLUDED.role`, + m.IdentityID, m.OrgID, m.WorkspaceID.String, m.Role) + return err + }) +} + +// ListMembers returns an org's memberships joined with their identity display names. +func (s *Store) ListMembers(ctx context.Context, orgID string) ([]MemberRow, error) { + var out []MemberRow + if err := s.db.SelectContext(ctx, &out, ` + SELECT m.identity_id, i.kind, i.display_name, m.workspace_id, m.role + FROM governance.memberships m + JOIN governance.identities i ON i.id = m.identity_id + WHERE m.org_id = $1 + ORDER BY m.created_at, m.identity_id, m.workspace_id`, orgID); err != nil { + return nil, fmt.Errorf("list members: %w", err) + } + return out, nil +} + +// RemoveMembership revokes a membership while preserving at least one active org owner. +func (s *Store) RemoveMembership(ctx context.Context, identityID, orgID, workspaceID string) error { + return s.withTx(ctx, func(tx *sqlx.Tx) error { + if workspaceID == "" { + if err := keepActiveOwner(ctx, tx, identityID, orgID); err != nil { + return err + } + } + _, err := tx.ExecContext(ctx, ` + DELETE FROM governance.memberships + WHERE identity_id = $1 AND org_id = $2 AND COALESCE(workspace_id, '') = $3`, + identityID, orgID, workspaceID) + return err + }) +} + +// ListMembershipsByIdentity returns all memberships held by identityID. +func (s *Store) ListMembershipsByIdentity(ctx context.Context, identityID string) ([]MembershipRow, error) { + var out []MembershipRow + if err := s.db.SelectContext(ctx, &out, ` + SELECT identity_id, org_id, workspace_id, role, created_at + FROM governance.memberships WHERE identity_id = $1 ORDER BY created_at, org_id`, identityID); err != nil { + return nil, fmt.Errorf("list memberships: %w", err) + } + return out, nil +} + +// ListOrgAgents returns every agent assignment in orgID. +func (s *Store) ListOrgAgents(ctx context.Context, orgID string) ([]AgentAssignmentRow, error) { + var out []AgentAssignmentRow + if err := s.db.SelectContext(ctx, &out, ` + SELECT identity_id, org_id FROM governance.org_agents WHERE org_id = $1 ORDER BY identity_id`, orgID); err != nil { + return nil, fmt.Errorf("list org agents: %w", err) + } + return out, nil +} + +// AssignAgent assigns an agent identity to orgID and ensures its developer membership. +func (s *Store) AssignAgent(ctx context.Context, identityID, orgID string) error { + if _, ok, err := s.GetOrg(ctx, orgID); err != nil { + return err + } else if !ok { + return ErrNotFound + } + return s.withTx(ctx, func(tx *sqlx.Tx) error { + if _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.org_agents (identity_id, org_id) VALUES ($1, $2) + ON CONFLICT (identity_id) DO UPDATE SET org_id = EXCLUDED.org_id`, identityID, orgID); err != nil { + return err + } + _, err := tx.ExecContext(ctx, ` + INSERT INTO governance.memberships (identity_id, org_id, role) + SELECT a.identity_id, a.org_id, 'developer' FROM governance.org_agents a + WHERE a.identity_id = $1 + ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO NOTHING`, identityID) + return err + }) +} + +// EnsureAgentOrgMembership grants every assigned agent a developer membership if missing. +func (s *Store) EnsureAgentOrgMembership(ctx context.Context) error { + _, err := s.db.ExecContext(ctx, ` + INSERT INTO governance.memberships (identity_id, org_id, role) + SELECT a.identity_id, a.org_id, 'developer' FROM governance.org_agents a + ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO NOTHING`) + return err +} + +// ResolveIdentityOrg resolves the org an identity serves, falling back to defaultOrgID. +func (s *Store) ResolveIdentityOrg(ctx context.Context, identityID, defaultOrgID string) (string, error) { + var resolved string + if err := s.db.GetContext(ctx, &resolved, ` + SELECT COALESCE( + (SELECT a.org_id FROM governance.org_agents a WHERE a.identity_id = $1), + (SELECT m.org_id FROM governance.memberships m WHERE m.identity_id = $1 + ORDER BY m.created_at, m.org_id, m.workspace_id NULLS LAST LIMIT 1), + $2 + )::text AS org_id`, identityID, defaultOrgID); err != nil { + return "", fmt.Errorf("resolve identity org: %w", err) + } + return resolved, nil +} + +// ListOrgOwners returns the identity IDs holding an org-wide owner role. +func (s *Store) ListOrgOwners(ctx context.Context, orgID string) ([]string, error) { + var out []string + if err := s.db.SelectContext(ctx, &out, ` + SELECT identity_id FROM governance.memberships + WHERE org_id = $1 AND workspace_id IS NULL AND role = 'owner' + ORDER BY identity_id`, orgID); err != nil { + return nil, fmt.Errorf("list org owners: %w", err) + } + return out, nil +} diff --git a/modules/governance/internal/store/passkeys.go b/modules/governance/internal/store/passkeys.go new file mode 100644 index 000000000..abbae1f61 --- /dev/null +++ b/modules/governance/internal/store/passkeys.go @@ -0,0 +1,155 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "fmt" + "time" + + "github.com/jmoiron/sqlx" +) + +// PasskeyRow is a registered WebAuthn passkey in governance.passkeys. +type PasskeyRow struct { + CredentialID string `db:"credential_id"` + IdentityID string `db:"identity_id"` + Name string `db:"name"` + Credential []byte `db:"credential"` + CreatedAt time.Time `db:"created_at"` +} + +// CeremonyRow is an in-flight WebAuthn ceremony in governance.passkey_ceremonies. +type CeremonyRow struct { + TokenHash string `db:"token_hash"` + IdentityID string `db:"identity_id"` + Registration bool `db:"registration"` + SessionData []byte `db:"session_data"` + ExpiresAt time.Time `db:"expires_at"` +} + +// PasskeyTx runs passkey verification and persistence inside a single database transaction. +type PasskeyTx struct { + tx *sqlx.Tx +} + +// WithPasskeyTx executes fn inside a transaction that rolls back on error. +func (s *Store) WithPasskeyTx(ctx context.Context, fn func(*PasskeyTx) error) error { + return s.withTx(ctx, func(tx *sqlx.Tx) error { + return fn(&PasskeyTx{tx: tx}) + }) +} + +// LoadUser returns an active user identity and its registered WebAuthn credentials. +func (p *PasskeyTx) LoadUser(ctx context.Context, identityID string) (IdentityRow, [][]byte, error) { + return loadPasskeyUser(ctx, p.tx, identityID) +} + +// LockCredentialOwner locks a passkey row and returns its owning identity ID. +func (p *PasskeyTx) LockCredentialOwner(ctx context.Context, credentialID string) (string, error) { + var owner string + err := p.tx.GetContext(ctx, &owner, ` + SELECT identity_id FROM governance.passkeys WHERE credential_id = $1 FOR UPDATE`, credentialID) + if errors.Is(err, sql.ErrNoRows) { + return "", ErrNotFound + } + return owner, err +} + +// InsertPasskey persists a newly registered passkey credential. +func (p *PasskeyTx) InsertPasskey(ctx context.Context, row PasskeyRow) error { + _, err := p.tx.ExecContext(ctx, ` + INSERT INTO governance.passkeys (credential_id, identity_id, name, credential) VALUES ($1, $2, $3, $4)`, + row.CredentialID, row.IdentityID, row.Name, row.Credential) + return err +} + +// UpdateCredential updates the stored WebAuthn credential after a successful sign-in. +func (p *PasskeyTx) UpdateCredential(ctx context.Context, credentialID string, credential []byte) error { + _, err := p.tx.ExecContext(ctx, ` + UPDATE governance.passkeys SET credential = $2 WHERE credential_id = $1`, credentialID, credential) + return err +} + +// InsertSession records an account session created by a passkey sign-in. +func (p *PasskeyTx) InsertSession(ctx context.Context, tokenHash, identityID string, expires time.Time) error { + _, err := p.tx.ExecContext(ctx, ` + INSERT INTO governance.account_sessions (token_hash, identity_id, expires_at) VALUES ($1, $2, $3)`, + tokenHash, identityID, expires) + return err +} + +func loadPasskeyUser(ctx context.Context, q sqlx.ExtContext, identityID string) (IdentityRow, [][]byte, error) { + var row IdentityRow + err := sqlx.GetContext(ctx, q, &row, `SELECT `+identityCols+` FROM governance.identities WHERE id = $1`, identityID) + if errors.Is(err, sql.ErrNoRows) { + return IdentityRow{}, nil, ErrNotFound + } + if err != nil { + return IdentityRow{}, nil, err + } + if row.Kind != "user" || row.Lifecycle != "active" { + return IdentityRow{}, nil, ErrCredentialRejected + } + var creds [][]byte + if err := sqlx.SelectContext(ctx, q, &creds, ` + SELECT credential FROM governance.passkeys WHERE identity_id = $1 ORDER BY created_at`, identityID); err != nil { + return IdentityRow{}, nil, err + } + return row, creds, nil +} + +// LoadPasskeyUser returns an active user identity and its stored WebAuthn credentials. +func (s *Store) LoadPasskeyUser(ctx context.Context, identityID string) (IdentityRow, [][]byte, error) { + return loadPasskeyUser(ctx, s.db, identityID) +} + +// InsertPasskeyCeremony sweeps expired ceremonies and stores a new 5-minute ceremony. +func (s *Store) InsertPasskeyCeremony(ctx context.Context, tokenHash, identityID string, registration bool, sessionData []byte) error { + if _, err := s.db.ExecContext(ctx, `DELETE FROM governance.passkey_ceremonies WHERE expires_at <= now()`); err != nil { + return fmt.Errorf("sweep passkey ceremonies: %w", err) + } + if _, err := s.db.ExecContext(ctx, ` + INSERT INTO governance.passkey_ceremonies (token_hash, identity_id, registration, session_data, expires_at) + VALUES ($1, $2, $3, $4, now() + interval '5 minutes')`, + tokenHash, identityID, registration, sessionData); err != nil { + return fmt.Errorf("insert passkey ceremony: %w", err) + } + return nil +} + +// TakePasskeyCeremony consumes a live single-use ceremony. +func (s *Store) TakePasskeyCeremony(ctx context.Context, tokenHash string, registration bool) (CeremonyRow, error) { + var out CeremonyRow + err := s.db.GetContext(ctx, &out, ` + DELETE FROM governance.passkey_ceremonies + WHERE token_hash = $1 AND registration = $2 AND expires_at > now() + RETURNING token_hash, identity_id, registration, session_data, expires_at`, + tokenHash, registration) + if errors.Is(err, sql.ErrNoRows) { + return CeremonyRow{}, ErrNotFound + } + return out, err +} + +// ListPasskeys lists registered passkeys for identityID, oldest first. +func (s *Store) ListPasskeys(ctx context.Context, identityID string) ([]PasskeyRow, error) { + var out []PasskeyRow + if err := s.db.SelectContext(ctx, &out, ` + SELECT credential_id, identity_id, name, created_at FROM governance.passkeys + WHERE identity_id = $1 ORDER BY created_at`, identityID); err != nil { + return nil, fmt.Errorf("list passkeys: %w", err) + } + return out, nil +} + +// DeletePasskey removes one passkey owned by identityID. +func (s *Store) DeletePasskey(ctx context.Context, identityID, credentialID string) (bool, error) { + res, err := s.db.ExecContext(ctx, ` + DELETE FROM governance.passkeys WHERE credential_id = $1 AND identity_id = $2`, credentialID, identityID) + if err != nil { + return false, fmt.Errorf("delete passkey: %w", err) + } + n, err := res.RowsAffected() + return n == 1, err +} diff --git a/modules/governance/internal/store/people.go b/modules/governance/internal/store/people.go index 60aaa8fde..bc15ab93c 100644 --- a/modules/governance/internal/store/people.go +++ b/modules/governance/internal/store/people.go @@ -30,7 +30,7 @@ func (s *Store) People(ctx context.Context, orgID string) ([]Person, error) { Identity string `db:"identity"` } if err := s.db.SelectContext(ctx, &ids, ` - SELECT person_id, identity FROM governance.identities WHERE org_id = $1 ORDER BY identity`, orgID); err != nil { + SELECT person_id, identity FROM governance.person_identities WHERE org_id = $1 ORDER BY identity`, orgID); err != nil { return nil, fmt.Errorf("list identities: %w", err) } byID := make(map[uuid.UUID]int, len(people)) @@ -52,7 +52,7 @@ func (s *Store) PersonByIdentity(ctx context.Context, orgID, identity string) (P var p Person err := s.db.GetContext(ctx, &p, ` SELECT p.id, p.name, p.authority FROM governance.people p - JOIN governance.identities i ON i.person_id = p.id AND i.org_id = p.org_id + JOIN governance.person_identities i ON i.person_id = p.id AND i.org_id = p.org_id WHERE i.org_id = $1 AND i.identity = $2`, orgID, identity) if errors.Is(err, sql.ErrNoRows) { return Person{}, false, nil @@ -79,7 +79,7 @@ func (s *Store) ReplacePeople(ctx context.Context, orgID string, people []Person DELETE FROM governance.people WHERE org_id = $1 AND NOT (id = ANY($2))`, orgID, keep); err != nil { return fmt.Errorf("remove people: %w", err) } - if _, err := tx.ExecContext(ctx, `DELETE FROM governance.identities WHERE org_id = $1`, orgID); err != nil { + if _, err := tx.ExecContext(ctx, `DELETE FROM governance.person_identities WHERE org_id = $1`, orgID); err != nil { return fmt.Errorf("clear identities: %w", err) } for _, p := range people { @@ -91,7 +91,7 @@ func (s *Store) ReplacePeople(ctx context.Context, orgID string, people []Person } for _, identity := range p.Identities { if _, err := tx.ExecContext(ctx, ` - INSERT INTO governance.identities (org_id, identity, person_id) VALUES ($1, $2, $3)`, + INSERT INTO governance.person_identities (org_id, identity, person_id) VALUES ($1, $2, $3)`, orgID, identity, p.ID); err != nil { return fmt.Errorf("save identity %q: %w", identity, err) } diff --git a/modules/governance/live.go b/modules/governance/live.go new file mode 100644 index 000000000..e9a3e25e6 --- /dev/null +++ b/modules/governance/live.go @@ -0,0 +1,118 @@ +package governance + +import ( + "context" + "log/slog" + "sync" + "sync/atomic" + "time" +) + +const versionTimeout = 5 * time.Second + +// Live is an engine rebuilt from stored policies whenever their revision +// moves. A check that cannot read the store refuses so an edit never drops +// out behind a stale cache. +type Live struct { + version func(context.Context) (int64, error) + load func(context.Context) ([]Policy, error) + log *slog.Logger + + engine atomic.Pointer[Engine] + mu sync.Mutex + stamp atomic.Int64 +} + +// NewPending returns a chain whose engine refuses every request until the +// stored policies load. +func NewPending(version func(context.Context) (int64, error), load func(context.Context) ([]Policy, error), log *slog.Logger) *Live { + l := &Live{ + version: version, + load: func(ctx context.Context) ([]Policy, error) { + return load(WithoutPrincipal(ctx)) + }, + log: log, + } + l.engine.Store(pendingEngine) + l.stamp.Store(-1) + return l +} + +// Ready reports whether the stored policies have loaded. +func (l *Live) Ready() bool { return l.engine.Load().Ready() } + +// Reload rebuilds the engine from the store immediately. +func (l *Live) Reload(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, versionTimeout) + defer cancel() + l.mu.Lock() + defer l.mu.Unlock() + version, err := l.version(ctx) + if err != nil { + return err + } + return l.apply(ctx, version) +} + +func (l *Live) current(ctx context.Context) *Engine { + ctx, cancel := context.WithTimeout(ctx, versionTimeout) + defer cancel() + + // Read the version before the policies so a stamped engine can never hold + // content older than its stamp. + version, err := l.version(ctx) + if err != nil { + l.log.WarnContext(ctx, "access policy version unavailable; refusing until it is readable", "err", err) + return pendingEngine + } + if version == l.stamp.Load() { + return l.engine.Load() + } + l.mu.Lock() + defer l.mu.Unlock() + if version == l.stamp.Load() { + return l.engine.Load() + } + if err := l.apply(ctx, version); err != nil { + l.log.WarnContext(ctx, "access policies not reloaded; refusing until they load", "err", err) + return pendingEngine + } + return l.engine.Load() +} + +func (l *Live) apply(ctx context.Context, version int64) error { + stored, err := l.load(ctx) + if err != nil { + return err + } + engine := NewEngine(stored) + for _, problem := range engine.Problems() { + l.log.ErrorContext(ctx, "stored access policy is invalid and denies its level", + "policy", problem.Policy.ID, "level", problem.Policy.Level, "err", problem.Err) + } + l.engine.Store(engine) + l.stamp.Store(version) + return nil +} + +// Authorize evaluates the live policy chain for one request. +func (l *Live) Authorize(ctx context.Context, p Principal, a Action, r Resource, c AccessContext) Decision { + return l.current(ctx).Authorize(ctx, p, a, r, c) +} + +// AuthorizeDelivery decides whether addr may deliver an event to a source. +func (l *Live) AuthorizeDelivery(ctx context.Context, orgID OrgID, sourcePath, addr string) Decision { + return l.current(ctx).AuthorizeDelivery(ctx, orgID, sourcePath, addr) +} + +// Problems reports the current engine's invalid policies. +func (l *Live) Problems() []Problem { return l.engine.Load().Problems() } + +// StartLive loads the stored policies and keeps them current as they change. +func StartLive(ctx context.Context, list func(context.Context) ([]Policy, error), version func(context.Context) (int64, error), log *slog.Logger) *Live { + live := NewPending(version, list, log) + if err := live.Reload(ctx); err != nil { + log.WarnContext(ctx, "access policies not loaded; requests are refused until they load", "err", err) + } + return live +} diff --git a/modules/governance/org.go b/modules/governance/org.go new file mode 100644 index 000000000..442c333d6 --- /dev/null +++ b/modules/governance/org.go @@ -0,0 +1,215 @@ +package governance + +import ( + "context" + "errors" + "fmt" + "strings" +) + +// OrgID and WorkspaceID identify an organisation and a workspace. +type ( + OrgID string + WorkspaceID string +) + +// DefaultOrgID and DefaultWorkspaceID identify the default operating +// organisation and workspace. +const ( + DefaultOrgID OrgID = "org-sys" + DefaultWorkspaceID WorkspaceID = "default" +) + +var ( + ErrInvalidRole = errors.New("org: invalid role") + ErrInvalidOrg = errors.New("org: invalid org") + ErrInvalidMembership = errors.New("org: invalid membership") + ErrInvalidWorkspace = errors.New("org: invalid workspace") + ErrInvalidAssignment = errors.New("org: invalid agent assignment") + ErrOrgNotFound = errors.New("org: org not found") + ErrOrgExists = errors.New("org: org already exists") + ErrWorkspaceExists = errors.New("org: workspace already exists") + ErrMembershipExists = errors.New("org: membership already exists") + ErrLastOwner = errors.New("org: this is the organisation's last active owner; make another member owner first") +) + +// 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. +const ( + RoleOwner Role = "owner" + RoleAdmin Role = "admin" + RoleDeveloper Role = "developer" + RoleViewer Role = "viewer" +) + +// Validate reports whether r is one of the shipped roles. +func (r Role) Validate() error { + switch r { + case RoleOwner, RoleAdmin, RoleDeveloper, RoleViewer: + return nil + } + return fmt.Errorf("%w: %q", ErrInvalidRole, r) +} + +// Org is a tenant. +type Org struct { + ID OrgID `json:"id"` + Name string `json:"name"` +} + +// Validate requires an org to have an ID and a name without slashes. +func (o Org) Validate() error { + if o.ID == "" || strings.TrimSpace(o.Name) == "" { + return fmt.Errorf("%w: ID and name are required", ErrInvalidOrg) + } + if strings.Contains(string(o.ID), "/") { + return fmt.Errorf("%w: ID must not contain a slash", ErrInvalidOrg) + } + return nil +} + +// Workspace divides an organisation. Environment is a free-form attribute +// policies can test. +type Workspace struct { + ID WorkspaceID `json:"id"` + OrgID OrgID `json:"org_id"` + Name string `json:"name"` + Environment string `json:"environment,omitempty"` +} + +// Validate requires a workspace to belong to an org and have a name without slashes. +func (w Workspace) Validate() error { + if w.OrgID == "" { + return fmt.Errorf("%w: no org", ErrInvalidWorkspace) + } + if strings.TrimSpace(w.Name) == "" { + return fmt.Errorf("%w: no name", ErrInvalidWorkspace) + } + if strings.Contains(string(w.ID), "/") || strings.Contains(string(w.OrgID), "/") { + return fmt.Errorf("%w: IDs must not contain a slash", ErrInvalidWorkspace) + } + return nil +} + +// Membership gives an identity a role in an org, or in one workspace of it +// when WorkspaceID is set. +type Membership struct { + IdentityID IdentityID `json:"identity_id"` + OrgID OrgID `json:"org_id"` + WorkspaceID WorkspaceID `json:"workspace_id,omitempty"` + Role Role `json:"role"` +} + +// Validate requires an identity, an org and a valid role. +func (m Membership) Validate() error { + if m.IdentityID == "" { + return fmt.Errorf("%w: no identity", ErrInvalidMembership) + } + if m.OrgID == "" { + return fmt.Errorf("%w: no org", ErrInvalidMembership) + } + return m.Role.Validate() +} + +// Member is one identity's membership in an org or workspace. +type Member struct { + IdentityID IdentityID `json:"identity_id"` + Kind Kind `json:"kind"` + DisplayName string `json:"display_name"` + WorkspaceID WorkspaceID `json:"workspace_id,omitempty"` + Role Role `json:"role"` +} + +// AgentAssignment records the one org an agent or service identity serves. +type AgentAssignment struct { + IdentityID IdentityID `json:"identity_id"` + OrgID OrgID `json:"org_id"` +} + +// Validate requires an identity and an org. +func (a AgentAssignment) Validate() error { + if a.IdentityID == "" || a.OrgID == "" { + return fmt.Errorf("%w: identity and org are required", ErrInvalidAssignment) + } + return nil +} + +type ( + orgContextKey struct{} + scopeContextKey struct{} +) + +// WithOrg attaches the organisation a request acts in. +func WithOrg(ctx context.Context, id OrgID) context.Context { + return context.WithValue(ctx, orgContextKey{}, id) +} + +// OrgFromContext returns the organisation a request acts in, or DefaultOrgID +// when the context carries none. +func OrgFromContext(ctx context.Context) OrgID { + if id, ok := ctx.Value(orgContextKey{}).(OrgID); ok && id != "" { + return id + } + return DefaultOrgID +} + +// WithScope confines a request's reads to one org. +func WithScope(ctx context.Context, id OrgID) context.Context { + return context.WithValue(ctx, scopeContextKey{}, id) +} + +// WithoutScope lifts a request's org confinement for instance-wide reads. +func WithoutScope(ctx context.Context) context.Context { + return context.WithValue(ctx, scopeContextKey{}, OrgID("")) +} + +// InstanceScope reports whether ctx may read instance-wide records. +func InstanceScope(ctx context.Context) bool { + id, ok := Scope(ctx) + return !ok || id == DefaultOrgID +} + +// Scope returns the org WithScope confined ctx to. +func Scope(ctx context.Context) (OrgID, bool) { + id, ok := ctx.Value(scopeContextKey{}).(OrgID) + return id, ok && id != "" +} + +// OrgRepository persists organisations, workspaces, memberships and agent assignments. +type OrgRepository interface { //nolint:interfacebloat // one tenant-boundary store contract: orgs, workspaces, memberships and agent assignments + CreateOrg(context.Context, Org, IdentityID) (Org, error) + GetOrg(context.Context, OrgID) (Org, error) + ListOrgs(context.Context) ([]Org, error) + CreateWorkspace(context.Context, Workspace) (Workspace, error) + ListWorkspaces(context.Context, OrgID) ([]Workspace, error) + EnsureMembership(context.Context, Membership) error + ListMembers(context.Context, OrgID) ([]Member, error) + RemoveMembership(context.Context, Membership) error + ListOrgAgents(context.Context, OrgID) ([]AgentAssignment, error) + AssignAgent(context.Context, AgentAssignment) error + OrgForIdentity(context.Context, IdentityID) (OrgID, error) +} + +// OrgAPI is the read and write org surface exposed to callers. +type OrgAPI interface { + ListOrgs(context.Context) ([]Org, error) + GetOrg(context.Context, OrgID) (Org, error) + ListWorkspaces(context.Context, OrgID) ([]Workspace, error) + CreateWorkspace(context.Context, Workspace) (Workspace, error) + ListMembers(context.Context, OrgID) ([]Member, error) + EnsureMembership(context.Context, Membership) error + RemoveMembership(context.Context, Membership) error + AssignAgent(context.Context, AgentAssignment) error +} + +// OrgCreator creates an org with its default workspace and first owner. +type OrgCreator interface { + CreateOrg(context.Context, Org, IdentityID) (Org, error) +} + +// AgentAssignments reads authoritative agent ownership. +type AgentAssignments interface { + ListOrgAgents(context.Context, OrgID) ([]AgentAssignment, error) +} diff --git a/modules/governance/password.go b/modules/governance/password.go new file mode 100644 index 000000000..09a68c858 --- /dev/null +++ b/modules/governance/password.go @@ -0,0 +1,47 @@ +package governance + +import ( + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "fmt" + "strings" + "unicode/utf8" + + "golang.org/x/crypto/argon2" +) + +// HashPassword uses the OWASP Argon2id minimum with a fresh salt. +func HashPassword(password string) (string, error) { + if utf8.RuneCountInString(password) < 15 || len(password) > 1024 { + return "", fmt.Errorf("%w: password must have at least 15 characters and at most 1024 bytes", ErrInvalidIdentity) + } + if strings.Contains(commonPasswords, "\n"+strings.ToLower(password)+"\n") { + return "", fmt.Errorf("%w: choose a password that is not commonly used", ErrInvalidIdentity) + } + var salt [16]byte + if _, err := rand.Read(salt[:]); err != nil { + return "", err + } + key := argon2.IDKey([]byte(password), salt[:], 2, 19*1024, 1, 32) + return "$argon2id$v=19$m=19456,t=2,p=1$" + base64.RawStdEncoding.EncodeToString(salt[:]) + "$" + base64.RawStdEncoding.EncodeToString(key), nil +} + +// VerifyPassword accepts only parameters this application produces, bounding +// the work even if a stored hash is corrupted. +func VerifyPassword(password, hash string) bool { + parts := strings.Split(hash, "$") + if len(parts) != 6 || parts[1] != "argon2id" || parts[2] != "v=19" || parts[3] != "m=19456,t=2,p=1" || len(password) > 1024 { + return false + } + salt, err := base64.RawStdEncoding.DecodeString(parts[4]) + if err != nil || len(salt) != 16 { + return false + } + expected, err := base64.RawStdEncoding.DecodeString(parts[5]) + if err != nil || len(expected) != 32 { + return false + } + key := argon2.IDKey([]byte(password), salt, 2, 19*1024, 1, 32) + return subtle.ConstantTimeCompare(key, expected) == 1 +} diff --git a/modules/governance/roles.go b/modules/governance/roles.go new file mode 100644 index 000000000..0631287bb --- /dev/null +++ b/modules/governance/roles.go @@ -0,0 +1,59 @@ +package governance + +const ( + roleOwner = string(RoleOwner) + roleAdmin = string(RoleAdmin) + roleDeveloper = string(RoleDeveloper) + roleViewer = string(RoleViewer) +) + +// Shipped policy IDs overwritten by seeding and org policy resets. +const ( + PolicyOrgRead = "org-role-read" + PolicyOrgEdit = "org-role-edit" + PolicyOrgAdmin = "org-role-admin" + PolicyOrgOwner = "org-role-owner" + PolicyCrossOrgID = "instance-cross-org" +) + +const orgReadPolicy = `permit(principal, action, resource) when { + resource.org == principal.org && + ["` + roleViewer + `", "` + roleDeveloper + `", "` + roleAdmin + `", "` + roleOwner + `"].contains(principal.role) && + action in [Archie::Action::"read", Archie::Action::"read_logs"] +};` + +const orgEditPolicy = `permit(principal, action, resource) when { + resource.org == principal.org && + ["` + roleDeveloper + `", "` + roleAdmin + `", "` + roleOwner + `"].contains(principal.role) && + action in [Archie::Action::"create", Archie::Action::"update", Archie::Action::"run"] +};` + +const orgAdminPolicy = `permit(principal, action, resource) when { + resource.org == principal.org && + ["` + roleAdmin + `", "` + roleOwner + `"].contains(principal.role) && + (action != Archie::Action::"delete" || resource.kind != "org") +};` + +const orgOwnerPolicy = `permit(principal, action, resource) when { + resource.org == principal.org && + principal.role == "` + roleOwner + `" +};` + +// ShippedOrgPolicies returns the four shipped role policies for one org. +func ShippedOrgPolicies(orgID OrgID) []Policy { + return []Policy{ + {ID: PolicyOrgRead, Level: LevelOrg, OrgID: orgID, Text: orgReadPolicy}, + {ID: PolicyOrgEdit, Level: LevelOrg, OrgID: orgID, Text: orgEditPolicy}, + {ID: PolicyOrgAdmin, Level: LevelOrg, OrgID: orgID, Text: orgAdminPolicy}, + {ID: PolicyOrgOwner, Level: LevelOrg, OrgID: orgID, Text: orgOwnerPolicy}, + } +} + +// CrossOrgForbidID is the ID reported in denial records for cross-org refusals. +const CrossOrgForbidID = PolicyCrossOrgID + +// CrossOrgForbidText describes the non-removable cross-org forbid enforced +// structurally by the engine before Cedar evaluation. +const CrossOrgForbidText = `forbid(principal, action, resource) when { + resource.org != principal.org; +};` diff --git a/modules/governance/store_access.go b/modules/governance/store_access.go new file mode 100644 index 000000000..352ab13bb --- /dev/null +++ b/modules/governance/store_access.go @@ -0,0 +1,199 @@ +package governance + +import ( + "context" + "fmt" + "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, 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 { + return 0, err + } + return m.store.PutAccessPolicy(ctx, policyToRow(p)) +} + +// DeletePolicy removes one stored policy or returns ErrPolicyNotFound. +func (m *Module) DeletePolicy(ctx context.Context, p Policy) error { + if err := p.Validate(); 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 an org's shipped role policies when none exist yet. +func (m *Module) EnsureShippedOrgPolicies(ctx context.Context, orgID OrgID) error { + count, err := m.store.CountShippedOrgPolicies(ctx, string(orgID), shippedOrgPolicyIDs()) + if err != nil { + return err + } + if count > 0 { + return nil + } + for _, p := range ShippedOrgPolicies(orgID) { + if _, err := m.PutPolicy(ctx, 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.PutPolicy(ctx, p); err != nil { + return err + } + } + return nil +} + +// 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 + } + } +} diff --git a/modules/governance/store_identities.go b/modules/governance/store_identities.go new file mode 100644 index 000000000..8f65ef520 --- /dev/null +++ b/modules/governance/store_identities.go @@ -0,0 +1,798 @@ +package governance + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "database/sql" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net" + "net/url" + "strings" + "time" + + "github.com/go-webauthn/webauthn/protocol" + "github.com/go-webauthn/webauthn/webauthn" + + "github.com/samcharles93/archie-core/modules/governance/internal/store" +) + +var ( + _ IdentityRepository = (*Module)(nil) + _ SubjectResolver = (*Module)(nil) + _ SubjectBinding = (*Module)(nil) + _ PersonalTokenStore = (*Module)(nil) + _ PersonalTokens = (*Module)(nil) + _ Accounts = (*Module)(nil) + _ AccountSecurity = (*Module)(nil) + _ AuthenticationSettingsStore = (*Module)(nil) + _ Passkeys = (*Module)(nil) +) + +func scopeOrgFilter(ctx context.Context) *string { + if InstanceScope(ctx) { + return nil + } + id, ok := Scope(ctx) + if !ok { + return nil + } + s := string(id) + return &s +} + +func identityFromRow(r store.IdentityRow) Identity { + return Identity{ + ID: IdentityID(r.ID), + Kind: Kind(r.Kind), + DisplayName: r.DisplayName, + Lifecycle: Lifecycle(r.Lifecycle), + Version: r.Version, + CreatedAt: r.CreatedAt, + UpdatedAt: r.UpdatedAt, + } +} + +func identityToRow(i Identity) store.IdentityRow { + return store.IdentityRow{ + ID: string(i.ID), + Kind: string(i.Kind), + DisplayName: i.DisplayName, + Lifecycle: string(i.Lifecycle), + Version: i.Version, + CreatedAt: i.CreatedAt, + UpdatedAt: i.UpdatedAt, + } +} + +func mapIdentityErr(err error) error { + switch { + case errors.Is(err, store.ErrNotFound): + return ErrIdentityNotFound + case errors.Is(err, store.ErrAlreadyExists): + return ErrIdentityConflict + case errors.Is(err, store.ErrLastOwner): + return ErrLastOwner + case errors.Is(err, store.ErrSetupComplete): + return ErrSetupComplete + case errors.Is(err, store.ErrCredentialRejected): + return ErrCredentialRejected + default: + return err + } +} + +func checkAudit(audit IdentityAudit) (time.Time, error) { + if audit.ActorID == "" || audit.Source == "" || audit.RequestID == "" { + return time.Time{}, fmt.Errorf("%w: audit actor, source, and request ID are required", ErrInvalidIdentity) + } + now := audit.At.UTC() + if now.IsZero() { + now = time.Now().UTC() + } + return now, nil +} + +func sessionHash(token string) string { + sum := sha256.Sum256([]byte(token)) + return hex.EncodeToString(sum[:]) +} + +// List returns every identity visible to the caller's scope. +func (m *Module) List(ctx context.Context) ([]Identity, error) { + rows, err := m.store.ListIdentities(ctx, scopeOrgFilter(ctx)) + if err != nil { + return nil, err + } + out := make([]Identity, 0, len(rows)) + for _, r := range rows { + out = append(out, identityFromRow(r)) + } + return out, nil +} + +// Get returns one identity by ID if visible to the caller's scope. +func (m *Module) Get(ctx context.Context, id IdentityID) (Identity, error) { + row, err := m.store.GetVisibleIdentity(ctx, string(id), scopeOrgFilter(ctx)) + if err != nil { + return Identity{}, mapIdentityErr(err) + } + return identityFromRow(row), nil +} + +// ResolveLegacyName resolves an identity by display-name alias. +func (m *Module) ResolveLegacyName(ctx context.Context, name string) (Identity, error) { + row, err := m.store.ResolveIdentityAlias(ctx, strings.TrimSpace(name), scopeOrgFilter(ctx)) + if err != nil { + return Identity{}, mapIdentityErr(err) + } + return identityFromRow(row), nil +} + +// Create inserts a new identity and assigns agents to the acting organisation. +func (m *Module) Create(ctx context.Context, value Identity, audit IdentityAudit) (Identity, error) { + if err := value.Validate(); err != nil { + return Identity{}, err + } + now, err := checkAudit(audit) + if err != nil { + return Identity{}, err + } + value.Version, value.CreatedAt, value.UpdatedAt = 1, now, now + ev := store.IdentityEventRow{ + IdentityID: string(value.ID), + EventType: "create", + ToLifecycle: string(value.Lifecycle), + DisplayName: value.DisplayName, + ActorID: string(audit.ActorID), + Source: audit.Source, + RequestID: audit.RequestID, + At: now, + } + if err := m.store.CreateIdentity(ctx, identityToRow(value), ev, string(OrgFromContext(ctx)), value.Kind.Agent()); err != nil { + return Identity{}, mapIdentityErr(err) + } + return value, nil +} + +// Apply transitions an identity under an optimistic version guard. +func (m *Module) Apply(ctx context.Context, id IdentityID, expectedVersion int64, command IdentityCommand, audit IdentityAudit) (Identity, error) { + now, err := checkAudit(audit) + if err != nil { + return Identity{}, err + } + row, err := m.store.ApplyIdentityTransition(ctx, string(id), expectedVersion, scopeOrgFilter(ctx), + func(cur store.IdentityRow) (store.IdentityRow, store.IdentityEventRow, error) { + next, ev, err := ApplyIdentity(identityFromRow(cur), command) + if err != nil { + return store.IdentityRow{}, store.IdentityEventRow{}, err + } + next.UpdatedAt = now + return identityToRow(next), store.IdentityEventRow{ + IdentityID: string(id), + EventType: string(ev.Type), + FromLifecycle: string(ev.From), + ToLifecycle: string(ev.To), + DisplayName: ev.DisplayName, + ActorID: string(audit.ActorID), + Source: audit.Source, + RequestID: audit.RequestID, + At: now, + }, nil + }) + if err != nil { + return Identity{}, mapIdentityErr(err) + } + return identityFromRow(row), nil +} + +// ResolveSubject returns the identity bound to a provider subject. +func (m *Module) ResolveSubject(ctx context.Context, subject Subject) (Identity, error) { + row, err := m.store.ResolveIdentitySubject(ctx, subject.Issuer, subject.Subject) + if err != nil { + return Identity{}, mapIdentityErr(err) + } + return identityFromRow(row), nil +} + +// ClaimSubject moves a placeholder email binding onto a verified subject. +func (m *Module) ClaimSubject(ctx context.Context, placeholder, subject Subject) (Identity, error) { + if err := subject.Validate(); err != nil { + return Identity{}, err + } + row, err := m.store.ClaimIdentitySubject(ctx, placeholder.Issuer, placeholder.Subject, subject.Subject, placeholder.Subject, time.Now().UTC()) + if err != nil { + return Identity{}, mapIdentityErr(err) + } + return identityFromRow(row), nil +} + +// BindSubject binds an identity to a provider subject. +func (m *Module) BindSubject(ctx context.Context, id IdentityID, subject Subject, audit IdentityAudit) error { + return m.BindPersonalToken(ctx, id, subject, "", nil, audit) +} + +// BindPersonalToken binds a personal API token subject with optional name and expiry. +func (m *Module) BindPersonalToken(ctx context.Context, id IdentityID, subject Subject, name string, expiresAt *time.Time, audit IdentityAudit) error { + if err := subject.Validate(); err != nil { + return err + } + now, err := checkAudit(audit) + if err != nil { + return err + } + var exp sql.NullTime + if expiresAt != nil { + exp = sql.NullTime{Time: expiresAt.UTC(), Valid: true} + } + sub := store.SubjectRow{ + Issuer: subject.Issuer, + Subject: subject.Subject, + BoundAt: now, + Name: name, + ExpiresAt: exp, + } + ev := store.IdentityEventRow{ + EventType: "bind_subject", + DisplayName: subject.Subject, + ActorID: string(audit.ActorID), + Source: audit.Source, + RequestID: audit.RequestID, + At: now, + } + return mapIdentityErr(m.store.UpsertIdentitySubject(ctx, string(id), scopeOrgFilter(ctx), sub, ev)) +} + +// SubjectsOf lists an identity's subject bindings under issuer. +func (m *Module) SubjectsOf(ctx context.Context, id IdentityID, issuer string) ([]PersonalToken, error) { + rows, err := m.store.ListIdentitySubjects(ctx, string(id), issuer) + if err != nil { + return nil, err + } + out := make([]PersonalToken, 0, len(rows)) + for _, r := range rows { + out = append(out, personalTokenFromRow(r)) + } + return out, nil +} + +// PersonalTokenOf looks up one personal token subject binding. +func (m *Module) PersonalTokenOf(ctx context.Context, subject Subject) (PersonalToken, error) { + row, err := m.store.GetIdentitySubject(ctx, subject.Issuer, subject.Subject) + if err != nil { + return PersonalToken{}, mapIdentityErr(err) + } + return personalTokenFromRow(row), nil +} + +// TouchPersonalToken records when a personal token last authenticated. +func (m *Module) TouchPersonalToken(ctx context.Context, subject Subject, at time.Time) error { + return m.store.TouchIdentitySubject(ctx, subject.Issuer, subject.Subject, at.UTC()) +} + +// UnbindSubject removes a subject binding owned by id. +func (m *Module) UnbindSubject(ctx context.Context, id IdentityID, subject Subject, audit IdentityAudit) error { + now, err := checkAudit(audit) + if err != nil { + return err + } + ev := store.IdentityEventRow{ + EventType: "unbind_subject", + DisplayName: subject.Subject, + ActorID: string(audit.ActorID), + Source: audit.Source, + RequestID: audit.RequestID, + At: now, + } + return mapIdentityErr(m.store.DeleteIdentitySubject(ctx, string(id), scopeOrgFilter(ctx), subject.Issuer, subject.Subject, ev)) +} + +func personalTokenFromRow(r store.SubjectRow) PersonalToken { + tok := PersonalToken{ID: r.Subject, Name: r.Name, CreatedAt: r.BoundAt} + if r.ExpiresAt.Valid { + t := r.ExpiresAt.Time + tok.ExpiresAt = &t + } + if r.LastUsedAt.Valid { + t := r.LastUsedAt.Time + tok.LastUsedAt = &t + } + return tok +} + +// AddPersonalToken binds a personal API token for the authenticated caller. +func (m *Module) AddPersonalToken(ctx context.Context, subject Subject, name string, expiresAt *time.Time) error { + p, ok := PrincipalFromContext(ctx) + if !ok || p.IdentityID == "" || p.IdentityID == SystemID { + return ErrCredentialRejected + } + return m.BindPersonalToken(ctx, p.IdentityID, subject, name, expiresAt, IdentityAudit{ + ActorID: p.IdentityID, + Source: "personal-token", + RequestID: "pat-bind:" + rand.Text(), + }) +} + +// ListPersonalTokens lists the authenticated caller's personal API tokens. +func (m *Module) ListPersonalTokens(ctx context.Context) ([]PersonalToken, error) { + p, ok := PrincipalFromContext(ctx) + if !ok || p.IdentityID == "" || p.IdentityID == SystemID { + return nil, ErrCredentialRejected + } + return m.SubjectsOf(ctx, p.IdentityID, PersonalTokenIssuer) +} + +// RevokePersonalToken revokes one personal API token held by the authenticated caller. +func (m *Module) RevokePersonalToken(ctx context.Context, id string) error { + p, ok := PrincipalFromContext(ctx) + if !ok || p.IdentityID == "" || p.IdentityID == SystemID { + return ErrCredentialRejected + } + return m.UnbindSubject(ctx, p.IdentityID, Subject{Issuer: PersonalTokenIssuer, Subject: id}, IdentityAudit{ + ActorID: p.IdentityID, + Source: "personal-token", + RequestID: "pat-revoke:" + rand.Text(), + }) +} + +// AccountSetupRequired reports whether initial owner account setup is needed. +func (m *Module) AccountSetupRequired(ctx context.Context) (bool, error) { + return m.store.AccountSetupRequired(ctx) +} + +// RegisterAccount creates a user account, bootstrapping the operating org when bootstrap is true. +func (m *Module) RegisterAccount(ctx context.Context, r AccountRegistration, bootstrap bool) (Identity, error) { + role, orgID, err := registrationScope(ctx, &r, bootstrap) + if err != nil { + return Identity{}, err + } + hash, err := HashPassword(r.Password) + if err != nil { + return Identity{}, err + } + id := IdentityID(rand.Text()) + if bootstrap { + id = OperatorID() + } + if _, err := NewIdentity(id, KindUser, r.DisplayName); err != nil { + return Identity{}, err + } + actor := id + if p, ok := PrincipalFromContext(ctx); ok { + actor = p.IdentityID + } + row, err := m.store.RegisterAccount(ctx, store.RegisterAccountParams{ + IdentityID: string(id), Email: r.Email, DisplayName: r.DisplayName, + PasswordHash: hash, OrgID: string(orgID), OrgName: r.OrganisationName, + WorkspaceID: string(DefaultWorkspaceID), WorkspaceName: r.WorkspaceName, + PublicURL: r.PublicURL, Role: string(role), ActorID: string(actor), + RequestID: "account:" + rand.Text(), Bootstrap: bootstrap, Now: time.Now().UTC(), + }) + if err != nil { + return Identity{}, mapIdentityErr(err) + } + return identityFromRow(row), nil +} + +func registrationScope(ctx context.Context, r *AccountRegistration, bootstrap bool) (Role, OrgID, error) { + if err := r.Validate(); err != nil { + return "", "", err + } + if bootstrap { + r.OrganisationName = strings.TrimSpace(r.OrganisationName) + r.WorkspaceName = strings.TrimSpace(r.WorkspaceName) + r.PublicURL = strings.TrimRight(r.PublicURL, "/") + if r.WorkspaceName == "" || len(r.WorkspaceName) > 200 || r.OrganisationName == "" || len(r.OrganisationName) > 200 { + return "", "", ErrInvalidIdentity + } + if err := (AuthenticationSettings{PublicURL: r.PublicURL}).Validate(); err != nil { + return "", "", err + } + return RoleOwner, DefaultOrgID, nil + } + orgID := OrgFromContext(ctx) + p, ok := PrincipalFromContext(ctx) + if !ok || p.Org != orgID { + return "", "", ErrCredentialRejected + } + role := Role(r.Role) + if role != RoleAdmin && role != RoleDeveloper && role != RoleViewer { + return "", "", ErrInvalidIdentity + } + return role, orgID, nil +} + +// SignInAccount verifies email and password and opens a session. +func (m *Module) SignInAccount(ctx context.Context, email, password string) (AccountSession, error) { + token := rand.Text() + expires := time.Now().UTC().Add(AccountSessionLifetime) + row, err := m.store.SignInAccount(ctx, email, sessionHash(token), expires, func(hash string) bool { + if hash == "" { + _, _ = HashPassword("unknown account dummy password") + return false + } + return VerifyPassword(password, hash) + }) + if err != nil { + return AccountSession{}, mapIdentityErr(err) + } + return AccountSession{Identity: identityFromRow(row), Token: token, Expires: expires}, nil +} + +// ResolveAccountSession resolves a session token to its active identity. +func (m *Module) ResolveAccountSession(ctx context.Context, token string) (Identity, error) { + if len(token) < 26 || len(token) > 128 { + return Identity{}, ErrCredentialRejected + } + row, err := m.store.ResolveAccountSession(ctx, sessionHash(token)) + if err != nil { + return Identity{}, mapIdentityErr(err) + } + return identityFromRow(row), nil +} + +// SignOutAccount deletes the session associated with token. +func (m *Module) SignOutAccount(ctx context.Context, token string) error { + return m.store.DeleteAccountSession(ctx, sessionHash(token)) +} + +// ChangeAccountPassword verifies current, sets next, and revokes active sessions. +func (m *Module) ChangeAccountPassword(ctx context.Context, current, next string) error { + p, ok := PrincipalFromContext(ctx) + if !ok { + return ErrCredentialRejected + } + hash, err := HashPassword(next) + if err != nil { + return err + } + return mapIdentityErr(m.store.ChangeAccountPassword(ctx, string(p.IdentityID), func(oldHash string) bool { + return VerifyPassword(current, oldHash) + }, hash)) +} + +// OpenAccountSession creates a session bounded by expires for the current principal. +func (m *Module) OpenAccountSession(ctx context.Context, expires time.Time) (AccountSession, error) { + p, ok := PrincipalFromContext(ctx) + if !ok { + return AccountSession{}, ErrCredentialRejected + } + if expires.IsZero() || !expires.After(time.Now()) { + return AccountSession{}, ErrCredentialRejected + } + maxExpires := time.Now().UTC().Add(AccountSessionLifetime) + if maxExpires.Before(expires) { + expires = maxExpires + } + token := rand.Text() + row, err := m.store.OpenAccountSession(ctx, string(p.IdentityID), sessionHash(token), expires) + if err != nil { + return AccountSession{}, mapIdentityErr(err) + } + return AccountSession{Identity: identityFromRow(row), Token: token, Expires: expires}, nil +} + +// RequireFreshAccountSession requires token to have been issued within the last 10 minutes. +func (m *Module) RequireFreshAccountSession(ctx context.Context, token string) error { + p, ok := PrincipalFromContext(ctx) + if !ok { + return ErrCredentialRejected + } + fresh, err := m.store.IsFreshAccountSession(ctx, string(p.IdentityID), sessionHash(token)) + if err != nil { + return err + } + if !fresh { + return ErrCredentialRejected + } + return nil +} + +// CreateAccountRecovery issues a one-time recovery secret for the current principal. +func (m *Module) CreateAccountRecovery(ctx context.Context) (string, error) { + p, ok := PrincipalFromContext(ctx) + if !ok { + return "", ErrCredentialRejected + } + code := rand.Text() + rand.Text() + if err := m.store.SetAccountRecoveryHash(ctx, string(p.IdentityID), sessionHash(code)); err != nil { + return "", mapIdentityErr(err) + } + return code, nil +} + +// RecoverAccount consumes code and resets email's password. +func (m *Module) RecoverAccount(ctx context.Context, email, code, password string) error { + if len(code) < 52 || len(code) > 128 { + return ErrCredentialRejected + } + hash, err := HashPassword(password) + if err != nil { + return err + } + return mapIdentityErr(m.store.RecoverAccount(ctx, email, sessionHash(code), hash)) +} + +// AuthenticationSettings returns the instance authentication settings. +func (m *Module) AuthenticationSettings(ctx context.Context) (AuthenticationSettings, error) { + row, err := m.store.AuthenticationSettings(ctx) + if err != nil { + return AuthenticationSettings{}, err + } + return AuthenticationSettings{ + PublicURL: row.PublicURL, + OIDCIssuer: row.OIDCIssuer, + OIDCAudience: row.OIDCAudience, + OIDCClientID: row.OIDCClientID, + }, nil +} + +// SaveAuthenticationSettings validates and persists instance authentication settings. +func (m *Module) SaveAuthenticationSettings(ctx context.Context, value AuthenticationSettings) error { + p, ok := PrincipalFromContext(ctx) + if !ok || !p.InstanceAdmin() { + return ErrCredentialRejected + } + value.PublicURL = strings.TrimRight(value.PublicURL, "/") + if err := value.Validate(); err != nil { + return err + } + updated, err := m.store.SaveAuthenticationSettings(ctx, store.AuthSettingsRow{ + PublicURL: value.PublicURL, + OIDCIssuer: value.OIDCIssuer, + OIDCAudience: value.OIDCAudience, + OIDCClientID: value.OIDCClientID, + }) + if err != nil { + return err + } + if !updated { + return ErrInvalidIdentity + } + return nil +} + +type passkeyUser struct { + value Identity + credentials []webauthn.Credential +} + +func (u passkeyUser) WebAuthnID() []byte { return []byte(u.value.ID) } +func (u passkeyUser) WebAuthnName() string { return u.value.DisplayName } +func (u passkeyUser) WebAuthnDisplayName() string { return u.value.DisplayName } +func (u passkeyUser) WebAuthnCredentials() []webauthn.Credential { return u.credentials } + +func decodePasskeyUser(row store.IdentityRow, rawCreds [][]byte) (passkeyUser, error) { + user := passkeyUser{value: identityFromRow(row)} + for _, data := range rawCreds { + var cred webauthn.Credential + if err := json.Unmarshal(data, &cred); err != nil { + return passkeyUser{}, err + } + user.credentials = append(user.credentials, cred) + } + return user, nil +} + +func (m *Module) webAuthn(ctx context.Context) (*webauthn.WebAuthn, error) { + settings, err := m.AuthenticationSettings(ctx) + if err != nil { + return nil, err + } + u, err := url.Parse(settings.PublicURL) + secure := err == nil && (u.Scheme == "https" || (u.Scheme == "http" && u.Hostname() == "localhost")) + if !secure || u.Hostname() == "" || net.ParseIP(u.Hostname()) != nil { + return nil, ErrInvalidIdentity + } + return webauthn.New(&webauthn.Config{ + RPDisplayName: "Archie", + RPID: u.Hostname(), + RPOrigins: []string{strings.TrimRight(settings.PublicURL, "/")}, + AuthenticatorSelection: protocol.AuthenticatorSelection{ + UserVerification: protocol.VerificationRequired, + ResidentKey: protocol.ResidentKeyRequirementRequired, + }, + }) +} + +// BeginPasskey starts a WebAuthn passkey registration or discoverable login ceremony. +func (m *Module) BeginPasskey(ctx context.Context, registration bool) (PasskeyCeremony, error) { + wa, err := m.webAuthn(ctx) + if err != nil { + return PasskeyCeremony{}, err + } + var ( + options any + session *webauthn.SessionData + owner string + ) + if registration { + p, ok := PrincipalFromContext(ctx) + if !ok { + return PasskeyCeremony{}, ErrCredentialRejected + } + owner = string(p.IdentityID) + row, creds, loadErr := m.store.LoadPasskeyUser(ctx, owner) + if loadErr != nil { + return PasskeyCeremony{}, mapIdentityErr(loadErr) + } + user, decErr := decodePasskeyUser(row, creds) + if decErr != nil { + return PasskeyCeremony{}, decErr + } + options, session, err = wa.BeginRegistration(user) + } else { + options, session, err = wa.BeginDiscoverableLogin(webauthn.WithUserVerification(protocol.VerificationRequired)) + } + if err != nil { + return PasskeyCeremony{}, err + } + data, err := json.Marshal(session) + if err != nil { + return PasskeyCeremony{}, err + } + encoded, err := json.Marshal(options) + if err != nil { + return PasskeyCeremony{}, err + } + token := rand.Text() + if err := m.store.InsertPasskeyCeremony(ctx, sessionHash(token), owner, registration, data); err != nil { + return PasskeyCeremony{}, err + } + return PasskeyCeremony{Token: token, Options: encoded}, nil +} + +// FinishPasskey completes a WebAuthn passkey ceremony and issues a session on sign-in. +func (m *Module) FinishPasskey(ctx context.Context, token string, response []byte, registration bool, name string) (AccountSession, error) { + wa, err := m.webAuthn(ctx) + if err != nil { + return AccountSession{}, err + } + ceremony, err := m.store.TakePasskeyCeremony(ctx, sessionHash(token), registration) + if err != nil { + return AccountSession{}, mapIdentityErr(err) + } + var session webauthn.SessionData + if err := json.Unmarshal(ceremony.SessionData, &session); err != nil { + return AccountSession{}, err + } + var result AccountSession + err = m.store.WithPasskeyTx(ctx, func(pt *store.PasskeyTx) error { + cred, user, verifyErr := verifyPasskeyTx(ctx, pt, wa, ceremony.IdentityID, session, response, registration) + if verifyErr != nil || cred == nil || cred.Authenticator.CloneWarning { + return ErrCredentialRejected + } + if err := persistPasskeyTx(ctx, pt, cred, string(user.value.ID), name, registration); err != nil { + return err + } + result = AccountSession{Identity: user.value} + if !registration { + result.Token = rand.Text() + result.Expires = time.Now().UTC().Add(AccountSessionLifetime) + return pt.InsertSession(ctx, sessionHash(result.Token), string(user.value.ID), result.Expires) + } + return nil + }) + return result, mapIdentityErr(err) +} + +func verifyPasskeyTx( + ctx context.Context, + pt *store.PasskeyTx, + wa *webauthn.WebAuthn, + owner string, + session webauthn.SessionData, + response []byte, + registration bool, +) (*webauthn.Credential, passkeyUser, error) { + if registration { + return verifyPasskeyRegistrationTx(ctx, pt, wa, owner, session, response) + } + parsed, err := protocol.ParseCredentialRequestResponseBytes(response) + if err != nil { + return nil, passkeyUser{}, ErrCredentialRejected + } + var user passkeyUser + cred, err := wa.ValidateDiscoverableLogin(func(rawID, userHandle []byte) (webauthn.User, error) { + credOwner, err := pt.LockCredentialOwner(ctx, base64.RawURLEncoding.EncodeToString(rawID)) + if err != nil || credOwner != string(userHandle) { + return nil, ErrCredentialRejected + } + row, rawCreds, err := pt.LoadUser(ctx, credOwner) + if err != nil { + return nil, ErrCredentialRejected + } + user, err = decodePasskeyUser(row, rawCreds) + return user, err + }, session, parsed) + return cred, user, err +} + +func verifyPasskeyRegistrationTx( + ctx context.Context, + pt *store.PasskeyTx, + wa *webauthn.WebAuthn, + owner string, + session webauthn.SessionData, + response []byte, +) (*webauthn.Credential, passkeyUser, error) { + p, ok := PrincipalFromContext(ctx) + if !ok || string(p.IdentityID) != owner { + return nil, passkeyUser{}, ErrCredentialRejected + } + row, rawCreds, err := pt.LoadUser(ctx, owner) + if err != nil { + return nil, passkeyUser{}, err + } + user, err := decodePasskeyUser(row, rawCreds) + if err != nil { + return nil, passkeyUser{}, err + } + parsed, err := protocol.ParseCredentialCreationResponseBytes(response) + if err != nil { + return nil, user, ErrCredentialRejected + } + cred, err := wa.CreateCredential(user, session, parsed) + return cred, user, err +} + +func persistPasskeyTx(ctx context.Context, pt *store.PasskeyTx, cred *webauthn.Credential, owner, name string, registration bool) error { + encoded, err := json.Marshal(cred) + if err != nil { + return err + } + credID := base64.RawURLEncoding.EncodeToString(cred.ID) + if !registration { + return pt.UpdateCredential(ctx, credID, encoded) + } + name = strings.TrimSpace(name) + if name == "" { + name = "Passkey" + } + if len(name) > 200 { + return ErrInvalidIdentity + } + return pt.InsertPasskey(ctx, store.PasskeyRow{ + CredentialID: credID, + IdentityID: owner, + Name: name, + Credential: encoded, + }) +} + +// ListPasskeys lists the authenticated caller's registered passkeys. +func (m *Module) ListPasskeys(ctx context.Context) ([]Passkey, error) { + p, ok := PrincipalFromContext(ctx) + if !ok { + return nil, ErrCredentialRejected + } + rows, err := m.store.ListPasskeys(ctx, string(p.IdentityID)) + if err != nil { + return nil, err + } + out := make([]Passkey, 0, len(rows)) + for _, r := range rows { + out = append(out, Passkey{ID: r.CredentialID, Name: r.Name}) + } + return out, nil +} + +// DeletePasskey removes one passkey owned by the authenticated caller. +func (m *Module) DeletePasskey(ctx context.Context, id string) error { + p, ok := PrincipalFromContext(ctx) + if !ok { + return ErrCredentialRejected + } + found, err := m.store.DeletePasskey(ctx, string(p.IdentityID), id) + if err != nil { + return err + } + if !found { + return ErrIdentityNotFound + } + return nil +} diff --git a/modules/governance/store_orgs.go b/modules/governance/store_orgs.go new file mode 100644 index 000000000..217b0be78 --- /dev/null +++ b/modules/governance/store_orgs.go @@ -0,0 +1,231 @@ +package governance + +import ( + "context" + "database/sql" + "errors" + "fmt" + + "github.com/samcharles93/archie-core/modules/governance/internal/store" +) + +var ( + _ OrgRepository = (*Module)(nil) + _ WorkspaceLister = (*Module)(nil) + _ PrincipalSource = (*Module)(nil) +) + +// CreateOrg creates an organisation with its default workspace and owner membership. +func (m *Module) CreateOrg(ctx context.Context, value Org, owner IdentityID) (Org, error) { + if err := value.Validate(); err != nil { + return Org{}, err + } + if err := (Membership{IdentityID: owner, OrgID: value.ID, Role: RoleOwner}).Validate(); err != nil { + return Org{}, err + } + err := m.store.CreateOrg(ctx, string(value.ID), value.Name, string(DefaultWorkspaceID), string(owner)) + if errors.Is(err, store.ErrAlreadyExists) { + return Org{}, fmt.Errorf("%w: %s", ErrOrgExists, value.ID) + } + if err != nil { + return Org{}, err + } + return value, nil +} + +// GetOrg returns one org by ID or ErrOrgNotFound. +func (m *Module) GetOrg(ctx context.Context, id OrgID) (Org, error) { + row, ok, err := m.store.GetOrg(ctx, string(id)) + if err != nil { + return Org{}, err + } + if !ok { + return Org{}, ErrOrgNotFound + } + return Org{ID: OrgID(row.ID), Name: row.Name}, nil +} + +// ListOrgs returns every organisation, oldest first. +func (m *Module) ListOrgs(ctx context.Context) ([]Org, error) { + rows, err := m.store.ListOrgs(ctx) + if err != nil { + return nil, err + } + out := make([]Org, 0, len(rows)) + for _, r := range rows { + out = append(out, Org{ID: OrgID(r.ID), Name: r.Name}) + } + return out, nil +} + +// CreateWorkspace adds a workspace to an existing organisation. +func (m *Module) CreateWorkspace(ctx context.Context, value Workspace) (Workspace, error) { + if err := value.Validate(); err != nil { + return Workspace{}, err + } + err := m.store.CreateWorkspace(ctx, store.WorkspaceRow{ + ID: string(value.ID), + OrgID: string(value.OrgID), + Name: value.Name, + Environment: value.Environment, + }) + switch { + case errors.Is(err, store.ErrNotFound): + return Workspace{}, ErrOrgNotFound + case errors.Is(err, store.ErrAlreadyExists): + return Workspace{}, fmt.Errorf("%w: %s/%s", ErrWorkspaceExists, value.OrgID, value.ID) + case err != nil: + return Workspace{}, err + } + return value, nil +} + +// ListWorkspaces returns an organisation's workspaces, oldest first. +func (m *Module) ListWorkspaces(ctx context.Context, id OrgID) ([]Workspace, error) { + rows, err := m.store.ListWorkspaces(ctx, string(id)) + if err != nil { + return nil, err + } + out := make([]Workspace, 0, len(rows)) + for _, r := range rows { + out = append(out, Workspace{ + ID: WorkspaceID(r.ID), + OrgID: OrgID(r.OrgID), + Name: r.Name, + Environment: r.Environment, + }) + } + return out, nil +} + +// EnsureMembership grants or updates a membership role in an organisation or workspace. +func (m *Module) EnsureMembership(ctx context.Context, value Membership) error { + if err := value.Validate(); err != nil { + return err + } + var ws sql.NullString + if value.WorkspaceID != "" { + ws = sql.NullString{String: string(value.WorkspaceID), Valid: true} + } + err := m.store.EnsureMembership(ctx, store.MembershipRow{ + IdentityID: string(value.IdentityID), + OrgID: string(value.OrgID), + WorkspaceID: ws, + Role: string(value.Role), + }) + switch { + case errors.Is(err, store.ErrNotFound): + return ErrOrgNotFound + case errors.Is(err, store.ErrLastOwner): + return ErrLastOwner + default: + return err + } +} + +// ListMembers returns an organisation's memberships with identity metadata. +func (m *Module) ListMembers(ctx context.Context, id OrgID) ([]Member, error) { + rows, err := m.store.ListMembers(ctx, string(id)) + if err != nil { + return nil, err + } + out := make([]Member, 0, len(rows)) + for _, r := range rows { + var ws WorkspaceID + if r.WorkspaceID.Valid { + ws = WorkspaceID(r.WorkspaceID.String) + } + out = append(out, Member{ + IdentityID: IdentityID(r.IdentityID), + Kind: Kind(r.Kind), + DisplayName: r.DisplayName, + WorkspaceID: ws, + Role: Role(r.Role), + }) + } + return out, nil +} + +// RemoveMembership revokes a membership while keeping at least one active owner. +func (m *Module) RemoveMembership(ctx context.Context, value Membership) error { + if value.IdentityID == "" || value.OrgID == "" { + return fmt.Errorf("%w: identity and org are required", ErrInvalidMembership) + } + err := m.store.RemoveMembership(ctx, string(value.IdentityID), string(value.OrgID), string(value.WorkspaceID)) + if errors.Is(err, store.ErrLastOwner) { + return ErrLastOwner + } + return err +} + +// ListOrgAgents returns every agent assignment in org id. +func (m *Module) ListOrgAgents(ctx context.Context, id OrgID) ([]AgentAssignment, error) { + rows, err := m.store.ListOrgAgents(ctx, string(id)) + if err != nil { + return nil, err + } + out := make([]AgentAssignment, 0, len(rows)) + for _, r := range rows { + out = append(out, AgentAssignment{IdentityID: IdentityID(r.IdentityID), OrgID: OrgID(r.OrgID)}) + } + return out, nil +} + +// AssignAgent assigns an agent identity to an organisation. +func (m *Module) AssignAgent(ctx context.Context, value AgentAssignment) error { + if err := value.Validate(); err != nil { + return err + } + err := m.store.AssignAgent(ctx, string(value.IdentityID), string(value.OrgID)) + if errors.Is(err, store.ErrNotFound) { + return ErrOrgNotFound + } + return err +} + +// OrgForIdentity resolves the organisation an identity serves. +func (m *Module) OrgForIdentity(ctx context.Context, id IdentityID) (OrgID, error) { + resolved, err := m.store.ResolveIdentityOrg(ctx, string(id), string(DefaultOrgID)) + if err != nil { + return "", err + } + return OrgID(resolved), nil +} + +// PrincipalFor assembles the Cedar Principal for id. +func (m *Module) PrincipalFor(ctx context.Context, id IdentityID) (Principal, error) { + resolved, err := m.OrgForIdentity(ctx, id) + if err != nil { + return Principal{}, err + } + rows, err := m.store.ListMembershipsByIdentity(ctx, string(id)) + if err != nil { + return Principal{}, err + } + memberships := make([]Membership, 0, len(rows)) + for _, r := range rows { + var ws WorkspaceID + if r.WorkspaceID.Valid { + ws = WorkspaceID(r.WorkspaceID.String) + } + memberships = append(memberships, Membership{ + IdentityID: id, + OrgID: OrgID(r.OrgID), + WorkspaceID: ws, + Role: Role(r.Role), + }) + } + workspaces, err := m.ListWorkspaces(ctx, resolved) + if err != nil { + return Principal{}, err + } + if id == SystemID { + memberships = SharedTokenOwner().Memberships + } + return Principal{ + IdentityID: id, + Org: resolved, + Memberships: memberships, + Workspaces: workspaces, + }, nil +}