From 7bf4fb6079e4e5c8d2779a7acbfcabe570ad3aba Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 25 Oct 2026 19:53:16 +0100 Subject: [PATCH] feat(supabase): workspaces M1, one personal workspace per account MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit V1-1.1 (contract V1-1_OWNERS_ANIMALS.md §4, §8, §9). Tables workspaces and workspace_members, created with the profile by trigger through one atomic, idempotent write path; deferred invariant (a personal workspace has exactly its account as holder); backfill of existing profiles; access helpers caller_workspace_ids (active profile, confirmed email) and writable_workspace_ids; RLS select for members only; no privilege for anon or service_role. log_event keeps x-correlation-id only as a short token. pgTAP 012 (85 checks), census and types updated, config test. --- packages/supabase/src/database.types.ts | 71 +++ packages/supabase/tests/db/config.test.ts | 38 ++ .../supabase/tests/db/schema-types.test.ts | 2 + .../migrations/20261025100000_workspaces.sql | 353 ++++++++++++++ supabase/tests/001_schema.sql | 2 +- supabase/tests/012_workspaces.sql | 458 ++++++++++++++++++ 6 files changed, 923 insertions(+), 1 deletion(-) create mode 100644 packages/supabase/tests/db/config.test.ts create mode 100644 supabase/migrations/20261025100000_workspaces.sql create mode 100644 supabase/tests/012_workspaces.sql diff --git a/packages/supabase/src/database.types.ts b/packages/supabase/src/database.types.ts index ad4cdb51..37fab90b 100644 --- a/packages/supabase/src/database.types.ts +++ b/packages/supabase/src/database.types.ts @@ -444,6 +444,73 @@ export type Database = { } Relationships: [] } + workspace_members: { + Row: { + created_at: string + member_role: Database['public']['Enums']['workspace_member_role'] + user_id: string + workspace_id: string + } + ComputedFields: never + Insert: { + created_at?: string + member_role: Database['public']['Enums']['workspace_member_role'] + user_id: string + workspace_id: string + } + Update: { + created_at?: string + member_role?: Database['public']['Enums']['workspace_member_role'] + user_id?: string + workspace_id?: string + } + Relationships: [ + { + foreignKeyName: 'workspace_members_user_id_fkey' + columns: ['user_id'] + isOneToOne: false + referencedRelation: 'profiles' + referencedColumns: ['id'] + }, + { + foreignKeyName: 'workspace_members_workspace_id_fkey' + columns: ['workspace_id'] + isOneToOne: false + referencedRelation: 'workspaces' + referencedColumns: ['id'] + }, + ] + } + workspaces: { + Row: { + created_at: string + id: string + kind: Database['public']['Enums']['workspace_kind'] + personal_user_id: string | null + } + ComputedFields: never + Insert: { + created_at?: string + id?: string + kind: Database['public']['Enums']['workspace_kind'] + personal_user_id?: string | null + } + Update: { + created_at?: string + id?: string + kind?: Database['public']['Enums']['workspace_kind'] + personal_user_id?: string | null + } + Relationships: [ + { + foreignKeyName: 'workspaces_personal_user_id_fkey' + columns: ['personal_user_id'] + isOneToOne: true + referencedRelation: 'profiles' + referencedColumns: ['id'] + }, + ] + } } Views: { [_ in never]: never @@ -588,6 +655,8 @@ export type Database = { sheet_status: 'active' | 'archived' | 'deleted' sheet_version_status: 'draft' | 'published' | 'deprecated' sheet_visibility: 'private' | 'public' + workspace_kind: 'personal' + workspace_member_role: 'holder' } CompositeTypes: { [_ in never]: never @@ -726,6 +795,8 @@ export const Constants = { sheet_status: ['active', 'archived', 'deleted'], sheet_version_status: ['draft', 'published', 'deprecated'], sheet_visibility: ['private', 'public'], + workspace_kind: ['personal'], + workspace_member_role: ['holder'], }, }, } as const diff --git a/packages/supabase/tests/db/config.test.ts b/packages/supabase/tests/db/config.test.ts new file mode 100644 index 00000000..4ed86b19 --- /dev/null +++ b/packages/supabase/tests/db/config.test.ts @@ -0,0 +1,38 @@ +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { supabaseDir } from './harness' + +/** + * Settings the workspace access rule depends on (V1-1 contract §6.2, §9.1). + * private.caller_workspace_ids() requires auth.users.email_confirmed_at, but + * with confirmations off GoTrue stamps that column at sign-up; the helpers + * live in `private`, which must stay out of the PostgREST schemas. + */ +async function readSetting( + section: string, + key: string, +): Promise { + const config = await readFile(join(supabaseDir, 'config.toml'), 'utf8') + let current = '' + for (const line of config.split('\n')) { + const header = line.match(/^\[([^\]]+)\]\s*$/) + if (header) current = header[1] + const setting = line.match(/^(\w+)\s*=\s*(.+?)\s*$/) + if (current === section && setting?.[1] === key) return setting[2] + } + return undefined +} + +describe('config.toml settings the access rules rely on', () => { + it('requires email confirmation before any session', async () => { + expect(await readSetting('auth.email', 'enable_confirmations')).toBe('true') + }) + + it('keeps anonymous sign-ins off (no account without an email)', async () => { + expect(await readSetting('auth', 'enable_anonymous_sign_ins')).toBe('false') + }) + + it('exposes only the public schema through PostgREST', async () => { + expect(await readSetting('api', 'schemas')).toBe('["public"]') + }) +}) diff --git a/packages/supabase/tests/db/schema-types.test.ts b/packages/supabase/tests/db/schema-types.test.ts index 84da6653..36aa8f45 100644 --- a/packages/supabase/tests/db/schema-types.test.ts +++ b/packages/supabase/tests/db/schema-types.test.ts @@ -112,6 +112,8 @@ const expectedColumns = { 'updated_at', ], species: ['active', 'created_at', 'id', 'name_en', 'name_fr', 'sort_order'], + workspace_members: ['created_at', 'member_role', 'user_id', 'workspace_id'], + workspaces: ['created_at', 'id', 'kind', 'personal_user_id'], } as const satisfies ColumnMap // Compile-time: a column present in the type but absent from the list is an error. diff --git a/supabase/migrations/20261025100000_workspaces.sql b/supabase/migrations/20261025100000_workspaces.sql new file mode 100644 index 00000000..fad6a2cd --- /dev/null +++ b/supabase/migrations/20261025100000_workspaces.sql @@ -0,0 +1,353 @@ +-- V1-1.1 Workspaces (M1): the perimeter that will own and isolate clients, +-- animals and later bilans. Contract: docs/development/V1-1_OWNERS_ANIMALS.md +-- §4 (model), §8 (schema), §9 (helpers, RLS), §13.2 N7 / N9 (privileges, audit). +-- +-- In V1-1 every account has exactly one personal workspace, created by the +-- server in the transaction that creates its profile (sign-up), never by a +-- client call. Its only member is the account itself, with member_role +-- holder. Nothing is shared between accounts; cabinets come with plan Step 10. +-- +-- Invariants pinned by supabase/tests/012_workspaces.sql: +-- * one personal workspace per profile (unique personal_user_id), created +-- with its holder membership in one statement, idempotent under retries +-- and concurrent calls (ON CONFLICT on the unique key); +-- * a personal workspace has exactly one member, its account as holder, +-- checked at commit, so neither row ever survives alone; +-- * a workspace is readable only by its members whose profile is active and +-- whose email is confirmed; auth.uid() is the only input of that rule; +-- * no API role writes either table; anon and service_role hold no +-- privilege on them; no policy names a platform role (D16); +-- * the audit correlation id is kept only when it is a short token, so a +-- caller no longer chooses the size of an append-only audit row. + +-- --------------------------------------------------------------------------- +-- Tables +-- --------------------------------------------------------------------------- +-- cabinet joins workspace_kind with the cabinet step; holder is the only +-- member role until then (no unused cabinet role). +create type public.workspace_kind as enum ('personal'); +create type public.workspace_member_role as enum ('holder'); + +create table public.workspaces ( + id uuid primary key default gen_random_uuid(), + kind public.workspace_kind not null, + -- The account whose personal workspace this is; null for a future cabinet. + -- Deleting the account deletes its personal workspace, unless a record + -- table refuses it (D9a, `on delete restrict` from M2 on). + personal_user_id uuid references public.profiles (id) on delete cascade, + created_at timestamptz not null default now(), + constraint workspaces_personal_user_unique unique (personal_user_id), + constraint workspaces_personal_user_iff_personal + check ((kind = 'personal') = (personal_user_id is not null)) +); + +comment on table public.workspaces is + 'Perimeter that owns and isolates records. V1-1: one personal workspace per account, created with its profile; no API write path; no archive (it follows its account).'; +comment on column public.workspaces.personal_user_id is + 'Account of a personal workspace (unique); null for a cabinet.'; + +create table public.workspace_members ( + workspace_id uuid not null references public.workspaces (id) on delete cascade, + user_id uuid not null references public.profiles (id) on delete cascade, + member_role public.workspace_member_role not null, + created_at timestamptz not null default now(), + primary key (workspace_id, user_id) +); + +comment on table public.workspace_members is + 'Membership and rights of an account in a workspace. V1-1: the holder of each personal workspace only; no API write path.'; + +-- The membership lookup of every workspace policy (by caller). +create index workspace_members_user_idx on public.workspace_members (user_id); + +-- --------------------------------------------------------------------------- +-- Invariant: a personal workspace has exactly one member, its account as +-- holder. Deferred to commit so the two rows may be written in either order +-- inside one transaction; a workspace or a membership left alone, or a +-- foreign member added to a personal workspace, fails the commit whatever +-- role writes it. Cabinets are not constrained here. +-- --------------------------------------------------------------------------- +create or replace function private.check_personal_workspace() +returns trigger +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_ids uuid[]; +begin + if tg_table_name = 'workspaces' then + v_ids := array[new.id]; + elsif tg_op = 'INSERT' then + v_ids := array[new.workspace_id]; + elsif tg_op = 'DELETE' then + v_ids := array[old.workspace_id]; + else + v_ids := array[old.workspace_id, new.workspace_id]; + end if; + + -- A deleted workspace has nothing left to check (account deletion cascades). + if exists ( + select 1 + from public.workspaces w + where w.id = any (v_ids) + and w.kind = 'personal' + and ( + not exists ( + select 1 from public.workspace_members m + where m.workspace_id = w.id + and m.user_id = w.personal_user_id + and m.member_role = 'holder' + ) + or exists ( + select 1 from public.workspace_members m + where m.workspace_id = w.id + and m.user_id <> w.personal_user_id + ) + ) + ) then + raise exception 'personal workspace must have exactly its account as holder' + using errcode = '23514', constraint = 'workspaces_personal_holder'; + end if; + return null; +end; +$$; + +comment on function private.check_personal_workspace() is + 'Deferred constraint trigger: a personal workspace has exactly one member, personal_user_id as holder.'; + +create constraint trigger workspaces_personal_holder + after insert or update on public.workspaces + deferrable initially deferred + for each row execute function private.check_personal_workspace(); + +create constraint trigger workspace_members_personal_holder + after insert or update or delete on public.workspace_members + deferrable initially deferred + for each row execute function private.check_personal_workspace(); + +-- --------------------------------------------------------------------------- +-- Creation of the personal workspace +-- --------------------------------------------------------------------------- +-- The single write path: workspace and holder membership in one statement, +-- so both rows exist or neither does. A replay, or a call racing another +-- one, waits on the unique personal_user_id, then writes nothing and +-- returns false. The id comes from the server (a new profile, the backfill), +-- never from an API role: EXECUTE is granted to nobody. +create or replace function private.ensure_personal_workspace(p_user_id uuid) +returns boolean +language sql +volatile +security definer +set search_path = '' +as $$ + with created as ( + insert into public.workspaces (kind, personal_user_id) + values ('personal', p_user_id) + on conflict (personal_user_id) do nothing + returning id, personal_user_id + ), + joined as ( + insert into public.workspace_members (workspace_id, user_id, member_role) + select id, personal_user_id, 'holder' from created + returning workspace_id + ) + select exists (select 1 from joined); +$$; + +comment on function private.ensure_personal_workspace(uuid) is + 'Creates the personal workspace of an existing profile with its holder membership, atomically; idempotent (false when it already exists).'; + +-- Sign-up: GoTrue inserts auth.users, private.handle_new_auth_user inserts the +-- profile, this trigger creates the workspace, all in one transaction. The +-- workspace exists before the email is confirmed but stays unreadable until +-- then (private.caller_workspace_ids). +create or replace function private.create_personal_workspace() +returns trigger +language plpgsql +security definer +set search_path = '' +as $$ +begin + perform private.ensure_personal_workspace(new.id); + return null; +end; +$$; + +comment on function private.create_personal_workspace() is + 'AFTER INSERT on profiles: creates the personal workspace and its holder membership.'; + +create trigger profiles_create_personal_workspace + after insert on public.profiles + for each row execute function private.create_personal_workspace(); + +-- Accounts created before this migration. Called once below; idempotent, so +-- a second call (or a call racing a sign-up) creates nothing twice. +create or replace function private.backfill_personal_workspaces() +returns integer +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_profile_id uuid; + v_created integer := 0; +begin + for v_profile_id in + select p.id + from public.profiles p + where not exists ( + select 1 from public.workspaces w where w.personal_user_id = p.id + ) + order by p.id + loop + if private.ensure_personal_workspace(v_profile_id) then + v_created := v_created + 1; + end if; + end loop; + return v_created; +end; +$$; + +comment on function private.backfill_personal_workspaces() is + 'Creates the missing personal workspaces of existing profiles; returns how many were created. Idempotent.'; + +-- --------------------------------------------------------------------------- +-- Access helpers (contract §9.1) +-- --------------------------------------------------------------------------- +-- The single source of the access rule of every workspace-scoped table: the +-- workspaces where the caller is a member, with an active profile and a +-- confirmed email. No parameter: auth.uid() (a JWT verified by PostgREST) is +-- the only input, so a caller can name nobody else, and a direct call returns +-- what the caller may already read. Definer, so it reads auth.users and +-- workspace_members past their privileges and policies (no RLS recursion). +create or replace function private.caller_workspace_ids() +returns setof uuid +language sql +stable +security definer +set search_path = '' +as $$ + select m.workspace_id + from public.workspace_members m + join public.profiles p on p.id = m.user_id + join auth.users u on u.id = m.user_id + where m.user_id = (select auth.uid()) + and p.active + and u.email_confirmed_at is not null; +$$; + +comment on function private.caller_workspace_ids() is + 'Workspaces of auth.uid() as a member, active profile and confirmed email required. Evaluated by the workspace policies.'; + +-- The same set restricted to the member roles that may write records (V1-1: +-- holder). Called inside the write RPCs of M2 and M3 only. +create or replace function private.writable_workspace_ids() +returns setof uuid +language sql +stable +security definer +set search_path = '' +as $$ + select m.workspace_id + from public.workspace_members m + where m.user_id = (select auth.uid()) + and m.member_role = 'holder' + and m.workspace_id in (select private.caller_workspace_ids()); +$$; + +comment on function private.writable_workspace_ids() is + 'caller_workspace_ids() restricted to a write role (holder). For definer RPCs only.'; + +-- --------------------------------------------------------------------------- +-- Audit: cap the caller-controlled correlation id (contract §8, §10, N9) +-- --------------------------------------------------------------------------- +-- PostgREST exposes every request header, so x-correlation-id is chosen by +-- the caller. Kept only when it is a short token, else stored as null. Same +-- signature, privileges and callers as the foundation version. +create or replace function private.log_event( + p_actor_user_id uuid, + p_action text, + p_resource_type text, + p_resource_id uuid default null, + p_target_user_id uuid default null, + p_organization_id uuid default null, + p_metadata jsonb default '{}'::jsonb +) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_id uuid; + v_correlation text; +begin + -- PostgREST exposes request headers as a JSON setting; absent elsewhere. + v_correlation := nullif(current_setting('request.headers', true), '')::jsonb ->> 'x-correlation-id'; + if v_correlation !~ '^[A-Za-z0-9-]{1,64}$' then + v_correlation := null; + end if; + + insert into audit.audit_logs ( + actor_user_id, action, resource_type, resource_id, + target_user_id, organization_id, metadata, correlation_id + ) + values ( + p_actor_user_id, p_action, p_resource_type, p_resource_id, + p_target_user_id, p_organization_id, coalesce(p_metadata, '{}'::jsonb), v_correlation + ) + returning id into v_id; + + return v_id; +end; +$$; + +-- New rows only: rows written before this migration keep whatever they hold. +alter table audit.audit_logs + add constraint audit_logs_correlation_id_format + check (correlation_id ~ '^[A-Za-z0-9-]{1,64}$') not valid; + +-- --------------------------------------------------------------------------- +-- Privileges + RLS. Supabase default privileges grant ALL on new public +-- tables to anon, authenticated and service_role: start from zero. The +-- service key reads nothing here (N7); it remains a GoTrue admin credential +-- (contract §6.3), which no table privilege can bound. +-- --------------------------------------------------------------------------- +revoke all on public.workspaces from public, anon, authenticated, service_role; +revoke all on public.workspace_members from public, anon, authenticated, service_role; +grant select (id, kind, personal_user_id, created_at) on public.workspaces to authenticated; +grant select (workspace_id, user_id, member_role, created_at) on public.workspace_members to authenticated; + +alter table public.workspaces enable row level security; +alter table public.workspace_members enable row level security; + +-- Members read their workspaces and the memberships of those workspaces. +-- No write policy: every write is server-side (trigger, backfill, RPCs). +create policy workspaces_select_member + on public.workspaces + for select + to authenticated + using (id in (select private.caller_workspace_ids())); + +create policy workspace_members_select_member + on public.workspace_members + for select + to authenticated + using (workspace_id in (select private.caller_workspace_ids())); + +revoke all on function private.check_personal_workspace() from public, anon, authenticated, service_role; +revoke all on function private.ensure_personal_workspace(uuid) from public, anon, authenticated, service_role; +revoke all on function private.create_personal_workspace() from public, anon, authenticated, service_role; +revoke all on function private.backfill_personal_workspaces() from public, anon, authenticated, service_role; +revoke all on function private.writable_workspace_ids() from public, anon, authenticated, service_role; +revoke all on function private.caller_workspace_ids() from public, anon, authenticated, service_role; +-- Policies run as the API role: it needs EXECUTE on the predicate. +grant execute on function private.caller_workspace_ids() to authenticated; + +-- --------------------------------------------------------------------------- +-- Existing accounts. Runs after the trigger exists, so a profile created +-- while the migration runs is covered by one or the other; a double pass +-- creates nothing twice (ensure_personal_workspace). +-- --------------------------------------------------------------------------- +select private.backfill_personal_workspaces(); diff --git a/supabase/tests/001_schema.sql b/supabase/tests/001_schema.sql index 0f99835a..ce66814d 100644 --- a/supabase/tests/001_schema.sql +++ b/supabase/tests/001_schema.sql @@ -62,7 +62,7 @@ select is( (select string_agg(p.proname::text, ',' order by p.proname::text collate "C") from pg_proc p join pg_namespace n on n.oid = p.pronamespace where n.nspname in ('private', 'audit') and has_function_privilege('authenticated', p.oid, 'execute')), - 'can_edit_sheet,can_read_avatar_object,can_read_sheet_asset_object,can_upload_avatar_object,can_use_sheet,has_platform_role,is_platform_admin,is_platform_moderator,is_platform_owner,is_support', + 'caller_workspace_ids,can_edit_sheet,can_read_avatar_object,can_read_sheet_asset_object,can_upload_avatar_object,can_use_sheet,has_platform_role,is_platform_admin,is_platform_moderator,is_platform_owner,is_support', 'authenticated executes only the policy predicates in private' ); diff --git a/supabase/tests/012_workspaces.sql b/supabase/tests/012_workspaces.sql new file mode 100644 index 00000000..a9de24b1 --- /dev/null +++ b/supabase/tests/012_workspaces.sql @@ -0,0 +1,458 @@ +-- V1-1.1 Workspaces (M1): creation with the account, uniqueness, the commit +-- invariant, the backfill, isolation between accounts, refusals for every +-- other actor, privileges and the definer census, the audit correlation cap. +-- Contract: docs/development/V1-1_OWNERS_ANIMALS.md §4, §8, §9, §12.1. +-- Actors: A and B confirmed and active; C unconfirmed; D deactivated; S a +-- platform owner; E an empty account deleted; F and G profiles created with +-- the trigger disabled (backfill, invariant). +begin; +select plan(85); + +insert into auth.users (id, email, email_confirmed_at) values + ('50000000-0000-0000-0000-00000000000a', 'alice-ws@test.local', now()), + ('50000000-0000-0000-0000-00000000000b', 'bob-ws@test.local', now()), + ('50000000-0000-0000-0000-00000000000c', 'carol-ws@test.local', null), + ('50000000-0000-0000-0000-00000000000d', 'dave-ws@test.local', now()), + ('50000000-0000-0000-0000-000000000005', 'staff-ws@test.local', now()), + ('50000000-0000-0000-0000-00000000000e', 'empty-ws@test.local', now()); +update public.profiles set active = false where id = '50000000-0000-0000-0000-00000000000d'; +select private.assign_platform_role(null, '50000000-0000-0000-0000-000000000005', 'owner'); + +-- Fixture readers usable from every role (pg_temp objects belong to postgres). +create function pg_temp.ws(p_user uuid) returns uuid language sql stable security definer +as $$ select id from public.workspaces where personal_user_id = p_user $$; +create function pg_temp.act_as(p_user uuid) returns text language sql +as $$ select set_config('request.jwt.claims', + json_build_object('sub', p_user, 'role', 'authenticated')::text, true) $$; +create function pg_temp.writable() returns setof uuid language sql stable security definer +as $$ select private.writable_workspace_ids() $$; +create table pg_temp.audit_ids (key text primary key, id uuid not null); +grant execute on function pg_temp.ws(uuid) to anon, authenticated, service_role; +grant execute on function pg_temp.act_as(uuid) to anon, authenticated, service_role; +grant execute on function pg_temp.writable() to anon, authenticated, service_role; + +-- --------------------------------------------------------------------------- +-- 1. Schema +-- --------------------------------------------------------------------------- +select has_table('public', 'workspaces', 'table public.workspaces exists'); +select has_table('public', 'workspace_members', 'table public.workspace_members exists'); +select enum_has_labels('public', 'workspace_kind', array['personal'], 'workspace_kind: personal only (cabinet comes with its step)'); +select enum_has_labels('public', 'workspace_member_role', array['holder'], 'workspace_member_role: holder only (no unused cabinet role)'); +select ok((select relrowsecurity from pg_class where oid = 'public.workspaces'::regclass), 'RLS enabled on workspaces'); +select ok((select relrowsecurity from pg_class where oid = 'public.workspace_members'::regclass), 'RLS enabled on workspace_members'); +select is( + (select string_agg(tablename || ':' || tableowner, ',' order by tablename collate "C") + from pg_tables where schemaname = 'public' and tablename in ('workspaces', 'workspace_members')), + 'workspace_members:postgres,workspaces:postgres', 'both tables belong to postgres (the migration role)' +); + +-- --------------------------------------------------------------------------- +-- 2. Creation with the account (sign-up chain auth.users -> profiles -> workspace) +-- --------------------------------------------------------------------------- +select is( + (select count(*) from public.workspaces where personal_user_id::text like '50000000-%'), + 6::bigint, 'every new account got a workspace, confirmed or not' +); +select results_eq( + $$ select kind::text, personal_user_id from public.workspaces + where personal_user_id = '50000000-0000-0000-0000-00000000000a' $$, + $$ values ('personal'::text, '50000000-0000-0000-0000-00000000000a'::uuid) $$, + 'A has one personal workspace of its own' +); +select results_eq( + $$ select user_id, member_role::text from public.workspace_members + where workspace_id = pg_temp.ws('50000000-0000-0000-0000-00000000000a') $$, + $$ values ('50000000-0000-0000-0000-00000000000a'::uuid, 'holder'::text) $$, + 'the workspace of A has exactly A as holder' +); +select is( + (select count(*) from public.workspace_members m join public.workspaces w on w.id = m.workspace_id + where w.personal_user_id::text like '50000000-%' and m.user_id = w.personal_user_id and m.member_role = 'holder'), + 6::bigint, 'every fixture workspace has its account as holder' +); +select isnt( + pg_temp.ws('50000000-0000-0000-0000-00000000000a'), pg_temp.ws('50000000-0000-0000-0000-00000000000b'), + 'A and B have two distinct workspaces' +); + +-- A sign-up that fails after the chain ran leaves no account, profile or workspace. +select throws_ok( + $$ do $b$ begin + insert into auth.users (id, email, email_confirmed_at) + values ('50000000-0000-0000-0000-000000000099', 'boom-ws@test.local', now()); + raise exception 'boom' using errcode = 'P0001'; + end $b$ $$, + 'P0001', 'boom', 'a sign-up transaction that fails after the trigger raises' +); +select is( + (select count(*) from public.workspaces where personal_user_id = '50000000-0000-0000-0000-000000000099'), + 0::bigint, 'no workspace survives the failed sign-up' +); +select is( + (select count(*) from public.profiles where id = '50000000-0000-0000-0000-000000000099'), + 0::bigint, 'no profile survives the failed sign-up' +); + +-- --------------------------------------------------------------------------- +-- 3. Uniqueness and idempotence +-- --------------------------------------------------------------------------- +select is(private.ensure_personal_workspace('50000000-0000-0000-0000-00000000000a'), false, + 'a replayed creation for A writes nothing and says so'); +select is( + (select count(*) from public.workspaces where personal_user_id = '50000000-0000-0000-0000-00000000000a'), + 1::bigint, 'A still has one workspace after the replay' +); +select is( + (select count(*) from public.workspace_members where user_id = '50000000-0000-0000-0000-00000000000a'), + 1::bigint, 'A still has one membership after the replay' +); +select throws_ok( + $$ insert into public.workspaces (kind, personal_user_id) values ('personal', '50000000-0000-0000-0000-00000000000a') $$, + '23505', null, 'a second personal workspace for A is refused by the unique key' +); +select throws_ok( + $$ insert into public.workspaces (kind, personal_user_id) values ('personal', null) $$, + '23514', null, 'a personal workspace without an account is refused' +); +select throws_ok( + $$ insert into public.workspaces (kind, personal_user_id) values ('personal', '50000000-0000-0000-0000-0000000000ff') $$, + '23503', null, 'a personal workspace for an unknown account is refused' +); +select throws_ok( + $$ insert into public.workspace_members (workspace_id, user_id, member_role) + values (gen_random_uuid(), '50000000-0000-0000-0000-00000000000a', 'holder') $$, + '23503', null, 'a membership of an unknown workspace is refused' +); +select throws_ok( + $$ insert into public.workspace_members (workspace_id, user_id, member_role) + values (pg_temp.ws('50000000-0000-0000-0000-00000000000a'), '50000000-0000-0000-0000-00000000000a', 'holder') $$, + '23505', null, 'a duplicate membership is refused by the primary key' +); + +-- --------------------------------------------------------------------------- +-- 4. Backfill of accounts created without the trigger (migration path) +-- --------------------------------------------------------------------------- +alter table public.profiles disable trigger profiles_create_personal_workspace; +insert into auth.users (id, email, email_confirmed_at) values + ('50000000-0000-0000-0000-00000000000f', 'backfill-ws@test.local', now()), + ('50000000-0000-0000-0000-000000000010', 'invariant-ws@test.local', now()); +alter table public.profiles enable trigger profiles_create_personal_workspace; +select is(pg_temp.ws('50000000-0000-0000-0000-00000000000f'), null, 'F has no workspace before the backfill'); +select is(private.backfill_personal_workspaces(), 2, 'the backfill creates the two missing workspaces'); +select is(private.backfill_personal_workspaces(), 0, 'a second backfill creates nothing'); +select results_eq( + $$ select m.user_id, m.member_role::text from public.workspace_members m + where m.workspace_id = pg_temp.ws('50000000-0000-0000-0000-00000000000f') $$, + $$ values ('50000000-0000-0000-0000-00000000000f'::uuid, 'holder'::text) $$, + 'the backfilled workspace of F has F as holder' +); + +-- --------------------------------------------------------------------------- +-- 5. Commit invariant (checked here statement by statement) +-- --------------------------------------------------------------------------- +set constraints workspaces_personal_holder, workspace_members_personal_holder immediate; +delete from public.workspaces where personal_user_id = '50000000-0000-0000-0000-000000000010'; +select is(pg_temp.ws('50000000-0000-0000-0000-000000000010'), null, 'deleting a personal workspace takes its membership along'); +select throws_ok( + $$ insert into public.workspaces (kind, personal_user_id) values ('personal', '50000000-0000-0000-0000-000000000010') $$, + '23514', 'personal workspace must have exactly its account as holder', + 'a personal workspace without its holder cannot be committed' +); +select throws_ok( + $$ insert into public.workspace_members (workspace_id, user_id, member_role) + values (pg_temp.ws('50000000-0000-0000-0000-00000000000a'), '50000000-0000-0000-0000-00000000000b', 'holder') $$, + '23514', 'personal workspace must have exactly its account as holder', + 'B cannot be added to the personal workspace of A, even by the table owner' +); +select throws_ok( + $$ delete from public.workspace_members where user_id = '50000000-0000-0000-0000-00000000000a' $$, + '23514', 'personal workspace must have exactly its account as holder', + 'the holder of a personal workspace cannot be removed alone' +); +select throws_ok( + $$ update public.workspaces set personal_user_id = '50000000-0000-0000-0000-000000000010' + where personal_user_id = '50000000-0000-0000-0000-00000000000a' $$, + '23514', 'personal workspace must have exactly its account as holder', + 'a personal workspace cannot be handed to another account' +); +select is(private.ensure_personal_workspace('50000000-0000-0000-0000-000000000010'), true, + 'the single write path passes the invariant (both rows in one statement)'); +set constraints all deferred; + +-- --------------------------------------------------------------------------- +-- 6. Reading: each confirmed active account reads its own workspace only +-- --------------------------------------------------------------------------- +set local role authenticated; +select pg_temp.act_as('50000000-0000-0000-0000-00000000000a'); +select results_eq( + $$ select id, kind::text, personal_user_id from public.workspaces $$, + $$ values (pg_temp.ws('50000000-0000-0000-0000-00000000000a'), 'personal'::text, + '50000000-0000-0000-0000-00000000000a'::uuid) $$, + 'A reads exactly its workspace' +); +select results_eq( + $$ select workspace_id, user_id, member_role::text from public.workspace_members $$, + $$ values (pg_temp.ws('50000000-0000-0000-0000-00000000000a'), '50000000-0000-0000-0000-00000000000a'::uuid, 'holder'::text) $$, + 'A reads exactly its membership (no RLS recursion)' +); +select is( + (select count(*) from public.workspaces where id = pg_temp.ws('50000000-0000-0000-0000-00000000000b')), + 0::bigint, 'A reads nothing of the workspace of B by id' +); +select is( + (select count(*) from public.workspaces where personal_user_id = '50000000-0000-0000-0000-00000000000b'), + 0::bigint, 'A naming B as personal_user_id reads nothing' +); +select is( + (select count(*) from public.workspace_members where user_id = '50000000-0000-0000-0000-00000000000b' + or workspace_id = pg_temp.ws('50000000-0000-0000-0000-00000000000b')), + 0::bigint, 'A reads no membership of B' +); +select results_eq( + $$ select private.caller_workspace_ids() $$, + $$ values (pg_temp.ws('50000000-0000-0000-0000-00000000000a')) $$, + 'a direct call of the helper returns only what A may already read' +); +select results_eq( + $$ select pg_temp.writable() $$, + $$ values (pg_temp.ws('50000000-0000-0000-0000-00000000000a')) $$, + 'A may write in its workspace (holder)' +); + +select pg_temp.act_as('50000000-0000-0000-0000-00000000000b'); +select results_eq( + $$ select id from public.workspaces $$, + $$ values (pg_temp.ws('50000000-0000-0000-0000-00000000000b')) $$, + 'B reads exactly its workspace' +); +select is( + (select count(*) from public.workspaces where id = pg_temp.ws('50000000-0000-0000-0000-00000000000a')), + 0::bigint, 'B reads nothing of the workspace of A' +); + +-- --------------------------------------------------------------------------- +-- 7. Refused readers: unconfirmed, deactivated, platform staff +-- --------------------------------------------------------------------------- +select pg_temp.act_as('50000000-0000-0000-0000-00000000000c'); +select is((select count(*) from public.workspaces), 0::bigint, 'C (email unconfirmed) reads no workspace, not even its own'); +select is((select count(*) from public.workspace_members), 0::bigint, 'C reads no membership'); +select is((select count(*) from private.caller_workspace_ids()), 0::bigint, 'C has no workspace for the helper'); +select is((select count(*) from pg_temp.writable()), 0::bigint, 'C may write nowhere'); + +select pg_temp.act_as('50000000-0000-0000-0000-00000000000d'); +select is((select count(*) from public.workspaces), 0::bigint, 'D (deactivated) reads no workspace, not even its own'); +select is((select count(*) from public.workspace_members), 0::bigint, 'D reads no membership'); +select is((select count(*) from pg_temp.writable()), 0::bigint, 'D may write nowhere'); + +select pg_temp.act_as('50000000-0000-0000-0000-000000000005'); +select results_eq( + $$ select id from public.workspaces $$, + $$ values (pg_temp.ws('50000000-0000-0000-0000-000000000005')) $$, + 'S (platform owner) reads its own workspace only: no platform-role branch' +); +select is( + (select count(*) from public.workspace_members where user_id <> '50000000-0000-0000-0000-000000000005'), + 0::bigint, 'S reads no membership of another account' +); +reset role; + +-- The confirmation flow: confirming the email opens the existing workspace. +update auth.users set email_confirmed_at = now() where id = '50000000-0000-0000-0000-00000000000c'; +set local role authenticated; +select pg_temp.act_as('50000000-0000-0000-0000-00000000000c'); +select results_eq( + $$ select id from public.workspaces $$, + $$ values (pg_temp.ws('50000000-0000-0000-0000-00000000000c')) $$, + 'once its email is confirmed, C reads the workspace created at sign-up' +); + +-- --------------------------------------------------------------------------- +-- 8. Refused writes and calls for an authenticated caller +-- --------------------------------------------------------------------------- +select pg_temp.act_as('50000000-0000-0000-0000-00000000000a'); +select throws_ok( + $$ insert into public.workspaces (kind, personal_user_id) values ('personal', '50000000-0000-0000-0000-00000000000a') $$, + '42501', 'permission denied for table workspaces', 'A cannot create a workspace' +); +select throws_ok( + $$ insert into public.workspace_members (workspace_id, user_id, member_role) + values (pg_temp.ws('50000000-0000-0000-0000-00000000000b'), '50000000-0000-0000-0000-00000000000a', 'holder') $$, + '42501', 'permission denied for table workspace_members', 'A cannot add itself to the workspace of B' +); +select throws_ok( + $$ update public.workspaces set personal_user_id = '50000000-0000-0000-0000-00000000000b' $$, + '42501', 'permission denied for table workspaces', 'A cannot rewrite a workspace' +); +select throws_ok( + $$ update public.workspace_members set member_role = 'holder' $$, + '42501', 'permission denied for table workspace_members', 'A cannot rewrite a membership' +); +select throws_ok( + $$ delete from public.workspaces $$, + '42501', 'permission denied for table workspaces', 'A cannot delete a workspace' +); +select throws_ok( + $$ delete from public.workspace_members $$, + '42501', 'permission denied for table workspace_members', 'A cannot delete a membership' +); +select throws_ok( + $$ select private.ensure_personal_workspace('50000000-0000-0000-0000-00000000000b') $$, + '42501', null, 'A cannot call the creation path, for itself or anyone' +); +select throws_ok( + $$ select private.backfill_personal_workspaces() $$, + '42501', null, 'A cannot run the backfill' +); +select throws_ok( + $$ select private.writable_workspace_ids() $$, + '42501', null, 'A cannot call the write helper directly' +); +reset role; + +-- --------------------------------------------------------------------------- +-- 9. anon and service_role hold no privilege (refused by SQL, not by RLS) +-- --------------------------------------------------------------------------- +set local role anon; +select throws_ok($$ select id from public.workspaces $$, '42501', 'permission denied for table workspaces', 'anon cannot read workspaces'); +select throws_ok($$ select user_id from public.workspace_members $$, '42501', 'permission denied for table workspace_members', 'anon cannot read memberships'); +select throws_ok($$ select private.caller_workspace_ids() $$, '42501', null, 'anon cannot call the access helper'); +reset role; + +set local role service_role; +select throws_ok($$ select id from public.workspaces $$, '42501', 'permission denied for table workspaces', 'service_role cannot read workspaces despite BYPASSRLS'); +select throws_ok($$ select user_id from public.workspace_members $$, '42501', 'permission denied for table workspace_members', 'service_role cannot read memberships'); +select throws_ok( + $$ insert into public.workspace_members (workspace_id, user_id, member_role) + values (pg_temp.ws('50000000-0000-0000-0000-00000000000a'), '50000000-0000-0000-0000-00000000000b', 'holder') $$, + '42501', 'permission denied for table workspace_members', 'service_role cannot add a member' +); +select throws_ok($$ select private.backfill_personal_workspaces() $$, '42501', null, 'service_role cannot run the backfill'); +reset role; + +select is( + (select count(*) from (values ('public.workspaces'), ('public.workspace_members')) t(name) + cross join (values ('anon'), ('service_role')) r(role) + cross join (values ('select'), ('insert'), ('update'), ('delete'), ('truncate'), ('references'), ('trigger')) p(priv) + where has_table_privilege(r.role, t.name, p.priv)), + 0::bigint, 'anon and service_role hold no table privilege on either table' +); +select is( + (select count(*) from (values ('public.workspaces'), ('public.workspace_members')) t(name) + cross join (values ('insert'), ('update'), ('delete'), ('truncate'), ('references'), ('trigger')) p(priv) + where has_table_privilege('authenticated', t.name, p.priv)), + 0::bigint, 'authenticated holds no write privilege on either table' +); +select ok( + has_column_privilege('authenticated', 'public.workspaces', 'personal_user_id', 'select') + and has_column_privilege('authenticated', 'public.workspace_members', 'member_role', 'select'), + 'authenticated selects the granted columns (RLS then filters rows)' +); + +-- --------------------------------------------------------------------------- +-- 10. Policies and definer functions +-- --------------------------------------------------------------------------- +select is( + (select string_agg(tablename || ':' || policyname || ':' || cmd || ':' || array_to_string(roles, '+'), ',' + order by tablename collate "C") + from pg_policies where schemaname = 'public' and tablename in ('workspaces', 'workspace_members')), + 'workspace_members:workspace_members_select_member:SELECT:authenticated,workspaces:workspaces_select_member:SELECT:authenticated', + 'one SELECT policy per table, for authenticated only; no write policy' +); +select is( + (select count(*) from pg_policies where schemaname = 'public' and tablename in ('workspaces', 'workspace_members') + and (qual not like '%caller_workspace_ids()%' or qual like '%platform%' or qual like '%support%')), + 0::bigint, 'both policies go through caller_workspace_ids() and name no platform role (D16)' +); +select is( + (select string_agg(p.proname::text, ',' order by p.proname::text collate "C") + from pg_proc p join pg_namespace n on n.oid = p.pronamespace + where n.nspname = 'private' and p.proname in ('backfill_personal_workspaces', 'caller_workspace_ids', + 'check_personal_workspace', 'create_personal_workspace', 'ensure_personal_workspace', 'writable_workspace_ids') + and p.prosecdef and p.proconfig = array['search_path=""'] + and pg_get_userbyid(p.proowner) = 'postgres'), + 'backfill_personal_workspaces,caller_workspace_ids,check_personal_workspace,create_personal_workspace,ensure_personal_workspace,writable_workspace_ids', + 'the six workspace functions are security definer, owned by postgres, search_path empty' +); +select ok( + (select p.prosecdef and p.proconfig = array['search_path=""'] from pg_proc p + where p.oid = 'private.log_event(uuid, text, text, uuid, uuid, uuid, jsonb)'::regprocedure), + 'log_event keeps security definer and its empty search_path' +); +select is( + (select string_agg(r.role || ':' || p.proname::text, ',' order by r.role, p.proname::text collate "C") + from pg_proc p join pg_namespace n on n.oid = p.pronamespace + cross join (values ('anon'), ('authenticated'), ('service_role')) r(role) + where n.nspname = 'private' and p.proname in ('backfill_personal_workspaces', 'caller_workspace_ids', + 'check_personal_workspace', 'create_personal_workspace', 'ensure_personal_workspace', 'writable_workspace_ids') + and has_function_privilege(r.role, p.oid, 'execute')), + 'authenticated:caller_workspace_ids', + 'EXECUTE: authenticated on the policy helper only; anon and service_role on none' +); +select ok( + has_function_privilege('service_role', 'private.log_event(uuid, text, text, uuid, uuid, uuid, jsonb)', 'execute') + and not has_function_privilege('authenticated', 'private.log_event(uuid, text, text, uuid, uuid, uuid, jsonb)', 'execute'), + 'log_event keeps the privileges of the foundation (service_role yes, authenticated no)' +); +select is( + (select count(*) from pg_trigger where not tgisinternal and tgdeferrable and tginitdeferred + and tgname in ('workspaces_personal_holder', 'workspace_members_personal_holder')), + 2::bigint, 'the invariant triggers are deferred to commit' +); + +-- --------------------------------------------------------------------------- +-- 11. Account deletion: an empty account takes its workspace along (D9a) +-- --------------------------------------------------------------------------- +set constraints workspaces_personal_holder, workspace_members_personal_holder immediate; +select lives_ok( + $$ delete from auth.users where id = '50000000-0000-0000-0000-00000000000e' $$, + 'deleting an empty account passes the invariant' +); +select is(pg_temp.ws('50000000-0000-0000-0000-00000000000e'), null, 'its workspace is gone'); +select is( + (select count(*) from public.workspace_members where user_id = '50000000-0000-0000-0000-00000000000e'), + 0::bigint, 'its membership is gone' +); +set constraints all deferred; + +-- --------------------------------------------------------------------------- +-- 12. Audit correlation id: kept only as a short token (contract §10, N9) +-- --------------------------------------------------------------------------- +select set_config('request.headers', '{"x-correlation-id":"req-7f3a-01"}', true); +insert into pg_temp.audit_ids values ('valid', private.log_event(null, 'workspace.probed', 'workspace')); +select set_config('request.headers', json_build_object('x-correlation-id', repeat('a', 64))::text, true); +insert into pg_temp.audit_ids values ('max', private.log_event(null, 'workspace.probed', 'workspace')); +select set_config('request.headers', json_build_object('x-correlation-id', repeat('a', 65))::text, true); +insert into pg_temp.audit_ids values ('long', private.log_event(null, 'workspace.probed', 'workspace')); +select set_config('request.headers', json_build_object('x-correlation-id', repeat('x', 8192))::text, true); +insert into pg_temp.audit_ids values ('huge', private.log_event(null, 'workspace.probed', 'workspace')); +select set_config('request.headers', '{"x-correlation-id":"a b"}', true); +insert into pg_temp.audit_ids values ('space', private.log_event(null, 'workspace.probed', 'workspace')); +select set_config('request.headers', '{"x-correlation-id":"abc\n"}', true); +insert into pg_temp.audit_ids values ('newline', private.log_event(null, 'workspace.probed', 'workspace')); +select set_config('request.headers', '{"x-correlation-id":{"nested":"x"}}', true); +insert into pg_temp.audit_ids values ('object', private.log_event(null, 'workspace.probed', 'workspace')); +select set_config('request.headers', '{}', true); +insert into pg_temp.audit_ids values ('absent', private.log_event(null, 'workspace.probed', 'workspace')); +select set_config('request.headers', '', true); + +select is( + (select correlation_id from audit.audit_logs where id = (select id from pg_temp.audit_ids where key = 'valid')), + 'req-7f3a-01', 'a short token is kept' +); +select is( + (select char_length(correlation_id) from audit.audit_logs where id = (select id from pg_temp.audit_ids where key = 'max')), + 64, 'a 64-character token is kept' +); +select is( + (select string_agg(i.key, ',' order by i.key collate "C") from pg_temp.audit_ids i + join audit.audit_logs a on a.id = i.id where a.correlation_id is null), + 'absent,huge,long,newline,object,space', + 'an oversized, malformed or absent correlation id is stored as null' +); +select throws_ok( + $$ insert into audit.audit_logs (action, resource_type, correlation_id) values ('workspace.probed', 'workspace', repeat('a', 65)) $$, + '23514', null, 'the CHECK refuses an oversized correlation id on a new row, whoever writes it' +); + +select * from finish(); +rollback;