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:
1 parent
62c5a3ac86
commit
2d5ff0c33e
10 files changed
+1142
No files matched your search
@@ -0,0 +1 @@
|
||||
v2.120.0
|
||||
@@ -0,0 +1,118 @@
|
||||
# Supabase CLI configuration (local stack + self-hosted parity).
|
||||
# Generated from `supabase init` (CLI 2.120) and trimmed to what the project
|
||||
# needs. Full reference: https://supabase.com/docs/guides/local-development/cli/config
|
||||
project_id = "faunosteo"
|
||||
|
||||
[api]
|
||||
enabled = true
|
||||
port = 54321
|
||||
# Only public is exposed through PostgREST. private and audit stay internal
|
||||
# (docs/development/BACKEND_ARCHITECTURE.md §3).
|
||||
schemas = ["public"]
|
||||
extra_search_path = ["public", "extensions"]
|
||||
max_rows = 1000
|
||||
|
||||
[api.tls]
|
||||
enabled = false
|
||||
|
||||
[db]
|
||||
port = 54322
|
||||
shadow_port = 54320
|
||||
health_timeout = "2m"
|
||||
# PostgreSQL 17, same major as the PGlite harness in packages/supabase.
|
||||
major_version = 17
|
||||
|
||||
[db.pooler]
|
||||
enabled = false
|
||||
|
||||
[db.migrations]
|
||||
enabled = true
|
||||
schema_paths = []
|
||||
|
||||
[db.seed]
|
||||
enabled = true
|
||||
# Local development data only (dev accounts + first owner). Never run in prod.
|
||||
sql_paths = ["./seed.sql"]
|
||||
|
||||
[realtime]
|
||||
# Not used before the cloud-reports step.
|
||||
enabled = false
|
||||
|
||||
[studio]
|
||||
enabled = true
|
||||
port = 54323
|
||||
api_url = "http://127.0.0.1"
|
||||
|
||||
# Local mail catcher: confirmation and OTP mails land at http://127.0.0.1:54324
|
||||
[local_smtp]
|
||||
enabled = true
|
||||
port = 54324
|
||||
|
||||
[storage]
|
||||
enabled = true
|
||||
file_size_limit = "50MiB"
|
||||
|
||||
[storage.s3_protocol]
|
||||
enabled = false
|
||||
|
||||
[storage.analytics]
|
||||
enabled = false
|
||||
|
||||
[storage.vector]
|
||||
enabled = false
|
||||
|
||||
[auth]
|
||||
enabled = true
|
||||
# Vite dev server of apps/app
|
||||
site_url = "http://127.0.0.1:5173"
|
||||
additional_redirect_urls = ["http://127.0.0.1:5173", "http://localhost:5173"]
|
||||
jwt_expiry = 3600
|
||||
enable_refresh_token_rotation = true
|
||||
refresh_token_reuse_interval = 10
|
||||
enable_signup = true
|
||||
enable_anonymous_sign_ins = false
|
||||
enable_manual_linking = false
|
||||
# Security baseline (business architecture §30): strong password policy.
|
||||
minimum_password_length = 12
|
||||
password_requirements = "lower_upper_letters_digits"
|
||||
|
||||
[auth.rate_limit]
|
||||
email_sent = 2
|
||||
sms_sent = 30
|
||||
anonymous_users = 30
|
||||
token_refresh = 150
|
||||
sign_in_sign_ups = 30
|
||||
token_verifications = 30
|
||||
|
||||
[auth.email]
|
||||
enable_signup = true
|
||||
double_confirm_changes = true
|
||||
# Email verification is mandatory before professional features (§30).
|
||||
enable_confirmations = true
|
||||
secure_password_change = true
|
||||
max_frequency = "1m0s"
|
||||
otp_length = 6
|
||||
otp_expiry = 3600
|
||||
|
||||
[auth.sms]
|
||||
# SMS provider deferred (OPEN_QUESTIONS Q7).
|
||||
enable_signup = false
|
||||
enable_confirmations = false
|
||||
|
||||
[auth.mfa]
|
||||
max_enrolled_factors = 10
|
||||
|
||||
[auth.mfa.totp]
|
||||
# Enrolment opens with the identity step (mandatory for platform staff).
|
||||
enroll_enabled = false
|
||||
verify_enabled = false
|
||||
|
||||
[edge_runtime]
|
||||
# No Edge Function before the files/webhooks steps; keeps the local stack light.
|
||||
enabled = false
|
||||
|
||||
[analytics]
|
||||
enabled = false
|
||||
|
||||
[experimental.pgdelta]
|
||||
enabled = false
|
||||
@@ -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())));
|
||||
@@ -0,0 +1,54 @@
|
||||
-- Local development seed. Applied by `supabase db reset` / `supabase start`
|
||||
-- on the LOCAL stack only (config.toml [db.seed]). Never run against a shared
|
||||
-- or production database: it creates accounts with a known password.
|
||||
--
|
||||
-- Accounts (password for all three: LocalDev-only-password-1)
|
||||
-- owner@faunosteo.local platform owner (bootstrapped below)
|
||||
-- alice@faunosteo.local plain user
|
||||
-- bob@faunosteo.local plain user
|
||||
--
|
||||
-- Needs the real auth schema (auth.identities, extensions.crypt): not part of
|
||||
-- the PGlite harness, which only applies migrations.
|
||||
|
||||
create or replace function pg_temp.seed_user(p_id uuid, p_email text, p_display_name text)
|
||||
returns void
|
||||
language plpgsql
|
||||
as $$
|
||||
begin
|
||||
insert into auth.users (
|
||||
instance_id, id, aud, role, email, encrypted_password, email_confirmed_at,
|
||||
raw_app_meta_data, raw_user_meta_data, created_at, updated_at,
|
||||
confirmation_token, recovery_token, email_change_token_new, email_change
|
||||
)
|
||||
values (
|
||||
'00000000-0000-0000-0000-000000000000', p_id, 'authenticated', 'authenticated',
|
||||
p_email, extensions.crypt('LocalDev-only-password-1', extensions.gen_salt('bf')), now(),
|
||||
'{"provider":"email","providers":["email"]}'::jsonb,
|
||||
jsonb_build_object('display_name', p_display_name, 'locale', 'fr'),
|
||||
now(), now(), '', '', '', ''
|
||||
)
|
||||
on conflict (id) do nothing;
|
||||
|
||||
insert into auth.identities (
|
||||
id, user_id, provider_id, identity_data, provider,
|
||||
last_sign_in_at, created_at, updated_at
|
||||
)
|
||||
values (
|
||||
gen_random_uuid(), p_id, p_id::text,
|
||||
jsonb_build_object('sub', p_id::text, 'email', p_email, 'email_verified', true),
|
||||
'email', now(), now(), now()
|
||||
)
|
||||
on conflict (provider_id, provider) do nothing;
|
||||
end;
|
||||
$$;
|
||||
|
||||
select pg_temp.seed_user('10000000-0000-0000-0000-000000000001', 'owner@faunosteo.local', 'Owner Local');
|
||||
select pg_temp.seed_user('10000000-0000-0000-0000-00000000000a', 'alice@faunosteo.local', 'Alice Local');
|
||||
select pg_temp.seed_user('10000000-0000-0000-0000-00000000000b', 'bob@faunosteo.local', 'Bob Local');
|
||||
|
||||
-- First platform owner (system bootstrap, audited with a null actor).
|
||||
select private.assign_platform_role(null, '10000000-0000-0000-0000-000000000001', 'owner')
|
||||
where not exists (
|
||||
select 1 from public.profile_roles
|
||||
where user_id = '10000000-0000-0000-0000-000000000001' and role = 'owner' and revoked_at is null
|
||||
);
|
||||
@@ -0,0 +1,53 @@
|
||||
-- Schema contract: objects exist, RLS is on, API roles start from zero.
|
||||
begin;
|
||||
select plan(22);
|
||||
|
||||
-- Schemas
|
||||
select has_schema('private', 'schema private exists');
|
||||
select has_schema('audit', 'schema audit exists');
|
||||
|
||||
-- Tables
|
||||
select has_table('public', 'profiles', 'table public.profiles exists');
|
||||
select has_table('public', 'profile_roles', 'table public.profile_roles exists');
|
||||
select has_table('audit', 'audit_logs', 'table audit.audit_logs exists');
|
||||
|
||||
-- RLS enabled everywhere (pgTAP has no helper: read pg_class)
|
||||
select ok(
|
||||
(select relrowsecurity from pg_class where oid = 'public.profiles'::regclass),
|
||||
'RLS enabled on profiles'
|
||||
);
|
||||
select ok(
|
||||
(select relrowsecurity from pg_class where oid = 'public.profile_roles'::regclass),
|
||||
'RLS enabled on profile_roles'
|
||||
);
|
||||
select ok(
|
||||
(select relrowsecurity from pg_class where oid = 'audit.audit_logs'::regclass),
|
||||
'RLS enabled on audit_logs'
|
||||
);
|
||||
|
||||
-- Enum
|
||||
select enum_has_labels(
|
||||
'public', 'platform_role',
|
||||
array['owner', 'admin', 'moderator', 'support'],
|
||||
'platform_role has exactly the four platform roles (no professional status)'
|
||||
);
|
||||
|
||||
-- Functions
|
||||
select has_function('private', 'log_event', 'private.log_event exists');
|
||||
select has_function('private', 'is_platform_owner', array['uuid'], 'private.is_platform_owner exists');
|
||||
select has_function('private', 'is_platform_admin', array['uuid'], 'private.is_platform_admin exists');
|
||||
select has_function('private', 'is_platform_moderator', array['uuid'], 'private.is_platform_moderator exists');
|
||||
select has_function('private', 'is_support', array['uuid'], 'private.is_support exists');
|
||||
select has_function('public', 'grant_platform_role', array['uuid', 'platform_role'], 'public.grant_platform_role exists');
|
||||
select has_function('public', 'revoke_platform_role', array['uuid', 'platform_role', 'text'], 'public.revoke_platform_role exists');
|
||||
|
||||
-- Privileges: anon has nothing, authenticated has only what RLS then filters
|
||||
select ok(not has_table_privilege('anon', 'public.profiles', 'select'), 'anon cannot select profiles');
|
||||
select ok(not has_table_privilege('anon', 'public.profile_roles', 'select'), 'anon cannot select profile_roles');
|
||||
select ok(not has_table_privilege('authenticated', 'public.profiles', 'insert'), 'authenticated cannot insert profiles');
|
||||
select ok(not has_table_privilege('authenticated', 'public.profiles', 'delete'), 'authenticated cannot delete profiles');
|
||||
select ok(not has_table_privilege('authenticated', 'public.profile_roles', 'insert'), 'authenticated cannot insert profile_roles');
|
||||
select ok(not has_column_privilege('authenticated', 'public.profiles', 'active', 'update'), 'authenticated cannot update profiles.active');
|
||||
|
||||
select * from finish();
|
||||
rollback;
|
||||
@@ -0,0 +1,131 @@
|
||||
-- profiles: trigger creation, own-row read/update, every denied path.
|
||||
begin;
|
||||
select plan(17);
|
||||
|
||||
-- Fixtures (privileged session = migration owner)
|
||||
insert into auth.users (id, email, raw_user_meta_data) values
|
||||
('00000000-0000-0000-0000-00000000000a', 'alice@test.local', '{"display_name":"Alice","locale":"en"}'),
|
||||
('00000000-0000-0000-0000-00000000000b', 'bob@test.local', '{}'),
|
||||
('00000000-0000-0000-0000-00000000000c', 'carol.long.name@test.local', '{"locale":"xx"}');
|
||||
|
||||
-- 1. Trigger builds the profile
|
||||
select results_eq(
|
||||
$$ select display_name, locale from public.profiles where id = '00000000-0000-0000-0000-00000000000a' $$,
|
||||
$$ values ('Alice'::text, 'en'::text) $$,
|
||||
'profile created from metadata (display_name + locale)'
|
||||
);
|
||||
select results_eq(
|
||||
$$ select display_name, locale from public.profiles where id = '00000000-0000-0000-0000-00000000000b' $$,
|
||||
$$ values ('bob'::text, 'fr'::text) $$,
|
||||
'profile falls back to the email local part and locale fr'
|
||||
);
|
||||
select is(
|
||||
(select locale from public.profiles where id = '00000000-0000-0000-0000-00000000000c'),
|
||||
'fr',
|
||||
'unsupported locale in metadata falls back to fr'
|
||||
);
|
||||
|
||||
-- 2. Alice, authenticated
|
||||
set local role authenticated;
|
||||
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
|
||||
|
||||
select results_eq(
|
||||
$$ select id from public.profiles order by id $$,
|
||||
$$ values ('00000000-0000-0000-0000-00000000000a'::uuid) $$,
|
||||
'alice sees exactly her own profile'
|
||||
);
|
||||
select is(
|
||||
(select count(*) from public.profiles where id = '00000000-0000-0000-0000-00000000000b'),
|
||||
0::bigint,
|
||||
'alice cannot read bob by id (no IDOR)'
|
||||
);
|
||||
|
||||
select lives_ok(
|
||||
$$ update public.profiles set display_name = 'Alice B.', timezone = 'Europe/Brussels' where id = '00000000-0000-0000-0000-00000000000a' $$,
|
||||
'alice updates her own display_name and timezone'
|
||||
);
|
||||
select is(
|
||||
(select display_name from public.profiles where id = '00000000-0000-0000-0000-00000000000a'),
|
||||
'Alice B.',
|
||||
'own update is visible'
|
||||
);
|
||||
|
||||
-- Update on another row: RLS filters it out silently (0 rows)
|
||||
update public.profiles set display_name = 'hacked' where id = '00000000-0000-0000-0000-00000000000b';
|
||||
select throws_ok(
|
||||
$$ update public.profiles set active = false where id = '00000000-0000-0000-0000-00000000000a' $$,
|
||||
'42501',
|
||||
null,
|
||||
'alice cannot deactivate herself (column privilege)'
|
||||
);
|
||||
select throws_ok(
|
||||
$$ update public.profiles set phone_verified_at = now() where id = '00000000-0000-0000-0000-00000000000a' $$,
|
||||
'42501',
|
||||
null,
|
||||
'alice cannot self-verify her phone (column privilege)'
|
||||
);
|
||||
select throws_ok(
|
||||
$$ insert into public.profiles (id, display_name) values (gen_random_uuid(), 'ghost') $$,
|
||||
'42501',
|
||||
null,
|
||||
'alice cannot insert a profile'
|
||||
);
|
||||
select throws_ok(
|
||||
$$ delete from public.profiles where id = '00000000-0000-0000-0000-00000000000a' $$,
|
||||
'42501',
|
||||
null,
|
||||
'alice cannot delete her profile'
|
||||
);
|
||||
select throws_ok(
|
||||
$$ update public.profiles set phone = '0612345678' where id = '00000000-0000-0000-0000-00000000000a' $$,
|
||||
'23514',
|
||||
null,
|
||||
'phone must be E.164'
|
||||
);
|
||||
|
||||
-- 3. Bob sees his row untouched
|
||||
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-00000000000b","role":"authenticated"}', true);
|
||||
select is(
|
||||
(select display_name from public.profiles where id = '00000000-0000-0000-0000-00000000000b'),
|
||||
'bob',
|
||||
'alice''s cross-row update did not touch bob'
|
||||
);
|
||||
|
||||
-- 4. Phone change resets verification
|
||||
reset role;
|
||||
update public.profiles
|
||||
set phone = '+33612345678', phone_verified_at = now()
|
||||
where id = '00000000-0000-0000-0000-00000000000b';
|
||||
set local role authenticated;
|
||||
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-00000000000b","role":"authenticated"}', true);
|
||||
select lives_ok(
|
||||
$$ update public.profiles set phone = '+33698765432' where id = '00000000-0000-0000-0000-00000000000b' $$,
|
||||
'bob changes his phone'
|
||||
);
|
||||
select is(
|
||||
(select phone_verified_at from public.profiles where id = '00000000-0000-0000-0000-00000000000b'),
|
||||
null,
|
||||
'changing the phone clears phone_verified_at'
|
||||
);
|
||||
|
||||
-- 5. Anonymous: no access at all
|
||||
set local role anon;
|
||||
select set_config('request.jwt.claims', '', true);
|
||||
select throws_ok(
|
||||
$$ select * from public.profiles $$,
|
||||
'42501',
|
||||
null,
|
||||
'anon cannot select profiles'
|
||||
);
|
||||
|
||||
-- 6. updated_at trigger overrides whatever the writer sends
|
||||
reset role;
|
||||
update public.profiles set updated_at = '2000-01-01' where id = '00000000-0000-0000-0000-00000000000a';
|
||||
select is(
|
||||
(select updated_at from public.profiles where id = '00000000-0000-0000-0000-00000000000a'),
|
||||
now(),
|
||||
'updated_at is stamped by the trigger, not by the writer'
|
||||
);
|
||||
|
||||
select * from finish();
|
||||
rollback;
|
||||
@@ -0,0 +1,147 @@
|
||||
-- Platform roles: bootstrap, delegation rules, every denied path, visibility.
|
||||
begin;
|
||||
select plan(28);
|
||||
|
||||
insert into auth.users (id, email) values
|
||||
('00000000-0000-0000-0000-000000000001', 'root@test.local'),
|
||||
('00000000-0000-0000-0000-00000000000a', 'alice@test.local'),
|
||||
('00000000-0000-0000-0000-00000000000b', 'bob@test.local'),
|
||||
('00000000-0000-0000-0000-00000000000c', 'carol@test.local');
|
||||
|
||||
-- 1. Nobody has a role; bootstrap the first owner from a privileged session
|
||||
select ok(not private.is_platform_owner('00000000-0000-0000-0000-000000000001'), 'fresh account has no owner role');
|
||||
select lives_ok(
|
||||
$$ select private.assign_platform_role(null, '00000000-0000-0000-0000-000000000001', 'owner') $$,
|
||||
'system bootstraps the first owner (actor null)'
|
||||
);
|
||||
select ok(private.is_platform_owner('00000000-0000-0000-0000-000000000001'), 'root is owner');
|
||||
select ok(private.is_platform_admin('00000000-0000-0000-0000-000000000001'), 'owner counts as admin');
|
||||
select ok(private.is_platform_moderator('00000000-0000-0000-0000-000000000001'), 'owner counts as moderator');
|
||||
select ok(not private.is_support('00000000-0000-0000-0000-000000000001'), 'owner is not support');
|
||||
|
||||
-- 2. Owner grants admin to alice through the RPC
|
||||
set local role authenticated;
|
||||
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-000000000001","role":"authenticated"}', true);
|
||||
select lives_ok(
|
||||
$$ select public.grant_platform_role('00000000-0000-0000-0000-00000000000a', 'admin') $$,
|
||||
'owner grants admin'
|
||||
);
|
||||
select throws_ok(
|
||||
$$ select public.grant_platform_role('00000000-0000-0000-0000-00000000000a', 'admin') $$,
|
||||
'23505',
|
||||
null,
|
||||
'granting an active role twice is refused'
|
||||
);
|
||||
select throws_ok(
|
||||
$$ select public.grant_platform_role('00000000-0000-0000-0000-000000000001', 'admin') $$,
|
||||
'42501',
|
||||
null,
|
||||
'owner cannot change their own roles'
|
||||
);
|
||||
select throws_ok(
|
||||
$$ select public.grant_platform_role(gen_random_uuid(), 'support') $$,
|
||||
'P0002',
|
||||
null,
|
||||
'unknown target is refused'
|
||||
);
|
||||
|
||||
-- 3. Alice (admin) may delegate moderator/support, nothing above
|
||||
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
|
||||
select lives_ok(
|
||||
$$ select public.grant_platform_role('00000000-0000-0000-0000-00000000000b', 'moderator') $$,
|
||||
'admin grants moderator'
|
||||
);
|
||||
select throws_ok(
|
||||
$$ select public.grant_platform_role('00000000-0000-0000-0000-00000000000b', 'admin') $$,
|
||||
'42501',
|
||||
null,
|
||||
'admin cannot grant admin'
|
||||
);
|
||||
select throws_ok(
|
||||
$$ select public.grant_platform_role('00000000-0000-0000-0000-00000000000b', 'owner') $$,
|
||||
'42501',
|
||||
null,
|
||||
'admin cannot grant owner'
|
||||
);
|
||||
select throws_ok(
|
||||
$$ select public.grant_platform_role('00000000-0000-0000-0000-00000000000a', 'owner') $$,
|
||||
'42501',
|
||||
null,
|
||||
'admin cannot promote herself to owner'
|
||||
);
|
||||
|
||||
-- 4. Direct writes are impossible for the API role
|
||||
select throws_ok(
|
||||
$$ insert into public.profile_roles (user_id, role) values ('00000000-0000-0000-0000-00000000000a', 'owner') $$,
|
||||
'42501',
|
||||
null,
|
||||
'admin cannot insert a role row directly'
|
||||
);
|
||||
select throws_ok(
|
||||
$$ update public.profile_roles set role = 'owner' where user_id = '00000000-0000-0000-0000-00000000000a' $$,
|
||||
'42501',
|
||||
null,
|
||||
'admin cannot update role rows directly'
|
||||
);
|
||||
select throws_ok(
|
||||
$$ delete from public.profile_roles $$,
|
||||
'42501',
|
||||
null,
|
||||
'admin cannot delete role rows directly'
|
||||
);
|
||||
|
||||
-- 5. Bob (moderator) cannot delegate; sees only his own grants; carol sees nothing
|
||||
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-00000000000b","role":"authenticated"}', true);
|
||||
select throws_ok(
|
||||
$$ select public.grant_platform_role('00000000-0000-0000-0000-00000000000c', 'support') $$,
|
||||
'42501',
|
||||
null,
|
||||
'moderator cannot grant any role'
|
||||
);
|
||||
select results_eq(
|
||||
$$ select user_id, role::text from public.profile_roles $$,
|
||||
$$ values ('00000000-0000-0000-0000-00000000000b'::uuid, 'moderator'::text) $$,
|
||||
'moderator sees only his own grant rows'
|
||||
);
|
||||
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-00000000000c","role":"authenticated"}', true);
|
||||
select is((select count(*) from public.profile_roles), 0::bigint, 'plain user sees no role rows');
|
||||
select is((select count(*) from public.profiles), 1::bigint, 'plain user still sees one profile (own)');
|
||||
|
||||
-- 6. Admin sees every grant and every profile (staff read)
|
||||
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
|
||||
select is((select count(*) from public.profile_roles), 3::bigint, 'admin sees all three grant rows');
|
||||
select is((select count(*) from public.profiles), 4::bigint, 'admin reads every profile');
|
||||
|
||||
-- 7. Anonymous
|
||||
set local role anon;
|
||||
select set_config('request.jwt.claims', '', true);
|
||||
select throws_ok(
|
||||
$$ select public.grant_platform_role('00000000-0000-0000-0000-00000000000c', 'support') $$,
|
||||
'42501',
|
||||
null,
|
||||
'anon cannot call grant_platform_role'
|
||||
);
|
||||
|
||||
-- 8. Revocation and deactivation
|
||||
set local role authenticated;
|
||||
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
|
||||
select lives_ok(
|
||||
$$ select public.revoke_platform_role('00000000-0000-0000-0000-00000000000b', 'moderator', 'test') $$,
|
||||
'admin revokes moderator'
|
||||
);
|
||||
select ok(not private.is_platform_moderator('00000000-0000-0000-0000-00000000000b'), 'revoked role no longer counts');
|
||||
|
||||
reset role;
|
||||
update public.profiles set active = false where id = '00000000-0000-0000-0000-00000000000a';
|
||||
select ok(not private.is_platform_admin('00000000-0000-0000-0000-00000000000a'), 'deactivated account loses its roles');
|
||||
|
||||
-- 9. Last-owner guard on the system path
|
||||
select throws_ok(
|
||||
$$ select private.withdraw_platform_role(null, '00000000-0000-0000-0000-000000000001', 'owner', 'oops') $$,
|
||||
'42501',
|
||||
null,
|
||||
'the last owner cannot be revoked'
|
||||
);
|
||||
|
||||
select * from finish();
|
||||
rollback;
|
||||
@@ -0,0 +1,99 @@
|
||||
-- audit.audit_logs: sensitive operations leave a row, rows are immutable,
|
||||
-- only owners/admins read them.
|
||||
begin;
|
||||
select plan(12);
|
||||
|
||||
insert into auth.users (id, email) values
|
||||
('00000000-0000-0000-0000-000000000001', 'root@test.local'),
|
||||
('00000000-0000-0000-0000-00000000000a', 'alice@test.local'),
|
||||
('00000000-0000-0000-0000-00000000000b', 'bob@test.local');
|
||||
select private.assign_platform_role(null, '00000000-0000-0000-0000-000000000001', 'owner');
|
||||
|
||||
-- 1. Bootstrap is audited as a system action
|
||||
select results_eq(
|
||||
$$ select actor_user_id, action, resource_type, target_user_id, metadata ->> 'role'
|
||||
from audit.audit_logs $$,
|
||||
$$ values (null::uuid, 'platform_role.granted'::text, 'profile_role'::text,
|
||||
'00000000-0000-0000-0000-000000000001'::uuid, 'owner'::text) $$,
|
||||
'bootstrap grant logged with null actor'
|
||||
);
|
||||
|
||||
-- 2. RPC grant and revoke are audited with the actor
|
||||
set local role authenticated;
|
||||
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-000000000001","role":"authenticated"}', true);
|
||||
select public.grant_platform_role('00000000-0000-0000-0000-00000000000a', 'admin');
|
||||
select public.revoke_platform_role('00000000-0000-0000-0000-00000000000a', 'admin', 'rotation');
|
||||
reset role;
|
||||
|
||||
select results_eq(
|
||||
$$ select action, actor_user_id, target_user_id, metadata ->> 'reason'
|
||||
from audit.audit_logs where actor_user_id is not null order by occurred_at, action $$,
|
||||
$$ values ('platform_role.granted'::text, '00000000-0000-0000-0000-000000000001'::uuid,
|
||||
'00000000-0000-0000-0000-00000000000a'::uuid, null::text),
|
||||
('platform_role.revoked'::text, '00000000-0000-0000-0000-000000000001'::uuid,
|
||||
'00000000-0000-0000-0000-00000000000a'::uuid, 'rotation'::text) $$,
|
||||
'grant and revoke logged with actor, target and metadata'
|
||||
);
|
||||
select is(
|
||||
(select count(*) from audit.audit_logs a
|
||||
join public.profile_roles r on r.id = a.resource_id),
|
||||
3::bigint,
|
||||
'every audit row points at its profile_roles row'
|
||||
);
|
||||
|
||||
-- 3. Append-only, even for the privileged owner session
|
||||
select throws_ok(
|
||||
$$ update audit.audit_logs set action = 'platform_role.tampered' $$,
|
||||
'42501',
|
||||
null,
|
||||
'audit rows cannot be updated'
|
||||
);
|
||||
select throws_ok(
|
||||
$$ delete from audit.audit_logs $$,
|
||||
'42501',
|
||||
null,
|
||||
'audit rows cannot be deleted'
|
||||
);
|
||||
|
||||
-- 4. log_event validates its inputs
|
||||
select throws_ok(
|
||||
$$ select private.log_event(null, 'Bad Action', 'profile') $$,
|
||||
'23514',
|
||||
null,
|
||||
'action must match <domain>.<verb>'
|
||||
);
|
||||
select throws_ok(
|
||||
$$ select private.log_event(null, 'export.requested', 'profile', null, null, null, '[]'::jsonb) $$,
|
||||
'23514',
|
||||
null,
|
||||
'metadata must be a JSON object'
|
||||
);
|
||||
|
||||
-- 5. Read access: owner yes, plain user no, anon no, nobody writes through the API
|
||||
set local role authenticated;
|
||||
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-000000000001","role":"authenticated"}', true);
|
||||
select is((select count(*) from audit.audit_logs), 3::bigint, 'owner reads the audit log');
|
||||
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-00000000000b","role":"authenticated"}', true);
|
||||
select is((select count(*) from audit.audit_logs), 0::bigint, 'plain user reads nothing');
|
||||
select throws_ok(
|
||||
$$ insert into audit.audit_logs (action, resource_type) values ('x.y', 'z') $$,
|
||||
'42501',
|
||||
null,
|
||||
'authenticated cannot insert audit rows'
|
||||
);
|
||||
select throws_ok(
|
||||
$$ select private.log_event(null, 'x.y', 'z') $$,
|
||||
'42501',
|
||||
null,
|
||||
'authenticated cannot call log_event'
|
||||
);
|
||||
set local role anon;
|
||||
select throws_ok(
|
||||
$$ select * from audit.audit_logs $$,
|
||||
'42501',
|
||||
null,
|
||||
'anon cannot read the audit log'
|
||||
);
|
||||
|
||||
select * from finish();
|
||||
rollback;
|
||||
Reference in new issue
Block a user