/** * SA-series: Server administration RPCs + audit log + server-layer * section visibility (Fase 13.5.1). * * SA-01 admin_list_collectives returns rows for an admin; rejected for a * non-admin user (P0001 'forbidden'). * SA-02 admin_soft_delete_collective writes an admin_actions row; the * collective is flipped to deleted_at IS NOT NULL. * SA-03 admin_restore_collective clears deleted_at + writes audit. * SA-04 admin_hard_delete_collective: blocked when deleted_at IS NULL OR * < 30 days old; allowed with p_force=true; cascade removes the * dependent rows (collective_members, shopping_lists, etc.) without * touching public.users. * SA-05 admin_remove_member kicks the user, writes audit. * SA-06 admin_set_default_section writes server_settings + audit. * SA-07 grant_server_admin / revoke_server_admin; last-admin guard fires. * SA-08 section_enabled() precedence: server > collective > user > default. * SA-09 non-admin cannot SELECT admin_actions (RLS). * SA-10 non-admin cannot SELECT server_admins beyond their own row (RLS). */ import { describe, it, expect, afterAll, beforeEach } from 'vitest'; import { createClientAs, createAdminClient } from '../src/supabase-clients.js'; import { sql, closePool } from '../src/db-helpers.js'; import { ANA_ID, BORJA_ID, CARMEN_ID, DAVID_ID, COLLECTIVE_ID } from '../src/seed-constants.js'; const admin = createAdminClient(); // Tracker so we can clean up anything we create. Ana is always the seed admin // (see supabase/seed.sql); Borja and others may be promoted in some tests and // must be demoted before the suite exits or other tests' assumptions break. const promotedNonSeed: string[] = []; const createdCollectiveIds: string[] = []; afterAll(async () => { // Demote anyone we promoted, leaving Ana as the only seed admin. if (promotedNonSeed.length) { await sql('DELETE FROM public.server_admins WHERE user_id = ANY($1::uuid[])', [ promotedNonSeed ]); } // Best-effort: drop any collectives we created. if (createdCollectiveIds.length) { await sql('DELETE FROM public.collectives WHERE id = ANY($1::uuid[])', [ createdCollectiveIds ]); } // Reset section flags + server settings. await sql(`UPDATE public.users SET feature_flags = '{}'::jsonb`); await sql(`UPDATE public.collectives SET feature_flags = '{}'::jsonb WHERE deleted_at IS NULL`); await sql(`UPDATE public.collectives SET deleted_at = NULL`); await sql(`UPDATE public.server_settings SET value = '{}'::jsonb WHERE key = 'default_sections'`); // Trim audit log to keep the dev DB tidy across re-runs. await sql(`DELETE FROM public.admin_actions WHERE actor_id = ANY($1::uuid[])`, [ [ANA_ID, BORJA_ID, CARMEN_ID] ]); await closePool(); }); beforeEach(async () => { // Always restore the seed admin to a clean state. await sql('INSERT INTO public.server_admins (user_id) VALUES ($1) ON CONFLICT DO NOTHING', [ ANA_ID ]); // Demote any non-seed admins between tests so SA-07 starts from "Ana only". if (promotedNonSeed.length) { await sql('DELETE FROM public.server_admins WHERE user_id = ANY($1::uuid[])', [ promotedNonSeed ]); promotedNonSeed.length = 0; } // Reset audit + settings so per-test row counts are deterministic. await sql(`UPDATE public.collectives SET deleted_at = NULL`); await sql(`UPDATE public.users SET feature_flags = '{}'::jsonb`); await sql(`UPDATE public.collectives SET feature_flags = '{}'::jsonb WHERE deleted_at IS NULL`); await sql(`UPDATE public.server_settings SET value = '{}'::jsonb WHERE key = 'default_sections'`); await sql(`DELETE FROM public.admin_actions`); }); async function makeThrowawayCollective(name: string, creator = ANA_ID): Promise { const r = await sql( `INSERT INTO public.collectives (name, emoji, created_by) VALUES ($1, '🧪', $2) RETURNING id`, [name, creator] ); const id = r.rows[0].id as string; createdCollectiveIds.push(id); await sql( `INSERT INTO public.collective_members (collective_id, user_id, role) VALUES ($1, $2, 'admin')`, [id, creator] ); return id; } describe('Server admin RPCs', () => { it('SA-01: admin_list_collectives returns rows for admin; forbidden for non-admin', async () => { const ana = await createClientAs(ANA_ID); const ok = await ana.rpc('admin_list_collectives', { p_search: null, p_limit: 50 }); expect(ok.error).toBeNull(); expect(Array.isArray(ok.data)).toBe(true); expect((ok.data ?? []).length).toBeGreaterThan(0); const borja = await createClientAs(BORJA_ID); const denied = await borja.rpc('admin_list_collectives', { p_search: null, p_limit: 50 }); expect(denied.error?.code).toBe('P0001'); expect(denied.error?.message).toMatch(/forbidden/i); }); it('SA-02: admin_soft_delete_collective sets deleted_at + writes audit', async () => { const cid = await makeThrowawayCollective('SA-02 throwaway'); const ana = await createClientAs(ANA_ID); const { error } = await ana.rpc('admin_soft_delete_collective', { p_collective_id: cid, p_reason: 'cleanup' }); expect(error).toBeNull(); const after = await sql('SELECT deleted_at FROM public.collectives WHERE id = $1', [cid]); expect(after.rows[0].deleted_at).not.toBeNull(); const audit = await sql( `SELECT action, target_id, payload FROM public.admin_actions WHERE action = 'soft_delete_collective' AND target_id = $1`, [cid] ); expect(audit.rows).toHaveLength(1); expect(audit.rows[0].payload.reason).toBe('cleanup'); }); it('SA-03: admin_restore_collective clears deleted_at + writes audit', async () => { const cid = await makeThrowawayCollective('SA-03 throwaway'); await sql('UPDATE public.collectives SET deleted_at = now() WHERE id = $1', [cid]); const ana = await createClientAs(ANA_ID); const { error } = await ana.rpc('admin_restore_collective', { p_collective_id: cid }); expect(error).toBeNull(); const after = await sql('SELECT deleted_at FROM public.collectives WHERE id = $1', [cid]); expect(after.rows[0].deleted_at).toBeNull(); const audit = await sql( `SELECT count(*)::int FROM public.admin_actions WHERE action = 'restore_collective' AND target_id = $1`, [cid] ); expect(audit.rows[0].count).toBe(1); }); it('SA-04: admin_hard_delete_collective is guarded by recency + cascade is non-destructive to users', async () => { const cid = await makeThrowawayCollective('SA-04 throwaway'); const ana = await createClientAs(ANA_ID); // Without soft-delete first: not_soft_deleted. const r1 = await ana.rpc('admin_hard_delete_collective', { p_collective_id: cid, p_force: false }); expect(r1.error?.message).toMatch(/not_soft_deleted/); // After a fresh soft-delete: too_recent. await sql('UPDATE public.collectives SET deleted_at = now() WHERE id = $1', [cid]); const r2 = await ana.rpc('admin_hard_delete_collective', { p_collective_id: cid, p_force: false }); expect(r2.error?.message).toMatch(/too_recent/); // Add some satellite rows that should cascade away cleanly. await sql( `INSERT INTO public.shopping_lists (collective_id, name, status, created_by) VALUES ($1, 'SA-04 list', 'active', $2) RETURNING id`, [cid, ANA_ID] ); // User row count snapshot — must be unchanged after hard delete. const usersBefore = await sql('SELECT count(*)::int FROM public.users'); // With force=true: succeeds. const r3 = await ana.rpc('admin_hard_delete_collective', { p_collective_id: cid, p_force: true }); expect(r3.error).toBeNull(); const gone = await sql('SELECT count(*)::int FROM public.collectives WHERE id = $1', [cid]); expect(gone.rows[0].count).toBe(0); const listsGone = await sql( 'SELECT count(*)::int FROM public.shopping_lists WHERE collective_id = $1', [cid] ); expect(listsGone.rows[0].count).toBe(0); const usersAfter = await sql('SELECT count(*)::int FROM public.users'); expect(usersAfter.rows[0].count).toBe(usersBefore.rows[0].count); const audit = await sql( `SELECT payload FROM public.admin_actions WHERE action = 'hard_delete_collective' AND target_id = $1`, [cid] ); expect(audit.rows).toHaveLength(1); expect(audit.rows[0].payload.force).toBe(true); expect(audit.rows[0].payload.name_snapshot).toBe('SA-04 throwaway'); }); it('SA-05: admin_remove_member removes the membership and writes audit', async () => { // Add Carmen to a throwaway collective so we can kick her without // disturbing the seed Casa García-López membership. const cid = await makeThrowawayCollective('SA-05 throwaway'); await sql( `INSERT INTO public.collective_members (collective_id, user_id, role) VALUES ($1, $2, 'member')`, [cid, CARMEN_ID] ); const ana = await createClientAs(ANA_ID); const { error } = await ana.rpc('admin_remove_member', { p_collective_id: cid, p_user: CARMEN_ID, p_reason: 'spam' }); expect(error).toBeNull(); const after = await sql( `SELECT count(*)::int FROM public.collective_members WHERE collective_id = $1 AND user_id = $2`, [cid, CARMEN_ID] ); expect(after.rows[0].count).toBe(0); const audit = await sql( `SELECT payload FROM public.admin_actions WHERE action = 'remove_member' AND target_id = $1`, [cid] ); expect(audit.rows).toHaveLength(1); expect(audit.rows[0].payload.user_id).toBe(CARMEN_ID); expect(audit.rows[0].payload.reason).toBe('spam'); }); it('SA-06: admin_set_default_section patches server_settings + writes audit; unknown section is rejected', async () => { const ana = await createClientAs(ANA_ID); const ok = await ana.rpc('admin_set_default_section', { p_section: 'notes', p_enabled: false }); expect(ok.error).toBeNull(); const row = await sql( `SELECT value FROM public.server_settings WHERE key = 'default_sections'` ); expect(row.rows[0].value.notes).toBe(false); const bad = await ana.rpc('admin_set_default_section', { p_section: 'definitely_not_a_section', p_enabled: true }); expect(bad.error?.message).toMatch(/unknown_section/); const audit = await sql( `SELECT count(*)::int FROM public.admin_actions WHERE action = 'set_default_section'` ); expect(audit.rows[0].count).toBe(1); }); it('SA-07: grant_server_admin + revoke_server_admin + last-admin guard', async () => { const ana = await createClientAs(ANA_ID); // Promote Borja. const promote = await ana.rpc('grant_server_admin', { p_user: BORJA_ID }); expect(promote.error).toBeNull(); promotedNonSeed.push(BORJA_ID); const after = await sql( 'SELECT count(*)::int FROM public.server_admins WHERE user_id = $1', [BORJA_ID] ); expect(after.rows[0].count).toBe(1); // Revoke Borja — succeeds (Ana still remains). const revoke = await ana.rpc('revoke_server_admin', { p_user: BORJA_ID }); expect(revoke.error).toBeNull(); // Pop because revoke removed it cleanly. promotedNonSeed.pop(); // Last-admin guard: Ana tries to revoke herself when she is the sole admin. const selfRevoke = await ana.rpc('revoke_server_admin', { p_user: ANA_ID }); expect(selfRevoke.error?.code).toBe('P0003'); expect(selfRevoke.error?.message).toMatch(/last_admin/); // Sanity: Ana still admin. const still = await sql( 'SELECT count(*)::int FROM public.server_admins WHERE user_id = $1', [ANA_ID] ); expect(still.rows[0].count).toBe(1); // Audit: 1 grant + 1 revoke. (The denied self-revoke should NOT have logged.) const audit = await sql( `SELECT action FROM public.admin_actions WHERE action IN ('grant_server_admin', 'revoke_server_admin') ORDER BY created_at` ); expect(audit.rows.map((r) => r.action)).toEqual([ 'grant_server_admin', 'revoke_server_admin' ]); }); it('SA-08: section_enabled precedence — server > collective > user > default', async () => { const borja = await createClientAs(BORJA_ID); // Layer 1: server ON → returns true regardless of lower layers being OFF. await sql( `UPDATE public.server_settings SET value = '{"tasks": true}'::jsonb WHERE key = 'default_sections'` ); await sql(`UPDATE public.collectives SET feature_flags = '{"tasks": false}'::jsonb WHERE id = $1`, [ COLLECTIVE_ID ]); await sql(`UPDATE public.users SET feature_flags = '{"tasks": false}'::jsonb WHERE id = $1`, [ BORJA_ID ]); const layer1 = await borja.rpc('section_enabled', { p_section: 'tasks', p_user: BORJA_ID, p_collective: COLLECTIVE_ID }); expect(layer1.error).toBeNull(); expect(layer1.data).toBe(true); // Layer 2: server absent → collective wins (OFF). await sql(`UPDATE public.server_settings SET value = '{}'::jsonb WHERE key = 'default_sections'`); const layer2 = await borja.rpc('section_enabled', { p_section: 'tasks', p_user: BORJA_ID, p_collective: COLLECTIVE_ID }); expect(layer2.data).toBe(false); // Layer 3: server + collective absent → user wins (OFF). await sql(`UPDATE public.collectives SET feature_flags = '{}'::jsonb WHERE id = $1`, [ COLLECTIVE_ID ]); const layer3 = await borja.rpc('section_enabled', { p_section: 'tasks', p_user: BORJA_ID, p_collective: COLLECTIVE_ID }); expect(layer3.data).toBe(false); // Layer 4: everyone absent → default true. await sql(`UPDATE public.users SET feature_flags = '{}'::jsonb WHERE id = $1`, [BORJA_ID]); const layer4 = await borja.rpc('section_enabled', { p_section: 'tasks', p_user: BORJA_ID, p_collective: COLLECTIVE_ID }); expect(layer4.data).toBe(true); }); it('SA-09: non-admin cannot SELECT admin_actions (RLS)', async () => { // Generate one audit row so there is something to maybe-leak. const cid = await makeThrowawayCollective('SA-09 throwaway'); const ana = await createClientAs(ANA_ID); await ana.rpc('admin_soft_delete_collective', { p_collective_id: cid, p_reason: 'sa-09' }); const borja = await createClientAs(BORJA_ID); const { data, error } = await borja .from('admin_actions') .select('id, action, target_id') .limit(10); expect(error).toBeNull(); // RLS returns empty, not an error expect(data ?? []).toHaveLength(0); // Sanity: Ana (admin) can SELECT. const { data: anaData } = await ana .from('admin_actions') .select('id, action') .eq('action', 'soft_delete_collective'); expect((anaData ?? []).length).toBeGreaterThan(0); }); it('SA-10: non-admin sees only their own row in server_admins', async () => { // Promote Carmen temporarily so server_admins has 2 rows. await sql('INSERT INTO public.server_admins (user_id) VALUES ($1) ON CONFLICT DO NOTHING', [ CARMEN_ID ]); promotedNonSeed.push(CARMEN_ID); // Borja (not an admin): sees nothing because no row matches user_id = auth.uid() // and the EXISTS branch (server admin) is false. const borja = await createClientAs(BORJA_ID); const { data: borjaRows } = await borja.from('server_admins').select('user_id'); expect(borjaRows ?? []).toHaveLength(0); // David (also not admin) likewise. const david = await createClientAs(DAVID_ID); const { data: davidRows } = await david.from('server_admins').select('user_id'); expect(davidRows ?? []).toHaveLength(0); // Carmen (admin via promotion): sees all rows. const carmen = await createClientAs(CARMEN_ID); const { data: carmenRows } = await carmen.from('server_admins').select('user_id'); expect((carmenRows ?? []).length).toBeGreaterThanOrEqual(2); }); });