Files
collective-lists/packages/test-utils/tests/rls-lists.test.ts
Oier Bravo Urtasun f396897cb5 test: full test suite (Vitest + pgTAP + Playwright) + TDD plan restructure
Add a 4-layer test stack covering RLS, triggers, and UI flows for Fases 0–2a,
then restructure every plan file so future fases start with tests and end with
a verification gate.

Test suite
- packages/test-utils: Vitest integration tests signing HS256 JWTs via jose so
  each test acts as a specific seed user (createClientAs + createAdminClient)
- supabase/tests: pgTAP for accept_invitation(), item_frequency trigger, and
  promote-on-admin-leave; each file self-installs pgtap extension
- apps/web/tests: Playwright E2E with live Keycloak login per test (storageState
  caching doesn't rehydrate Supabase's session state reliably)
- just test-all chains the three suites; test-db forwards POSTGRES_PASSWORD
  as PGPASSWORD with ON_ERROR_STOP=1 so failures abort the chain

Supabase auth gotcha
- PostgREST queries inside onAuthStateChange deadlock on GoTrue's navigator.locks
  auth lock (getAccessToken → getSession → initializePromise waits on the same
  lock that's held during event dispatch). Fix is two defenses: a pass-through
  lock in $lib/supabase, and a setTimeout(0) defer in root +layout.svelte to
  push loadUserCollectives out of the callback's microtask chain. Either alone
  is insufficient; both together unblock the Playwright suite.

Env key rotation
- apps/web/.env.development had a stale demo anon key signed with a different
  secret than root .env; Vite inlined that into the browser bundle so Kong (which
  uses the root .env value) rejected every request with 401. Aligned the two
  files and added a memory entry to flag this for the next rotation.

Plan restructure (TDD)
- Every fase now opens with X.0 Tests primero and closes with X.Z Verificación
  final. Completed fases (0, 1, 2a) show the pattern retroactively with the
  tests that currently cover them; pending fases (2b, 3, 4) list the tests to
  write before implementation.

Docs
- CLAUDE.md status line reports 54 + 12 + 15 = 81 green tests, adds gotchas
  #11 (auth-lock deadlock) and #12 (no storageState caching)
- README.md adds a TDD methodology section and the test-all command
- .gitignore excludes Playwright's generated reports and auth state

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 01:40:16 +02:00

238 lines
7.7 KiB
TypeScript

/**
* C-series: Shopping list RLS — create, read, soft-delete, restore, hard-delete.
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { createClientAs, createAdminClient } from '../src/supabase-clients.js';
import { sql, closePool } from '../src/db-helpers.js';
import { ANA_ID, BORJA_ID, DAVID_ID, EVA_ID, COLLECTIVE_ID, SEED_LIST_ID } from '../src/seed-constants.js';
const admin = createAdminClient();
const createdListIds: string[] = [];
afterAll(async () => {
// Hard-delete any lists created during tests (bypasses RLS)
if (createdListIds.length > 0) {
await admin.from('shopping_lists').delete().in('id', createdListIds);
}
await closePool();
});
describe('Shopping list read access', () => {
it('C-01: member (Borja) can read the seed list', async () => {
const borja = await createClientAs(BORJA_ID);
const { data, error } = await borja
.from('shopping_lists')
.select('id, name')
.eq('id', SEED_LIST_ID)
.single();
expect(error).toBeNull();
expect(data?.id).toBe(SEED_LIST_ID);
});
it('C-02: guest (David) can read the seed list', async () => {
const david = await createClientAs(DAVID_ID);
const { data, error } = await david
.from('shopping_lists')
.select('id')
.eq('id', SEED_LIST_ID)
.single();
expect(error).toBeNull();
expect(data?.id).toBe(SEED_LIST_ID);
});
it('C-03: Eva (non-member) sees no lists', async () => {
const eva = await createClientAs(EVA_ID);
const { data } = await eva.from('shopping_lists').select('id');
expect(data).toHaveLength(0);
});
});
describe('Shopping list create', () => {
it('C-04: member (Borja) can create a list', async () => {
const borja = await createClientAs(BORJA_ID);
const { data, error } = await borja
.from('shopping_lists')
.insert({ collective_id: COLLECTIVE_ID, name: 'Borja test list', created_by: BORJA_ID })
.select('id')
.single();
expect(error).toBeNull();
expect(data?.id).toBeTruthy();
if (data?.id) createdListIds.push(data.id);
});
it('C-05: guest (David) cannot create a list', async () => {
const david = await createClientAs(DAVID_ID);
const { data, error } = await david
.from('shopping_lists')
.insert({ collective_id: COLLECTIVE_ID, name: 'David sneaky list', created_by: DAVID_ID })
.select('id')
.single();
expect(data).toBeNull();
expect(error).not.toBeNull();
});
it('C-06: cannot spoof created_by to another user', async () => {
const borja = await createClientAs(BORJA_ID);
const { data, error } = await borja
.from('shopping_lists')
.insert({ collective_id: COLLECTIVE_ID, name: 'Spoofed list', created_by: ANA_ID })
.select('id')
.single();
expect(data).toBeNull();
expect(error).not.toBeNull();
});
});
describe('Shopping list soft-delete and trash window', () => {
let testListId: string;
beforeAll(async () => {
// Create a list via admin to avoid depending on prior test
const { data } = await admin
.from('shopping_lists')
.insert({ collective_id: COLLECTIVE_ID, name: 'Trash test list', created_by: ANA_ID })
.select('id')
.single();
testListId = data!.id;
createdListIds.push(testListId);
});
it('C-07: member (Borja) can soft-delete (set deleted_at) on a list', async () => {
const borja = await createClientAs(BORJA_ID);
const { error } = await borja
.from('shopping_lists')
.update({ deleted_at: new Date().toISOString() })
.eq('id', testListId);
expect(error).toBeNull();
const { data } = await admin.from('shopping_lists').select('deleted_at').eq('id', testListId).single();
expect(data?.deleted_at).not.toBeNull();
});
it('C-08: soft-deleted list is still visible within the 7-day window', async () => {
const borja = await createClientAs(BORJA_ID);
const { data, error } = await borja
.from('shopping_lists')
.select('id, deleted_at')
.eq('id', testListId)
.single();
expect(error).toBeNull();
expect(data?.id).toBe(testListId);
expect(data?.deleted_at).not.toBeNull();
});
it('C-09: soft-deleted list older than 7 days is not visible', async () => {
// Force deleted_at to 8 days ago via direct SQL
await sql(
`UPDATE public.shopping_lists SET deleted_at = now() - INTERVAL '8 days' WHERE id = $1`,
[testListId]
);
const borja = await createClientAs(BORJA_ID);
const { data, error } = await borja
.from('shopping_lists')
.select('id')
.eq('id', testListId);
expect(error).toBeNull();
expect(data).toHaveLength(0);
// Restore deleted_at so afterAll cleanup can hard-delete it
await sql(`UPDATE public.shopping_lists SET deleted_at = now() WHERE id = $1`, [testListId]);
});
it('C-10: member can restore a list (set deleted_at = null)', async () => {
const borja = await createClientAs(BORJA_ID);
const { error } = await borja
.from('shopping_lists')
.update({ deleted_at: null })
.eq('id', testListId);
expect(error).toBeNull();
const { data } = await admin.from('shopping_lists').select('deleted_at').eq('id', testListId).single();
expect(data?.deleted_at).toBeNull();
});
it('C-11: guest (David) cannot permanently delete a list', async () => {
// Soft-delete first via admin
await admin
.from('shopping_lists')
.update({ deleted_at: new Date().toISOString() })
.eq('id', testListId);
const david = await createClientAs(DAVID_ID);
const { error } = await david.from('shopping_lists').delete().eq('id', testListId);
// PostgREST returns 204 with 0 rows when RLS blocks — verify row still exists
const { data } = await admin.from('shopping_lists').select('id').eq('id', testListId).single();
expect(data?.id).toBe(testListId);
});
it('C-12: member (Borja) can permanently hard-delete a soft-deleted list', async () => {
// Ensure it's soft-deleted
await admin
.from('shopping_lists')
.update({ deleted_at: new Date().toISOString() })
.eq('id', testListId);
const borja = await createClientAs(BORJA_ID);
const { error } = await borja
.from('shopping_lists')
.delete()
.eq('id', testListId);
expect(error).toBeNull();
const { data } = await admin.from('shopping_lists').select('id').eq('id', testListId);
expect(data).toHaveLength(0);
// Remove from createdListIds since it's already gone
const idx = createdListIds.indexOf(testListId);
if (idx !== -1) createdListIds.splice(idx, 1);
});
});
describe('Cross-collective isolation', () => {
let otherCollectiveId: string;
let otherListId: string;
beforeAll(async () => {
// Eva creates her own collective and list (Eva is allowed to create collectives)
const { data: collective } = await admin
.from('collectives')
.insert({ name: 'Eva collective', emoji: '🐱', created_by: EVA_ID })
.select('id')
.single();
otherCollectiveId = collective!.id;
await admin
.from('collective_members')
.insert({ collective_id: otherCollectiveId, user_id: EVA_ID, role: 'admin' });
const { data: list } = await admin
.from('shopping_lists')
.insert({ collective_id: otherCollectiveId, name: 'Eva private list', created_by: EVA_ID })
.select('id')
.single();
otherListId = list!.id;
});
afterAll(async () => {
// Cascade delete removes members + lists
if (otherCollectiveId) {
await admin.from('collectives').delete().eq('id', otherCollectiveId);
}
});
it('C-13: Borja (member of main collective) cannot see Eva\'s list', async () => {
const borja = await createClientAs(BORJA_ID);
const { data } = await borja
.from('shopping_lists')
.select('id')
.eq('id', otherListId);
expect(data).toHaveLength(0);
});
it('C-14: Ana (admin of main collective) cannot see Eva\'s list', async () => {
const ana = await createClientAs(ANA_ID);
const { data } = await ana
.from('shopping_lists')
.select('id')
.eq('id', otherListId);
expect(data).toHaveLength(0);
});
});