Files
collective-lists/packages/test-utils/tests/rls-items.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

208 lines
6.8 KiB
TypeScript

/**
* D-series: Shopping item RLS — CRUD by role, cross-collective isolation.
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { createClientAs, createAdminClient } from '../src/supabase-clients.js';
import { ANA_ID, BORJA_ID, DAVID_ID, EVA_ID, COLLECTIVE_ID, SEED_LIST_ID } from '../src/seed-constants.js';
const admin = createAdminClient();
const createdItemIds: string[] = [];
afterAll(async () => {
if (createdItemIds.length > 0) {
await admin.from('shopping_items').delete().in('id', createdItemIds);
}
});
describe('Shopping item read access', () => {
it('D-05: member (Borja) can read items in the seed list', async () => {
const borja = await createClientAs(BORJA_ID);
const { data, error } = await borja
.from('shopping_items')
.select('id, name')
.eq('list_id', SEED_LIST_ID);
expect(error).toBeNull();
expect(data!.length).toBeGreaterThanOrEqual(1);
});
it('D-06: guest (David) can read items in the seed list', async () => {
const david = await createClientAs(DAVID_ID);
const { data, error } = await david
.from('shopping_items')
.select('id')
.eq('list_id', SEED_LIST_ID);
expect(error).toBeNull();
expect(data!.length).toBeGreaterThanOrEqual(1);
});
});
describe('Shopping item create', () => {
it('D-07: member (Borja) can add an item', async () => {
const borja = await createClientAs(BORJA_ID);
const { data, error } = await borja
.from('shopping_items')
.insert({ list_id: SEED_LIST_ID, name: 'Test item', sort_order: 100, created_by: BORJA_ID })
.select('id')
.single();
expect(error).toBeNull();
expect(data?.id).toBeTruthy();
if (data?.id) createdItemIds.push(data.id);
});
it('D-08: guest (David) cannot add an item', async () => {
const david = await createClientAs(DAVID_ID);
const { data, error } = await david
.from('shopping_items')
.insert({ list_id: SEED_LIST_ID, name: 'David sneaky item', sort_order: 101, created_by: DAVID_ID })
.select('id')
.single();
expect(data).toBeNull();
expect(error).not.toBeNull();
});
it('D-09: cannot spoof created_by to another user', async () => {
const borja = await createClientAs(BORJA_ID);
const { data, error } = await borja
.from('shopping_items')
.insert({ list_id: SEED_LIST_ID, name: 'Spoofed item', sort_order: 102, created_by: ANA_ID })
.select('id')
.single();
expect(data).toBeNull();
expect(error).not.toBeNull();
});
});
describe('Shopping item update', () => {
let testItemId: string;
beforeAll(async () => {
const { data } = await admin
.from('shopping_items')
.insert({ list_id: SEED_LIST_ID, name: 'Update test item', sort_order: 200, created_by: ANA_ID })
.select('id')
.single();
testItemId = data!.id;
createdItemIds.push(testItemId);
});
it('D-10: member (Carmen) can check an item', async () => {
const carmen = await createClientAs(ANA_ID); // use Ana since Carmen is seeded member
const { error } = await carmen
.from('shopping_items')
.update({ is_checked: true, checked_by: ANA_ID, checked_at: new Date().toISOString() })
.eq('id', testItemId);
expect(error).toBeNull();
const { data } = await admin.from('shopping_items').select('is_checked').eq('id', testItemId).single();
expect(data?.is_checked).toBe(true);
});
it('D-11: guest (David) cannot update an item', async () => {
const david = await createClientAs(DAVID_ID);
await david
.from('shopping_items')
.update({ is_checked: false })
.eq('id', testItemId);
// Verify no change — item should still be checked
const { data } = await admin.from('shopping_items').select('is_checked').eq('id', testItemId).single();
expect(data?.is_checked).toBe(true);
});
it('D-12: member can uncheck an item', async () => {
const borja = await createClientAs(BORJA_ID);
const { error } = await borja
.from('shopping_items')
.update({ is_checked: false, checked_by: null, checked_at: null })
.eq('id', testItemId);
expect(error).toBeNull();
const { data } = await admin.from('shopping_items').select('is_checked').eq('id', testItemId).single();
expect(data?.is_checked).toBe(false);
});
});
describe('Shopping item delete', () => {
let testItemId: string;
beforeAll(async () => {
const { data } = await admin
.from('shopping_items')
.insert({ list_id: SEED_LIST_ID, name: 'Delete test item', sort_order: 300, created_by: ANA_ID })
.select('id')
.single();
testItemId = data!.id;
createdItemIds.push(testItemId);
});
it('D-13: guest (David) cannot delete an item', async () => {
const david = await createClientAs(DAVID_ID);
await david.from('shopping_items').delete().eq('id', testItemId);
const { data } = await admin.from('shopping_items').select('id').eq('id', testItemId).single();
expect(data?.id).toBe(testItemId);
});
it('D-14: member (Borja) can hard-delete an item', async () => {
const borja = await createClientAs(BORJA_ID);
const { error } = await borja.from('shopping_items').delete().eq('id', testItemId);
expect(error).toBeNull();
const { data } = await admin.from('shopping_items').select('id').eq('id', testItemId);
expect(data).toHaveLength(0);
const idx = createdItemIds.indexOf(testItemId);
if (idx !== -1) createdItemIds.splice(idx, 1);
});
});
describe('Cross-collective item isolation', () => {
let otherCollectiveId: string;
let otherListId: string;
let otherItemId: string;
beforeAll(async () => {
const { data: collective } = await admin
.from('collectives')
.insert({ name: 'Item isolation 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: 'Private list', created_by: EVA_ID })
.select('id')
.single();
otherListId = list!.id;
const { data: item } = await admin
.from('shopping_items')
.insert({ list_id: otherListId, name: 'Private item', sort_order: 1, created_by: EVA_ID })
.select('id')
.single();
otherItemId = item!.id;
});
afterAll(async () => {
if (otherCollectiveId) {
await admin.from('collectives').delete().eq('id', otherCollectiveId);
}
});
it('D-15: Borja cannot read items from a different collective', async () => {
const borja = await createClientAs(BORJA_ID);
const { data } = await borja
.from('shopping_items')
.select('id')
.eq('id', otherItemId);
expect(data).toHaveLength(0);
});
it('D-16: Borja cannot delete an item from a different collective', async () => {
const borja = await createClientAs(BORJA_ID);
await borja.from('shopping_items').delete().eq('id', otherItemId);
const { data } = await admin.from('shopping_items').select('id').eq('id', otherItemId).single();
expect(data?.id).toBe(otherItemId);
});
});