From b1858542d0052121658a3787645e2eee1ea7e4ab Mon Sep 17 00:00:00 2001 From: Oier Bravo Urtasun Date: Mon, 18 May 2026 04:52:18 +0200 Subject: [PATCH] feat(fase-13): server_admins + admin_actions audit log model MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Migration 024 introduces the orthogonal global role and the append-only audit log. server_admins is a separate table (not a column on users) so that promote/revoke don't require a JWT re-issue; is_server_admin() is a STABLE SECURITY DEFINER helper matching the shape of is_admin/is_member. admin_actions has only a SELECT policy (admin-only) — no INSERT/UPDATE/ DELETE policies, so only the SECURITY DEFINER RPCs in migration 025 can write to it. actor_id FK uses RESTRICT so the audit trail outlives admins. Bootstrap via infra/db-init/10-server-admin-seed.sh on first volume init (reads SERVER_ADMIN_EMAIL); supabase/seed.sql also pre-seeds Ana for dev/test because docker-entrypoint-initdb.d does not re-fire on long-lived dev volumes. Documented in .env.erosi.example. 20 new pgTAP assertions cover schema shape, RLS posture, FK behaviour, and the SECURITY DEFINER + STABLE attributes on is_server_admin(). Co-Authored-By: Claude Opus 4.7 --- .env.erosi.example | 16 +++ infra/db-init/10-server-admin-seed.sh | 70 +++++++++++ supabase/migrations/024_server_admin.sql | 95 +++++++++++++++ supabase/seed.sql | 15 +++ supabase/tests/016_server_admin.sql | 149 +++++++++++++++++++++++ 5 files changed, 345 insertions(+) create mode 100755 infra/db-init/10-server-admin-seed.sh create mode 100644 supabase/migrations/024_server_admin.sql create mode 100644 supabase/tests/016_server_admin.sql diff --git a/.env.erosi.example b/.env.erosi.example index 5fd12b2..47ceeee 100644 --- a/.env.erosi.example +++ b/.env.erosi.example @@ -40,3 +40,19 @@ SUPABASE_SERVICE_ROLE_KEY=CHANGEME-sign-with-above # DB_ENC_KEY: exactly 16 characters. SECRET_KEY_BASE: ≥ 64 characters. REALTIME_ENC_KEY=CHANGEME16charkey REALTIME_SECRET_KEY_BASE=CHANGEME-openssl-rand-base64-64-at-minimum-so-phoenix-is-happy + +# ── Server admin bootstrap (Fase 13) ──────────────────────────────────────── +# Email of the user who should be promoted to `server_admin` on first volume +# init. The bootstrap script (infra/db-init/10-server-admin-seed.sh) reads +# this and, if `public.server_admins` is empty AND a matching public.users row +# exists, inserts that user as the first admin. Idempotent — re-running with a +# different email after the first admin is created does NOTHING. +# +# IMPORTANT: this fires from `docker-entrypoint-initdb.d`, which only runs on +# a FRESH volume. On prod first deploy: +# 1. Spin up the stack (this will likely log "no user matches" — the user +# hasn't completed their first Keycloak login yet). +# 2. Have the operator sign in once via Keycloak so public.users picks them up. +# 3. Manually re-run: `docker compose exec -T db bash /docker-entrypoint-initdb.d/10-server-admin-seed.sh server-admin-seed: SERVER_ADMIN_EMAIL not set, skipping" + exit 0 +fi + +echo "==> server-admin-seed: looking up ${SERVER_ADMIN_EMAIL}…" + +# Bash expands ${SERVER_ADMIN_EMAIL} inside the unquoted heredoc tag below. +# The PL/pgSQL `$$ ... $$` dollar-quoting needs to be escaped (\$\$) so bash +# doesn't try to interpolate it. Same idea as 00-role-passwords.sh. +psql -v ON_ERROR_STOP=1 --username postgres --dbname postgres < 0 THEN + RAISE NOTICE 'server-admin-seed: server_admins already populated (% row(s)), skipping', v_existing; + RETURN; + END IF; + + SELECT id INTO v_user_id + FROM public.users + WHERE lower(email) = lower(v_email); + + IF v_user_id IS NULL THEN + RAISE WARNING 'server-admin-seed: no public.users row matches email %, skipping (re-run after first login)', v_email; + RETURN; + END IF; + + INSERT INTO public.server_admins (user_id) + VALUES (v_user_id) + ON CONFLICT (user_id) DO NOTHING; + + RAISE NOTICE 'server-admin-seed: promoted user % (email %)', v_user_id, v_email; + END + \$\$; +EOSQL + +echo "==> server-admin-seed: done" diff --git a/supabase/migrations/024_server_admin.sql b/supabase/migrations/024_server_admin.sql new file mode 100644 index 0000000..ffc727f --- /dev/null +++ b/supabase/migrations/024_server_admin.sql @@ -0,0 +1,95 @@ +-- Migration 024: server admin role + audit log (Fase 13.1) +-- +-- Introduces an orthogonal global role used by the operator-facing /admin area. +-- A `server_admin` is NOT a `collective_member` role — it's a separate gate +-- that lets one user delete/restore collectives, expel members, set default +-- section visibility, and inspect any colective on the instance. +-- +-- ── Design notes ──────────────────────────────────────────────────────────── +-- * We pick a table (`server_admins`) over a column on `users` because the +-- JWT doesn't need to carry the flag — `is_server_admin()` is a cheap STABLE +-- query and there's no way for an admin to silently keep the role after a +-- `revoke` if the bit lived inside the cached JWT. +-- * `admin_actions` is append-only at the policy level. Only SECURITY DEFINER +-- RPCs (migration 025) ever write to it, so we never declare INSERT/UPDATE/ +-- DELETE policies. SELECT is admin-only — even the actor cannot reach back +-- in via PostgREST and rewrite their own history without a superuser shell. +-- * `server_admins.user_id` cascades on user delete: when an admin hard-deletes +-- their own public.users row via the standard `delete_account()` flow, their +-- privilege evaporates. The 'last admin' guard lives in the RPC layer +-- (migration 025), not here — `delete_account()` is intentionally orthogonal. +-- * Bootstrap: see `infra/db-init/10-server-admin-seed.sh`. The seed reads +-- SERVER_ADMIN_EMAIL on FIRST volume init only. For dev (where the volume is +-- long-lived) we additionally seed Ana as admin via supabase/seed.sql. + +CREATE TABLE public.server_admins ( + user_id uuid PRIMARY KEY REFERENCES public.users(id) ON DELETE CASCADE, + granted_by uuid NULL REFERENCES public.users(id) ON DELETE SET NULL, + granted_at timestamptz NOT NULL DEFAULT now() +); + +ALTER TABLE public.server_admins ENABLE ROW LEVEL SECURITY; + +-- A user can always read their own row (so the client can compute +-- $isServerAdmin without escalation); other admins can read the full list. +-- No INSERT/UPDATE/DELETE policy — only SECURITY DEFINER RPCs touch this. +CREATE POLICY "select_self_or_admin" ON public.server_admins + FOR SELECT + USING ( + user_id = auth.uid() + OR EXISTS (SELECT 1 FROM public.server_admins WHERE user_id = auth.uid()) + ); + +-- ── is_server_admin() ─────────────────────────────────────────────────────── +-- The default-arg form lets RLS-style call-sites write `is_server_admin()` and +-- get `auth.uid()` for free, matching the shape of `is_admin()` / `is_member()` +-- from migration 003. +CREATE OR REPLACE FUNCTION public.is_server_admin(p_user uuid DEFAULT auth.uid()) +RETURNS boolean +LANGUAGE sql +STABLE +SECURITY DEFINER +SET search_path = public, auth +AS $$ + SELECT EXISTS ( + SELECT 1 FROM public.server_admins WHERE user_id = p_user + ); +$$; + +COMMENT ON FUNCTION public.is_server_admin(uuid) IS + 'Returns true if the given user (default auth.uid()) is a server admin.'; + +REVOKE ALL ON FUNCTION public.is_server_admin(uuid) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION public.is_server_admin(uuid) TO anon, authenticated; + +-- ── admin_actions ────────────────────────────────────────────────────────── +-- Append-only audit log. Every privileged RPC in migration 025 writes one +-- row before mutating state. `actor_id` is RESTRICT so the audit trail +-- never silently disappears when an admin's user row is removed — the FK +-- forces an explicit decision (delete the actions first, or transfer +-- ownership). Operationally the audit log is intended to outlive admins. + +CREATE TABLE public.admin_actions ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + actor_id uuid NOT NULL REFERENCES public.users(id) ON DELETE RESTRICT, + action text NOT NULL, + target_type text NOT NULL, + target_id uuid NULL, + payload jsonb NOT NULL DEFAULT '{}'::jsonb, + created_at timestamptz NOT NULL DEFAULT now() +); + +ALTER TABLE public.admin_actions ENABLE ROW LEVEL SECURITY; + +-- Only admins can read the log. No write policy: SECURITY DEFINER RPCs only. +CREATE POLICY "select_admin_only" ON public.admin_actions + FOR SELECT + USING (public.is_server_admin()); + +CREATE INDEX admin_actions_actor_idx ON public.admin_actions (actor_id, created_at DESC); +CREATE INDEX admin_actions_target_idx ON public.admin_actions (target_type, target_id); +CREATE INDEX admin_actions_created_idx ON public.admin_actions (created_at DESC); + +COMMENT ON TABLE public.admin_actions IS + 'Append-only audit log of every privileged RPC call. Written exclusively ' + 'by SECURITY DEFINER functions in migration 025.'; diff --git a/supabase/seed.sql b/supabase/seed.sql index b94c3c5..c00018c 100644 --- a/supabase/seed.sql +++ b/supabase/seed.sql @@ -129,3 +129,18 @@ BEGIN last_used_at = EXCLUDED.last_used_at; END IF; END $$; + +-- ── Fase 13 server admins ───────────────────────────────────────────────────── +-- In dev we promote Ana directly so the integration + e2e suites have a known +-- server admin without depending on `docker-entrypoint-initdb.d` (which only +-- fires on a fresh volume). On prod the same role is bootstrapped by +-- infra/db-init/10-server-admin-seed.sh reading SERVER_ADMIN_EMAIL. +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM information_schema.tables + WHERE table_schema = 'public' AND table_name = 'server_admins') THEN + INSERT INTO public.server_admins (user_id) + VALUES ('11111111-1111-1111-1111-111111111111') -- Ana + ON CONFLICT (user_id) DO NOTHING; + END IF; +END $$; diff --git a/supabase/tests/016_server_admin.sql b/supabase/tests/016_server_admin.sql new file mode 100644 index 0000000..06d6b78 --- /dev/null +++ b/supabase/tests/016_server_admin.sql @@ -0,0 +1,149 @@ +-- pgTAP: server admin role + audit log (Fase 13.1) +-- Run with: psql -U postgres -d postgres -f supabase/tests/016_server_admin.sql +-- +-- Verifies: +-- * `public.server_admins` table shape: PK, FKs, RLS enabled, no +-- INSERT/UPDATE/DELETE policies (only SELECT). +-- * `public.is_server_admin(uuid)` exists, STABLE, SECURITY DEFINER, +-- returns boolean, has a default arg. +-- * `public.admin_actions` table shape: append-only (SELECT policy only), +-- RLS enabled, indexes present, actor_id FK is RESTRICT. +-- +-- The runtime semantics (non-admin denied SELECT, audit RPCs only write via +-- SECURITY DEFINER) live in the Vitest integration suite which connects as a +-- non-superuser. pgTAP runs as postgres and bypasses RLS. + +CREATE EXTENSION IF NOT EXISTS pgtap; + +BEGIN; +SELECT plan(20); + +-- ── server_admins table shape ─────────────────────────────────────────────── + +SELECT has_table( + 'public', 'server_admins', + 'SA-T01: public.server_admins table exists' +); + +SELECT has_column( + 'public', 'server_admins', 'user_id', + 'SA-T02: server_admins.user_id column exists' +); + +SELECT col_is_pk( + 'public', 'server_admins', 'user_id', + 'SA-T03: server_admins.user_id is the primary key' +); + +SELECT col_not_null( + 'public', 'server_admins', 'granted_at', + 'SA-T04: server_admins.granted_at is NOT NULL' +); + +-- RLS enabled +SELECT ok( + (SELECT relrowsecurity FROM pg_class WHERE relname = 'server_admins' AND relnamespace = 'public'::regnamespace), + 'SA-T05: RLS is enabled on server_admins' +); + +-- Only a SELECT policy — no INSERT/UPDATE/DELETE policies. +SELECT results_eq( + $$ SELECT cmd::text FROM pg_policies + WHERE schemaname = 'public' AND tablename = 'server_admins' + ORDER BY cmd $$, + $$ VALUES ('SELECT') $$, + 'SA-T06: server_admins has exactly one policy and it is SELECT-only' +); + +-- ── is_server_admin function ──────────────────────────────────────────────── + +SELECT has_function( + 'public', 'is_server_admin', ARRAY['uuid'], + 'SA-T07: public.is_server_admin(uuid) exists' +); + +SELECT function_returns( + 'public', 'is_server_admin', ARRAY['uuid'], 'boolean', + 'SA-T08: is_server_admin() returns boolean' +); + +SELECT volatility_is( + 'public', 'is_server_admin', ARRAY['uuid'], 'stable', + 'SA-T09: is_server_admin() is STABLE' +); + +-- Must be SECURITY DEFINER so non-admin callers can answer "am I admin?" +-- without escalating to SELECT-all on server_admins. +SELECT is( + (SELECT prosecdef FROM pg_proc WHERE proname = 'is_server_admin' AND pronamespace = 'public'::regnamespace), + true, + 'SA-T10: is_server_admin() is SECURITY DEFINER' +); + +-- ── admin_actions table shape ─────────────────────────────────────────────── + +SELECT has_table( + 'public', 'admin_actions', + 'SA-T11: public.admin_actions table exists' +); + +SELECT col_is_pk( + 'public', 'admin_actions', 'id', + 'SA-T12: admin_actions.id is the primary key' +); + +SELECT col_not_null( + 'public', 'admin_actions', 'actor_id', + 'SA-T13: admin_actions.actor_id is NOT NULL' +); + +SELECT col_not_null( + 'public', 'admin_actions', 'action', + 'SA-T14: admin_actions.action is NOT NULL' +); + +SELECT col_type_is( + 'public', 'admin_actions', 'payload', 'jsonb', + 'SA-T15: admin_actions.payload is jsonb' +); + +-- RLS enabled +SELECT ok( + (SELECT relrowsecurity FROM pg_class WHERE relname = 'admin_actions' AND relnamespace = 'public'::regnamespace), + 'SA-T16: RLS is enabled on admin_actions' +); + +-- Append-only: SELECT is the ONLY policy. No INSERT/UPDATE/DELETE policies → +-- non-superuser cannot write to admin_actions via REST under any +-- circumstances. Only SECURITY DEFINER RPCs (migration 025) write. +SELECT results_eq( + $$ SELECT cmd::text FROM pg_policies + WHERE schemaname = 'public' AND tablename = 'admin_actions' + ORDER BY cmd $$, + $$ VALUES ('SELECT') $$, + 'SA-T17: admin_actions has exactly one policy and it is SELECT-only (append-only)' +); + +-- actor_id FK must RESTRICT so the audit trail never silently loses rows +-- when a user is deleted. +SELECT results_eq( + $$ SELECT confdeltype::text FROM pg_constraint + WHERE conrelid = 'public.admin_actions'::regclass + AND conname = 'admin_actions_actor_id_fkey' $$, + $$ VALUES ('r') $$, -- 'r' = RESTRICT + 'SA-T18: admin_actions.actor_id FK uses RESTRICT' +); + +-- Indexes for the common queries +SELECT has_index( + 'public', 'admin_actions', 'admin_actions_actor_idx', + 'SA-T19: admin_actions has (actor_id, created_at DESC) index' +); + +SELECT has_index( + 'public', 'admin_actions', 'admin_actions_target_idx', + 'SA-T20: admin_actions has (target_type, target_id) index' +); + +SELECT * FROM finish(); +ROLLBACK;