Files
collective-lists/supabase/migrations/024_server_admin.sql
Oier Bravo Urtasun 7556d77bf8 feat(fase-13): admin RPCs + server_settings + section_enabled server layer
Migration 025 adds:
  - collectives.deleted_at column for soft delete (app-level visibility;
    RLS does NOT enforce soft-delete invisibility — admin area surfaces
    everything by design).
  - server_settings(key text pk, value jsonb) — generic admin-write bag
    seeded with an empty 'default_sections' row.
  - section_enabled() extended with the server layer as the topmost
    coalesce branch. Final precedence: server > collective > user > true.
  - Privileged RPCs: grant_/revoke_server_admin (last-admin guard fires
    P0003), admin_list_collectives, admin_soft_delete_collective,
    admin_restore_collective, admin_hard_delete_collective (30-day or
    p_force=true), admin_remove_member, admin_set_default_section
    (rejects unknown sections via known_sections() lookup).
  - _log_admin_action(): private helper centralising the
    audit INSERT, called by every privileged RPC BEFORE the mutation.

Migration 024 RLS policy on server_admins rewritten to delegate the
admin branch to is_server_admin() (SECURITY DEFINER, bypasses RLS) —
the original inline EXISTS hit infinite recursion (caught empirically
with `SET ROLE authenticated`).

22 new pgTAP assertions cover schema shape, RPC signatures, the
SECURITY DEFINER posture of every admin function, the new deleted_at
column, and the server-layer precedence semantics for section_enabled.

10 new Vitest integration tests (SA-01..SA-10) cover:
  - admin_list_collectives gated for non-admins (P0001 'forbidden').
  - soft / restore / hard delete audit + state transitions.
  - hard-delete recency guard (not_soft_deleted, too_recent, force).
  - hard-delete cascade is non-destructive to public.users.
  - remove_member writes role_was + reason to audit payload.
  - set_default_section rejects unknown sections; patches JSONB
    without clobbering siblings.
  - grant/revoke with last-admin guard (revoking the sole admin
    raises P0003 'last_admin'; failed call does NOT write audit).
  - section_enabled precedence walked layer by layer in one client.
  - RLS: non-admin sees zero rows in admin_actions + server_admins.

packages/types/src/database.ts hand-extended with the new tables and
RPC signatures; collectives Row/Insert/Update get deleted_at.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 05:01:19 +02:00

104 lines
5.4 KiB
PL/PgSQL

-- 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;
-- ── is_server_admin() ───────────────────────────────────────────────────────
-- Declared BEFORE the RLS policy so the policy can call it. The function is
-- SECURITY DEFINER → it bypasses RLS on `server_admins`, which is the only way
-- to break the otherwise-recursive policy ("you can see rows if you ARE in
-- this table" → the inner SELECT triggers the same policy → infinite
-- recursion, observed empirically before this rewrite).
--
-- 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;
-- A user can always read their own row (so the client can compute
-- $isServerAdmin without escalation); other admins can read the full list.
-- The admin branch uses is_server_admin() — NOT an inline EXISTS — to bypass
-- the otherwise-recursive RLS evaluation (see function comment above).
-- 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 public.is_server_admin()
);
-- ── 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.';