feat(supabase): foundation migrations (audit, profiles, platform roles) + pgTAP suite

- schemas private/audit, set_updated_at, append-only audit.audit_logs, private.log_event
- profiles created by auth.users trigger; own-row RLS; column-level UPDATE grant
- platform_role enum (owner/admin/moderator/support), profile_roles history table,
  is_platform_* helpers, grant/revoke RPCs audited; writes only via RPC
- config.toml (public schema only, strong passwords, no edge runtime), local seed
- 79 pgTAP checks: allowed and denied paths for every policy
This commit is contained in:
bchanot committed 2026-10-08 22:20:54 +02:00
1 parent 62c5a3ac86
commit 2d5ff0c33e
10 files changed
+1142

No files matched your search

@@ -0,0 +1,135 @@
-- Foundation: schemas, shared triggers, append-only audit log.
-- Conventions: docs/development/BACKEND_ARCHITECTURE.md §3, §7; business architecture §29.
-- Forward-only. Never edit after it has been applied: write a new migration.
-- ---------------------------------------------------------------------------
-- Schemas
-- ---------------------------------------------------------------------------
-- private: security-definer helpers and internal functions. Not exposed to
-- PostgREST (config.toml api.schemas lists public only).
create schema if not exists private;
-- audit: append-only event log, read by platform admins only.
create schema if not exists audit;
revoke all on schema private from public;
revoke all on schema audit from public;
-- Policies evaluated for API roles call private.* helpers by qualified name,
-- which needs USAGE on the schema. EXECUTE is granted per function below.
grant usage on schema private to anon, authenticated, service_role;
grant usage on schema audit to authenticated, service_role;
-- PostgreSQL grants EXECUTE on every new function to PUBLIC. Flip the default
-- for both schemas so a helper is callable only where a migration says so.
alter default privileges in schema private revoke execute on functions from public;
alter default privileges in schema audit revoke execute on functions from public;
-- ---------------------------------------------------------------------------
-- Shared trigger: updated_at
-- ---------------------------------------------------------------------------
create or replace function private.set_updated_at()
returns trigger
language plpgsql
set search_path = ''
as $$
begin
new.updated_at := now();
return new;
end;
$$;
comment on function private.set_updated_at() is
'BEFORE UPDATE trigger: stamps updated_at. Attach to every table that has the column.';
-- ---------------------------------------------------------------------------
-- Audit log (business architecture §29)
-- ---------------------------------------------------------------------------
create table audit.audit_logs (
id uuid primary key default gen_random_uuid(),
occurred_at timestamptz not null default now(),
-- null actor = system action (migration, worker, bootstrap).
actor_user_id uuid,
-- "<domain>.<verb>" e.g. platform_role.granted. Kept as text + CHECK: the
-- set grows with every step.
action text not null
constraint audit_logs_action_format check (action ~ '^[a-z_]+\.[a-z_]+$'),
resource_type text not null
constraint audit_logs_resource_type_format check (resource_type ~ '^[a-z_]+$'),
resource_id uuid,
organization_id uuid,
target_user_id uuid,
-- Sanitized by the caller: never report contents, passwords, tokens.
metadata jsonb not null default '{}'::jsonb
constraint audit_logs_metadata_object check (jsonb_typeof(metadata) = 'object'),
correlation_id text
);
comment on table audit.audit_logs is
'Append-only trace of sensitive operations. Insert only through private.log_event(). No FK on user ids: rows outlive accounts.';
create index audit_logs_occurred_at_idx on audit.audit_logs (occurred_at desc);
create index audit_logs_actor_idx on audit.audit_logs (actor_user_id, occurred_at desc);
create index audit_logs_target_idx on audit.audit_logs (target_user_id, occurred_at desc);
create index audit_logs_resource_idx on audit.audit_logs (resource_type, resource_id);
-- Append-only, enforced for every role including the table owner.
create or replace function audit.reject_mutation()
returns trigger
language plpgsql
set search_path = ''
as $$
begin
raise exception 'audit.audit_logs is append-only (% refused)', tg_op
using errcode = '42501';
end;
$$;
create trigger audit_logs_append_only
before update or delete on audit.audit_logs
for each row execute function audit.reject_mutation();
-- Privileges: nobody writes through the API; admins read (policy added with
-- the role helpers in the platform-roles migration).
revoke all on audit.audit_logs from public, anon, authenticated, service_role;
grant select on audit.audit_logs to authenticated, service_role;
alter table audit.audit_logs enable row level security;
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';
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;
$$;
comment on function private.log_event(uuid, text, text, uuid, uuid, uuid, jsonb) is
'Single write path into audit.audit_logs. Called from server-side functions only; never granted to API roles.';
revoke all on function private.log_event(uuid, text, text, uuid, uuid, uuid, jsonb) from public;
grant execute on function private.log_event(uuid, text, text, uuid, uuid, uuid, jsonb) to service_role;
@@ -0,0 +1,121 @@
-- Profiles: one row per auth.users row, created by trigger.
-- Business architecture §4.1 (profiles), §17.3 (own row only).
-- avatar_asset_id waits for the assets table (files step): added then.
create table public.profiles (
id uuid primary key references auth.users (id) on delete cascade,
display_name text not null
constraint profiles_display_name_length check (char_length(display_name) between 1 and 80),
first_name text
constraint profiles_first_name_length check (char_length(first_name) <= 80),
last_name text
constraint profiles_last_name_length check (char_length(last_name) <= 80),
-- E.164; verification is server-side (phone_verified_at is not user-writable).
phone text
constraint profiles_phone_e164 check (phone ~ '^\+[1-9][0-9]{6,14}$'),
phone_verified_at timestamptz,
locale text not null default 'fr'
constraint profiles_locale_supported check (locale in ('fr', 'en')),
timezone text not null default 'Europe/Paris'
constraint profiles_timezone_length check (char_length(timezone) between 1 and 64),
-- Platform-level switch (deactivation by staff). Not user-writable.
active boolean not null default true,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
comment on table public.profiles is
'Account profile, id = auth.users.id. Created by trigger on auth.users; never inserted through the API.';
comment on column public.profiles.active is
'false = deactivated by platform staff; role helpers treat the account as having no platform role.';
create trigger profiles_set_updated_at
before update on public.profiles
for each row execute function private.set_updated_at();
-- A new phone number is unverified until the server verifies it again.
create or replace function private.reset_phone_verification()
returns trigger
language plpgsql
set search_path = ''
as $$
begin
if new.phone is distinct from old.phone then
new.phone_verified_at := null;
end if;
return new;
end;
$$;
create trigger profiles_reset_phone_verification
before update of phone on public.profiles
for each row execute function private.reset_phone_verification();
-- ---------------------------------------------------------------------------
-- auth.users -> profiles
-- ---------------------------------------------------------------------------
create or replace function private.handle_new_auth_user()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
declare
v_meta jsonb := coalesce(new.raw_user_meta_data, '{}'::jsonb);
v_display_name text;
v_locale text;
begin
v_display_name := left(
coalesce(
nullif(trim(v_meta ->> 'display_name'), ''),
nullif(split_part(coalesce(new.email, ''), '@', 1), ''),
'Utilisateur'
),
80
);
v_locale := case
when v_meta ->> 'locale' in ('fr', 'en') then v_meta ->> 'locale'
else 'fr'
end;
insert into public.profiles (id, display_name, locale)
values (new.id, v_display_name, v_locale)
on conflict (id) do nothing;
return new;
end;
$$;
comment on function private.handle_new_auth_user() is
'AFTER INSERT on auth.users: creates the profile row. Display name from metadata, else the email local part.';
create trigger on_auth_user_created
after insert on auth.users
for each row execute function private.handle_new_auth_user();
-- ---------------------------------------------------------------------------
-- Privileges + RLS (API roles). Supabase default privileges grant ALL to
-- anon/authenticated/service_role on new tables: start from zero instead.
-- ---------------------------------------------------------------------------
revoke all on public.profiles from public, anon, authenticated;
grant select on public.profiles to authenticated;
-- Column-level UPDATE: active and phone_verified_at stay server-only.
grant update (display_name, first_name, last_name, phone, locale, timezone)
on public.profiles to authenticated;
alter table public.profiles enable row level security;
create policy profiles_select_own
on public.profiles
for select
to authenticated
using (id = (select auth.uid()));
create policy profiles_update_own
on public.profiles
for update
to authenticated
using (id = (select auth.uid()))
with check (id = (select auth.uid()));
-- No INSERT policy (trigger only), no DELETE policy (no deletion of user data).
@@ -0,0 +1,283 @@
-- Platform roles: owner / admin / moderator / support.
-- Business architecture §2.1, §4.1 (profile_roles), §17.2 (helpers), §17.3.
--
-- Platform roles are NOT professional statuses. practitioner / student /
-- professor are outcomes of professional verification (identity step) and
-- cabinet roles live in organization_members (organizations step). Keeping
-- them out of this enum avoids a self-declared "practitioner" row ever being
-- read as a verified status.
--
-- Hierarchy for permission checks: owner ⊇ admin ⊇ moderator. support is
-- separate and inherits nothing (§17.3 "Support does not inherit moderation").
-- Writes go through the two RPCs below only; the API roles cannot insert,
-- update or delete rows. Revocation keeps the row (history), re-grant adds one.
create type public.platform_role as enum ('owner', 'admin', 'moderator', 'support');
create table public.profile_roles (
id uuid primary key default gen_random_uuid(),
user_id uuid not null references public.profiles (id) on delete cascade,
role public.platform_role not null,
granted_at timestamptz not null default now(),
-- null = system (bootstrap, migration).
granted_by uuid references public.profiles (id) on delete set null,
revoked_at timestamptz,
revoked_by uuid references public.profiles (id) on delete set null,
revoke_reason text
constraint profile_roles_revoke_reason_length check (char_length(revoke_reason) <= 500),
-- revoked_by / revoke_reason only make sense on a revoked row.
constraint profile_roles_revoke_consistent
check (revoked_at is not null or (revoked_by is null and revoke_reason is null))
);
comment on table public.profile_roles is
'Platform role grants (owner/admin/moderator/support). One active row per (user, role); revoked rows kept as history. Writes only via grant_platform_role / revoke_platform_role.';
create unique index profile_roles_active_unique
on public.profile_roles (user_id, role) where revoked_at is null;
create index profile_roles_user_active_idx
on public.profile_roles (user_id) where revoked_at is null;
-- ---------------------------------------------------------------------------
-- Helpers (security definer, read profile_roles bypassing its policies)
-- ---------------------------------------------------------------------------
create or replace function private.has_platform_role(p_user_id uuid, variadic p_roles public.platform_role[])
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select exists (
select 1
from public.profile_roles r
join public.profiles p on p.id = r.user_id
where r.user_id = p_user_id
and r.revoked_at is null
and r.role = any (p_roles)
and p.active
);
$$;
create or replace function private.is_platform_owner(p_user_id uuid)
returns boolean language sql stable security definer set search_path = ''
as $$ select private.has_platform_role(p_user_id, 'owner'); $$;
create or replace function private.is_platform_admin(p_user_id uuid)
returns boolean language sql stable security definer set search_path = ''
as $$ select private.has_platform_role(p_user_id, 'owner', 'admin'); $$;
create or replace function private.is_platform_moderator(p_user_id uuid)
returns boolean language sql stable security definer set search_path = ''
as $$ select private.has_platform_role(p_user_id, 'owner', 'admin', 'moderator'); $$;
create or replace function private.is_support(p_user_id uuid)
returns boolean language sql stable security definer set search_path = ''
as $$ select private.has_platform_role(p_user_id, 'support'); $$;
comment on function private.is_platform_admin(uuid) is 'true for owner or admin (active account).';
comment on function private.is_platform_moderator(uuid) is 'true for owner, admin or moderator (active account).';
comment on function private.is_support(uuid) is 'true for support only; support inherits nothing.';
-- Who may grant or revoke which role. owner: any role. admin: moderator, support.
create or replace function private.can_manage_platform_role(p_actor uuid, p_role public.platform_role)
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select case
when private.is_platform_owner(p_actor) then true
when private.has_platform_role(p_actor, 'admin') then p_role in ('moderator', 'support')
else false
end;
$$;
-- Policies run as the API role: they need EXECUTE on the predicates.
grant execute on function private.has_platform_role(uuid, public.platform_role[]) to authenticated;
grant execute on function private.is_platform_owner(uuid) to authenticated;
grant execute on function private.is_platform_admin(uuid) to authenticated;
grant execute on function private.is_platform_moderator(uuid) to authenticated;
grant execute on function private.is_support(uuid) to authenticated;
-- can_manage_platform_role is called from the RPCs only (owner context).
-- ---------------------------------------------------------------------------
-- Internal write path (system or RPC), audited
-- ---------------------------------------------------------------------------
create or replace function private.assign_platform_role(
p_actor uuid,
p_target uuid,
p_role public.platform_role
)
returns uuid
language plpgsql
security definer
set search_path = ''
as $$
declare
v_id uuid;
begin
if not exists (select 1 from public.profiles where id = p_target) then
raise exception 'unknown user %', p_target using errcode = 'P0002';
end if;
if exists (
select 1 from public.profile_roles
where user_id = p_target and role = p_role and revoked_at is null
) then
raise exception 'role % already granted to %', p_role, p_target using errcode = '23505';
end if;
insert into public.profile_roles (user_id, role, granted_by)
values (p_target, p_role, p_actor)
returning id into v_id;
perform private.log_event(
p_actor, 'platform_role.granted', 'profile_role', v_id, p_target, null,
jsonb_build_object('role', p_role)
);
return v_id;
end;
$$;
create or replace function private.withdraw_platform_role(
p_actor uuid,
p_target uuid,
p_role public.platform_role,
p_reason text
)
returns uuid
language plpgsql
security definer
set search_path = ''
as $$
declare
v_id uuid;
begin
select id into v_id
from public.profile_roles
where user_id = p_target and role = p_role and revoked_at is null;
if v_id is null then
raise exception 'role % is not active for %', p_role, p_target using errcode = 'P0002';
end if;
-- Lock-out guard: the platform always keeps one active owner.
if p_role = 'owner' and (
select count(*) from public.profile_roles where role = 'owner' and revoked_at is null
) <= 1 then
raise exception 'cannot revoke the last platform owner' using errcode = '42501';
end if;
update public.profile_roles
set revoked_at = now(), revoked_by = p_actor, revoke_reason = p_reason
where id = v_id;
perform private.log_event(
p_actor, 'platform_role.revoked', 'profile_role', v_id, p_target, null,
jsonb_build_object('role', p_role, 'reason', p_reason)
);
return v_id;
end;
$$;
comment on function private.assign_platform_role(uuid, uuid, public.platform_role) is
'System write path. Bootstrap the first owner with p_actor = null from a privileged SQL session (docs/development/SUPABASE.md).';
-- ---------------------------------------------------------------------------
-- RPCs (authenticated callers, checked against the actor's own roles)
-- ---------------------------------------------------------------------------
create or replace function public.grant_platform_role(
target_user_id uuid,
role public.platform_role
)
returns uuid
language plpgsql
security definer
set search_path = ''
as $$
declare
v_actor uuid := auth.uid();
begin
if v_actor is null then
raise exception 'authentication required' using errcode = '42501';
end if;
if v_actor = target_user_id then
raise exception 'a user cannot change their own platform roles' using errcode = '42501';
end if;
if not private.can_manage_platform_role(v_actor, role) then
raise exception 'insufficient privileges to grant role %', role using errcode = '42501';
end if;
return private.assign_platform_role(v_actor, target_user_id, role);
end;
$$;
create or replace function public.revoke_platform_role(
target_user_id uuid,
role public.platform_role,
reason text default null
)
returns uuid
language plpgsql
security definer
set search_path = ''
as $$
declare
v_actor uuid := auth.uid();
begin
if v_actor is null then
raise exception 'authentication required' using errcode = '42501';
end if;
if v_actor = target_user_id then
raise exception 'a user cannot change their own platform roles' using errcode = '42501';
end if;
if not private.can_manage_platform_role(v_actor, role) then
raise exception 'insufficient privileges to revoke role %', role using errcode = '42501';
end if;
return private.withdraw_platform_role(v_actor, target_user_id, role, reason);
end;
$$;
comment on function public.grant_platform_role(uuid, public.platform_role) is
'Grants a platform role to another user. owner: any role; admin: moderator/support. Audited.';
comment on function public.revoke_platform_role(uuid, public.platform_role, text) is
'Revokes an active platform role of another user (same rights as grant). Keeps one owner. Audited.';
revoke all on function public.grant_platform_role(uuid, public.platform_role) from public, anon;
revoke all on function public.revoke_platform_role(uuid, public.platform_role, text) from public, anon;
grant execute on function public.grant_platform_role(uuid, public.platform_role) to authenticated, service_role;
grant execute on function public.revoke_platform_role(uuid, public.platform_role, text) to authenticated, service_role;
-- ---------------------------------------------------------------------------
-- Privileges + RLS
-- ---------------------------------------------------------------------------
revoke all on public.profile_roles from public, anon, authenticated;
grant select on public.profile_roles to authenticated;
alter table public.profile_roles enable row level security;
-- Own grants, or every grant for owners/admins. No write policy at all.
create policy profile_roles_select_own_or_admin
on public.profile_roles
for select
to authenticated
using (
user_id = (select auth.uid())
or private.is_platform_admin((select auth.uid()))
);
-- Staff read of profiles (owner/admin/support), now that the helpers exist.
create policy profiles_select_staff
on public.profiles
for select
to authenticated
using (
private.is_platform_admin((select auth.uid()))
or private.is_support((select auth.uid()))
);
-- Audit log read: owners and admins.
create policy audit_logs_select_admin
on audit.audit_logs
for select
to authenticated
using (private.is_platform_admin((select auth.uid())));