From 4adbfcb6086c34485862b56b25a9cc3a8e08eeab Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 25 Oct 2026 21:09:45 +0100 Subject: [PATCH] feat(supabase): clients M2 with RPCs, search and per-workspace budget MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit V1-1.2 (contract V1-1_OWNERS_ANIMALS.md §5, §9, §10). public.clients (person or organization, display name only, optional contact, folded search keys), create/update/set_archived as definer RPCs (identical not_found, idempotent create with divergent-replay refusal, revisions, archive read-only), search_clients invoker with keyset pages and phone search, write budget per workspace in UTC hour/day windows under a row lock, 20 000-client cap, ids-only audit hidden from platform staff (N9), nothing for anon or service_role. pgTAP 013 (130), field-limits parity test, sandbox suite (concurrency, budget races, 20 000-client search), types regenerated. --- packages/supabase/src/database.types.ts | 136 +++++ packages/supabase/src/field-limits.ts | 45 ++ .../supabase/tests/db/field-limits.test.ts | 170 ++++++ packages/supabase/tests/db/harness.ts | 4 +- .../supabase/tests/db/schema-types.test.ts | 57 ++ .../supabase/tests/sandbox/clients.sandbox.ts | 538 ++++++++++++++++++ .../migrations/20261025110000_clients.sql | 514 +++++++++++++++++ supabase/tests/001_schema.sql | 2 +- supabase/tests/013_clients.sql | 452 +++++++++++++++ 9 files changed, 1916 insertions(+), 2 deletions(-) create mode 100644 packages/supabase/src/field-limits.ts create mode 100644 packages/supabase/tests/db/field-limits.test.ts create mode 100644 packages/supabase/tests/sandbox/clients.sandbox.ts create mode 100644 supabase/migrations/20261025110000_clients.sql create mode 100644 supabase/tests/013_clients.sql diff --git a/packages/supabase/src/database.types.ts b/packages/supabase/src/database.types.ts index 37fab90b..42db1288 100644 --- a/packages/supabase/src/database.types.ts +++ b/packages/supabase/src/database.types.ts @@ -308,6 +308,84 @@ export type Database = { }, ] } + clients: { + Row: { + address_line1: string | null + address_line2: string | null + archived_at: string | null + city: string | null + country: string | null + create_request_digest: string + create_request_id: string + created_at: string + display_name: string + email: string | null + id: string + kind: Database['public']['Enums']['client_kind'] + name_key: string | null + phone: string | null + phone_digits: string | null + postal_code: string | null + revision: number + search_key: string | null + updated_at: string + workspace_id: string + } + ComputedFields: never + Insert: { + address_line1?: string | null + address_line2?: string | null + archived_at?: string | null + city?: string | null + country?: string | null + create_request_digest: string + create_request_id: string + created_at?: string + display_name: string + email?: string | null + id?: string + kind: Database['public']['Enums']['client_kind'] + name_key?: never + phone?: string | null + phone_digits?: never + postal_code?: string | null + revision?: number + search_key?: never + updated_at?: string + workspace_id: string + } + Update: { + address_line1?: string | null + address_line2?: string | null + archived_at?: string | null + city?: string | null + country?: string | null + create_request_digest?: string + create_request_id?: string + created_at?: string + display_name?: string + email?: string | null + id?: string + kind?: Database['public']['Enums']['client_kind'] + name_key?: never + phone?: string | null + phone_digits?: never + postal_code?: string | null + revision?: number + search_key?: never + updated_at?: string + workspace_id?: string + } + Relationships: [ + { + foreignKeyName: 'clients_workspace_id_fkey' + columns: ['workspace_id'] + isOneToOne: false + referencedRelation: 'workspaces' + referencedColumns: ['id'] + }, + ] + } profile_roles: { Row: { granted_at: string @@ -576,6 +654,22 @@ export type Database = { } Returns: string } + create_client: { + Args: { + address_line1?: string + address_line2?: string + city?: string + country?: string + create_request_id: string + display_name: string + email?: string + kind: string + phone?: string + postal_code?: string + workspace_id: string + } + Returns: Json + } create_sheet_draft: { Args: { change_note?: string @@ -636,6 +730,30 @@ export type Database = { } Returns: string } + search_clients: { + Args: { + after_id?: string + after_name_key?: string + archived?: boolean + page_size?: number + query?: string + workspace_id: string + } + Returns: { + archived_at: string + city: string + display_name: string + email: string + id: string + kind: Database['public']['Enums']['client_kind'] + name_key: string + phone: string + }[] + } + set_client_archived: { + Args: { archived: boolean; client_id: string } + Returns: Json + } set_sheet_visibility: { Args: { sheet_id: string @@ -643,6 +761,22 @@ export type Database = { } Returns: string } + update_client: { + Args: { + address_line1: string + address_line2: string + city: string + client_id: string + country: string + display_name: string + email: string + expected_revision: number + kind: string + phone: string + postal_code: string + } + Returns: Json + } } Enums: { asset_status: @@ -651,6 +785,7 @@ export type Database = { | 'clean' | 'rejected' | 'deleted' + client_kind: 'person' | 'organization' platform_role: 'owner' | 'admin' | 'moderator' | 'support' sheet_status: 'active' | 'archived' | 'deleted' sheet_version_status: 'draft' | 'published' | 'deprecated' @@ -791,6 +926,7 @@ export const Constants = { 'rejected', 'deleted', ], + client_kind: ['person', 'organization'], platform_role: ['owner', 'admin', 'moderator', 'support'], sheet_status: ['active', 'archived', 'deleted'], sheet_version_status: ['draft', 'published', 'deprecated'], diff --git a/packages/supabase/src/field-limits.ts b/packages/supabase/src/field-limits.ts new file mode 100644 index 00000000..1ce77e1d --- /dev/null +++ b/packages/supabase/src/field-limits.ts @@ -0,0 +1,45 @@ +/** + * Bounds and patterns of the V1-1 record fields, shared by the forms (Zod + * schemas, D-R7) and proven equal to the SQL CHECK constraints by + * tests/db/field-limits.test.ts (behaviour on the migrated schema, never by + * parsing SQL). Contract: docs/development/V1-1_OWNERS_ANIMALS.md §5, §12.2. + * + * Lengths count code points, as PostgreSQL's char_length does: use + * codePointLength, never String.length (UTF-16 units) or Zod's .max() alone. + */ + +export const CLIENT_FIELD_LIMITS = { + displayName: 120, + email: 254, + addressLine: 120, + postalCode: 16, + city: 80, +} as const + +/** U+0000 to U+001F, U+007F to U+009F, U+2028, U+2029 (the SQL literal starts at U+0001: text cannot hold U+0000). */ +export const CONTROL_CHARACTERS = /[\u0000-\u001F\u007F-\u009F\u2028\u2029]/u + +/** Applied to the lower-cased value. JavaScript's \s is wider than SQL's, so the form refuses at least what SQL refuses. */ +export const EMAIL_PATTERN = /^[^@\s]+@[^@\s]+\.[^@\s]+$/u + +export const PHONE_E164_PATTERN = /^\+[1-9][0-9]{6,14}$/ + +export const COUNTRY_CODE_PATTERN = /^[A-Z]{2}$/ + +export function codePointLength(value: string): number { + return [...value].length +} + +/** + * The text rule of contract §5: 1 to max code points, no leading or trailing + * space (U+0020, as SQL btrim checks), no control character. + */ +export function isCleanText(value: string, max: number): boolean { + const length = codePointLength(value) + return ( + length >= 1 && + length <= max && + value === value.replace(/^ +| +$/g, '') && + !CONTROL_CHARACTERS.test(value) + ) +} diff --git a/packages/supabase/tests/db/field-limits.test.ts b/packages/supabase/tests/db/field-limits.test.ts new file mode 100644 index 00000000..b0fb0db6 --- /dev/null +++ b/packages/supabase/tests/db/field-limits.test.ts @@ -0,0 +1,170 @@ +/** + * D-R7 parity: the constants of src/field-limits.ts behave like the SQL CHECK + * constraints of public.clients, proven by inserting values at and past each + * bound into the migrated PGlite schema (contract §12.2). The form may refuse + * more than SQL (never less): a value the TypeScript rule accepts must be + * accepted by SQL, and the listed samples must agree both ways. + */ +import type { PGlite } from '@electric-sql/pglite' +import { + CLIENT_FIELD_LIMITS, + COUNTRY_CODE_PATTERN, + EMAIL_PATTERN, + PHONE_E164_PATTERN, + codePointLength, + isCleanText, +} from '../../src/field-limits' +import { createMigratedDatabase } from './harness' + +type Column = + | 'display_name' + | 'email' + | 'phone' + | 'address_line1' + | 'postal_code' + | 'city' + | 'country' + +let db: PGlite +let workspaceId: string + +async function sqlAccepts(column: Column, value: string): Promise { + const name = column === 'display_name' ? value : 'Parity' + const extra = column === 'display_name' ? '' : `, ${column}` + await db.exec('begin') + try { + await db.query( + `insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest${extra}) + values ($1, 'person', $2, gen_random_uuid(), '\\x00'${column === 'display_name' ? '' : ', $3'})`, + column === 'display_name' + ? [workspaceId, name] + : [workspaceId, name, value], + ) + return true + } catch { + return false + } finally { + await db.exec('rollback') + } +} + +const textSamples = (max: number): string[] => [ + 'a'.repeat(max), + 'a'.repeat(max + 1), + 'é'.repeat(max), + 'é'.repeat(max + 1), + '𝄞'.repeat(max), + '𝄞'.repeat(max + 1), + '', + ' a', + 'a ', + 'a\tb', + 'a\u007Fb', + 'a\u0085b', + 'a\u2028b', + 'a\u2029b', + '\u00A0a', +] + +const textFields: [Column, number][] = [ + ['display_name', CLIENT_FIELD_LIMITS.displayName], + ['address_line1', CLIENT_FIELD_LIMITS.addressLine], + ['postal_code', CLIENT_FIELD_LIMITS.postalCode], + ['city', CLIENT_FIELD_LIMITS.city], +] + +const tsEmail = (v: string) => + isCleanText(v, CLIENT_FIELD_LIMITS.email) && + v === v.toLowerCase() && + EMAIL_PATTERN.test(v) +const emailSamples = [ + 'a@b.co', + 'A@b.co', + 'a b@c.de', + 'a@b', + '@b.co', + 'a@@b.co', + 'a'.repeat(246) + '@ex.test', + 'a'.repeat(247) + '@ex.test', + 'é@exemple.fr', +] +/** JavaScript's \s covers U+00A0, PostgreSQL's does not: the form refuses, SQL would accept. */ +const emailTsStricter = ['a\u00A0b@c.de'] + +describe('field limits match the SQL constraints (D-R7)', () => { + beforeAll(async () => { + db = await createMigratedDatabase() + await db.exec(`insert into auth.users (id, email, email_confirmed_at) + values ('7a000000-0000-0000-0000-000000000001', 'parity@test.local', now())`) + const { rows } = await db.query<{ id: string }>( + `select id from public.workspaces where personal_user_id = '7a000000-0000-0000-0000-000000000001'`, + ) + workspaceId = rows[0].id + }) + + afterAll(async () => { + await db?.close() + }) + + it('counts code points like char_length', () => { + expect(codePointLength('𝄞é')).toBe(2) + expect('𝄞é'.length).toBe(3) + }) + + it.each(textFields)( + '%s: the text rule and its bound %i agree', + async (column, max) => { + for (const value of textSamples(max)) { + expect([ + column, + JSON.stringify(value).slice(0, 24), + await sqlAccepts(column, value), + ]).toEqual([ + column, + JSON.stringify(value).slice(0, 24), + isCleanText(value, max), + ]) + } + }, + ) + + it('email: bound, lower case and pattern agree', async () => { + for (const value of emailSamples) { + expect([value.slice(0, 24), await sqlAccepts('email', value)]).toEqual([ + value.slice(0, 24), + tsEmail(value), + ]) + } + for (const value of emailTsStricter) { + expect(tsEmail(value)).toBe(false) + } + }) + + it('phone: E.164 agrees', async () => { + const samples = [ + '+33612345678', + '+1234567', + '+123456', + '+123456789012345', + '+1234567890123456', + '0612345678', + '+0612345678', + '+33 612345678', + ] + for (const value of samples) { + expect([value, await sqlAccepts('phone', value)]).toEqual([ + value, + PHONE_E164_PATTERN.test(value), + ]) + } + }) + + it('country: ISO alpha-2 upper case agrees', async () => { + for (const value of ['FR', 'fr', 'FRA', 'F1', 'F']) { + expect([value, await sqlAccepts('country', value)]).toEqual([ + value, + COUNTRY_CODE_PATTERN.test(value), + ]) + } + }) +}) diff --git a/packages/supabase/tests/db/harness.ts b/packages/supabase/tests/db/harness.ts index 228a6540..80006b5e 100644 --- a/packages/supabase/tests/db/harness.ts +++ b/packages/supabase/tests/db/harness.ts @@ -11,6 +11,7 @@ import { resolve, join } from 'node:path' import { fileURLToPath } from 'node:url' import { PGlite } from '@electric-sql/pglite' import { pgtap } from '@electric-sql/pglite/pgtap' +import { unaccent } from '@electric-sql/pglite/contrib/unaccent' const here = fileURLToPath(new URL('.', import.meta.url)) export const repoRoot = resolve(here, '../../../..') @@ -41,7 +42,8 @@ export async function listSeeds(): Promise { /** Boots PGlite, installs the shim and applies all migrations. */ export async function createMigratedDatabase(): Promise { - const db = await PGlite.create({ extensions: { pgtap } }) + // unaccent: created by the clients migration (search keys), as on the real image. + const db = await PGlite.create({ extensions: { pgtap, unaccent } }) await db.exec(await readFile(join(here, 'supabase-shim.sql'), 'utf8')) // Same placement as `supabase test db`: pgTAP lives in extensions, out of public. await db.exec('create extension if not exists pgtap with schema extensions;') diff --git a/packages/supabase/tests/db/schema-types.test.ts b/packages/supabase/tests/db/schema-types.test.ts index 36aa8f45..287a82af 100644 --- a/packages/supabase/tests/db/schema-types.test.ts +++ b/packages/supabase/tests/db/schema-types.test.ts @@ -85,6 +85,28 @@ const expectedColumns = { 'status', 'updated_at', ], + clients: [ + 'address_line1', + 'address_line2', + 'archived_at', + 'city', + 'country', + 'create_request_digest', + 'create_request_id', + 'created_at', + 'display_name', + 'email', + 'id', + 'kind', + 'name_key', + 'phone', + 'phone_digits', + 'postal_code', + 'revision', + 'search_key', + 'updated_at', + 'workspace_id', + ], profile_roles: [ 'granted_at', 'granted_by', @@ -139,6 +161,19 @@ const expectedFunctionArgs = { complete_avatar_job: ['asset_id', 'byte_size', 'lock_token', 'sha256'], confirm_asset_upload: ['asset_id'], confirm_sheet_asset_upload: ['asset_id'], + create_client: [ + 'address_line1', + 'address_line2', + 'city', + 'country', + 'create_request_id', + 'display_name', + 'email', + 'kind', + 'phone', + 'postal_code', + 'workspace_id', + ], create_anatomical_sheet: [ 'description', 'document', @@ -163,7 +198,29 @@ const expectedFunctionArgs = { remove_avatar: [], restore_anatomical_sheet: ['sheet_id'], revoke_platform_role: ['reason', 'role', 'target_user_id'], + search_clients: [ + 'after_id', + 'after_name_key', + 'archived', + 'page_size', + 'query', + 'workspace_id', + ], + set_client_archived: ['archived', 'client_id'], set_sheet_visibility: ['sheet_id', 'visibility'], + update_client: [ + 'address_line1', + 'address_line2', + 'city', + 'client_id', + 'country', + 'display_name', + 'email', + 'expected_revision', + 'kind', + 'phone', + 'postal_code', + ], } as const satisfies FunctionArgs // A function without arguments is generated as `Record` diff --git a/packages/supabase/tests/sandbox/clients.sandbox.ts b/packages/supabase/tests/sandbox/clients.sandbox.ts new file mode 100644 index 00000000..c1a35d18 --- /dev/null +++ b/packages/supabase/tests/sandbox/clients.sandbox.ts @@ -0,0 +1,538 @@ +/** + * V1-1.2 clients (M2) on the real stack of `pnpm db:sandbox`: RPCs through + * PostgREST with real sessions per role, identical refusals, search without + * leaks, then concurrent writes (creates, replays, revisions, archive races, + * budget at its limit, lock contention) and the search time on 20 000 clients. + * Contract: docs/development/V1-1_OWNERS_ANIMALS.md §9, §10, §12. + */ +import { randomUUID } from 'node:crypto' +import { + confirmedAccount, + errorCode, + rest, + rpc, + sql, + stack, + type Account, + type RestResult, +} from './stack' + +const workspaceOf = (userId: string) => + sql(`select id from public.workspaces where personal_user_id = '${userId}'`) +const budgetOf = (ws: string) => + sql( + `select coalesce((select hour_count || '/' || day_count from private.workspace_write_budgets where workspace_id = '${ws}'), 'none')`, + ) + +function create( + account: Account, + ws: string, + fields: Record, + requestId = randomUUID(), +) { + return rpc( + 'create_client', + { + workspace_id: ws, + create_request_id: requestId, + kind: 'person', + ...fields, + }, + account.token, + ) +} +const idOf = (result: RestResult) => (result.body as { id: string }).id +const fullUpdate = ( + clientId: string, + revision: number, + displayName: string, + city: string | null = null, +) => ({ + client_id: clientId, + expected_revision: revision, + kind: 'person', + display_name: displayName, + email: null, + phone: null, + address_line1: null, + address_line2: null, + postal_code: null, + city, + country: null, +}) +/** The error as the client sees it: status, code, message, details, hint. */ +const shape = (result: RestResult) => { + const body = result.body as Record + return [ + result.status, + body.code, + body.message, + body.details ?? null, + body.hint ?? null, + ] +} + +describe('clients through PostgREST, per role', () => { + let a: Account + let b: Account + let wA: string + let wB: string + let lac: string + + beforeAll(async () => { + a = await confirmedAccount('cl-a') + b = await confirmedAccount('cl-b') + wA = await workspaceOf(a.id) + wB = await workspaceOf(b.id) + const created = await create(a, wA, { + kind: 'organization', + display_name: 'Écurie du Lac', + email: 'Contact@Ecurie-Lac.test', + phone: '+33612345678', + city: 'Lyon', + }) + expect(created.status).toBe(200) + lac = idOf(created) + }) + + it('A creates, reads, searches with POST, updates and archives', async () => { + const row = await rest( + `/clients?select=id,kind,display_name,email,revision&id=eq.${lac}`, + a.token, + ) + expect(row.body).toEqual([ + { + id: lac, + kind: 'organization', + display_name: 'Écurie du Lac', + email: 'contact@ecurie-lac.test', + revision: 1, + }, + ]) + const found = await rpc( + 'search_clients', + { workspace_id: wA, query: 'ecu' }, + a.token, + ) + expect((found.body as { id: string }[]).map((r) => r.id)).toEqual([lac]) + const phone = await rpc( + 'search_clients', + { workspace_id: wA, query: '06 12' }, + a.token, + ) + expect((phone.body as { id: string }[]).map((r) => r.id)).toEqual([lac]) + expect( + ( + await rpc( + 'update_client', + fullUpdate(lac, 1, 'Écurie du Lac', 'Annecy'), + a.token, + ) + ).body, + ).toEqual({ revision: 2 }) + expect( + ( + await rpc( + 'set_client_archived', + { client_id: lac, archived: true }, + a.token, + ) + ).body, + ).toEqual({ revision: 3 }) + expect( + ( + await rpc( + 'set_client_archived', + { client_id: lac, archived: false }, + a.token, + ) + ).body, + ).toEqual({ revision: 4 }) + }) + + it('B gets nothing of A: reads, counts, search, and the same refusal as for an unknown id', async () => { + expect( + (await rest(`/clients?select=id&id=eq.${lac}`, b.token)).body, + ).toEqual([]) + const head = await rest( + `/clients?select=id&workspace_id=eq.${wA}`, + b.token, + { method: 'HEAD', headers: { Prefer: 'count=exact' } }, + ) + expect(head.headers.get('content-range')).toBe('*/0') + expect( + (await rpc('search_clients', { workspace_id: wA, query: '' }, b.token)) + .body, + ).toEqual([]) + const foreign = await rpc('update_client', fullUpdate(lac, 4, 'X'), b.token) + const unknown = await rpc( + 'update_client', + fullUpdate(randomUUID(), 4, 'X'), + b.token, + ) + expect(shape(foreign)).toEqual(shape(unknown)) + expect(shape(foreign)).toEqual([403, '42501', 'not_found', null, null]) + expect(shape(await create(b, wA, { display_name: 'X' }))).toEqual( + shape(await create(b, randomUUID(), { display_name: 'X' })), + ) + expect( + shape( + await rpc( + 'set_client_archived', + { client_id: lac, archived: true }, + b.token, + ), + ), + ).toEqual([403, '42501', 'not_found', null, null]) + }) + + it('refuses direct writes, the anon key and the service key; error bodies carry no value', async () => { + const attempts: [string, string, RequestInit, number][] = [ + [ + '/clients', + b.token, + { + method: 'POST', + body: JSON.stringify({ + workspace_id: wB, + kind: 'person', + display_name: 'Direct', + }), + }, + 403, + ], + [ + `/clients?id=eq.${lac}`, + a.token, + { method: 'PATCH', body: JSON.stringify({ display_name: 'Direct' }) }, + 403, + ], + [`/clients?id=eq.${lac}`, a.token, { method: 'DELETE' }, 403], + ['/clients?select=id', stack.anonKey, {}, 401], + [ + '/rpc/search_clients', + stack.anonKey, + { method: 'POST', body: JSON.stringify({ workspace_id: wA }) }, + 401, + ], + ['/clients?select=id', stack.serviceKey, {}, 403], + [ + '/rpc/create_client', + stack.serviceKey, + { + method: 'POST', + body: JSON.stringify({ + workspace_id: wA, + create_request_id: randomUUID(), + kind: 'person', + display_name: 'S', + }), + }, + 403, + ], + ] + for (const [path, token, init, status] of attempts) { + const result = await rest(path, token, init) + expect([path, result.status, errorCode(result)]).toEqual([ + path, + status, + '42501', + ]) + expect(result.text).not.toContain('Lac') + } + const invalid = await create(a, wA, { + display_name: 'Name', + email: 'secret-value-not-an-email', + }) + expect(shape(invalid)).toEqual([400, 'P0001', 'invalid_input', null, null]) + expect(invalid.text).not.toContain('secret-value') + }) + + it('cuts an unconfirmed or deactivated account', async () => { + await sql(`update public.profiles set active = false where id = '${a.id}'`) + expect((await rest('/clients?select=id', a.token)).body).toEqual([]) + expect( + shape(await rpc('update_client', fullUpdate(lac, 4, 'X'), a.token)), + ).toEqual([403, '42501', 'not_found', null, null]) + await sql(`update public.profiles set active = true where id = '${a.id}'`) + await sql( + `update auth.users set email_confirmed_at = null where id = '${a.id}'`, + ) + expect((await rest('/clients?select=id', a.token)).body).toEqual([]) + await sql( + `update auth.users set email_confirmed_at = now() where id = '${a.id}'`, + ) + expect((await rest('/clients?select=id', a.token)).body).toEqual([ + { id: lac }, + ]) + }) + + it('hides client audit rows from the platform owner (N9)', async () => { + expect( + await sql( + `select count(*) from audit.audit_logs where resource_id = '${lac}'`, + ), + ).toBe('4') + // audit is not exposed through PostgREST; the owner's view is its RLS-filtered SQL view. + const ownerId = await sql( + `select id from auth.users where email = 'owner@faunosteo.local'`, + ) + const asOwner = await sql(`begin; set local role authenticated; + select set_config('request.jwt.claims', '{"sub":"${ownerId}","role":"authenticated"}', true); + select count(*) from audit.audit_logs where resource_id = '${lac}'; commit;`) + expect(asOwner.split('\n').pop()).toBe('0') + }) +}) + +describe('concurrent writes', () => { + let a: Account + let wA: string + + beforeAll(async () => { + a = await confirmedAccount('cl-race') + wA = await workspaceOf(a.id) + }) + + it('20 parallel creates in one workspace all land, counted once each', async () => { + const results = await Promise.all( + Array.from({ length: 20 }, (_, i) => + create(a, wA, { display_name: `Parallel ${i}` }), + ), + ) + expect(results.map((r) => r.status)).toEqual(Array(20).fill(200)) + expect( + await sql( + `select count(*) from public.clients where workspace_id = '${wA}'`, + ), + ).toBe('20') + expect(await budgetOf(wA)).toBe('20/20') + }) + + it('the same request id sent 8 times at once creates one client and answers it 8 times', async () => { + const requestId = randomUUID() + const results = await Promise.all( + Array.from({ length: 8 }, () => + create(a, wA, { display_name: 'Replayed' }, requestId), + ), + ) + expect(new Set(results.map(idOf)).size).toBe(1) + expect( + await sql( + `select count(*) from public.clients where create_request_id = '${requestId}'`, + ), + ).toBe('1') + expect(await budgetOf(wA)).toBe('21/21') + }) + + it('two different contents racing on one request id: one created, the other refused', async () => { + const requestId = randomUUID() + const [x, y] = await Promise.all([ + create(a, wA, { display_name: 'Racer X' }, requestId), + create(a, wA, { display_name: 'Racer Y' }, requestId), + ]) + expect([x.status, y.status].sort()).toEqual([200, 400]) + expect( + [x, y] + .map((r) => + r.status === 400 ? (r.body as { message: string }).message : 'ok', + ) + .sort(), + ).toEqual(['ok', 'request_conflict']) + expect( + await sql( + `select count(*) from public.clients where create_request_id = '${requestId}'`, + ), + ).toBe('1') + }) + + it('two updates from the same revision: one wins, the other gets conflict, nothing lost', async () => { + const id = idOf(await create(a, wA, { display_name: 'Revision base' })) + const [x, y] = await Promise.all([ + rpc('update_client', fullUpdate(id, 1, 'Edited in tab X'), a.token), + rpc('update_client', fullUpdate(id, 1, 'Edited in tab Y'), a.token), + ]) + const winner = x.status === 200 ? 'Edited in tab X' : 'Edited in tab Y' + expect([x.status, y.status].sort()).toEqual([200, 400]) + expect([x, y].find((r) => r.status === 400)?.body).toMatchObject({ + message: 'conflict', + }) + expect( + await sql( + `select display_name || '/' || revision from public.clients where id = '${id}'`, + ), + ).toBe(`${winner}/2`) + }) + + it('archive, restore and edits racing on one client end consistent, without deadlock', async () => { + const id = idOf(await create(a, wA, { display_name: 'Archive race' })) + const calls = Array.from({ length: 30 }, (_, i) => + i % 3 === 0 + ? rpc('set_client_archived', { client_id: id, archived: true }, a.token) + : i % 3 === 1 + ? rpc( + 'set_client_archived', + { client_id: id, archived: false }, + a.token, + ) + : rpc('update_client', fullUpdate(id, 1, `Edit ${i}`), a.token), + ) + const results = await Promise.all(calls) + const messages = results.map((r) => + r.status === 200 ? 'ok' : (r.body as { message: string }).message, + ) + expect( + messages.every((m) => ['ok', 'archived', 'conflict'].includes(m)), + ).toBe(true) + const [revision, archived] = ( + await sql( + `select revision || '|' || (archived_at is not null) from public.clients where id = '${id}'`, + ) + ).split('|') + const audited = await sql( + `select count(*) from audit.audit_logs where resource_id = '${id}'`, + ) + expect(Number(audited)).toBe(Number(revision)) + expect(['true', 'false']).toContain(archived) + }) + + it('at the hourly limit, 20 racing writes: exactly the remaining 10 pass, refused ones consume nothing', async () => { + await sql( + `update private.workspace_write_budgets set hour_count = 990 where workspace_id = '${wA}'`, + ) + const results = await Promise.all( + Array.from({ length: 20 }, (_, i) => + create(a, wA, { display_name: `Limit ${i}` }), + ), + ) + const statuses = results.map((r) => + r.status === 200 ? 'ok' : (r.body as { message: string }).message, + ) + expect(statuses.filter((s) => s === 'ok')).toHaveLength(10) + expect(statuses.filter((s) => s === 'rate_limited')).toHaveLength(10) + expect((await budgetOf(wA)).split('/')[0]).toBe('1000') + await sql( + `update private.workspace_write_budgets set hour_count = 0, day_count = 0 where workspace_id = '${wA}'`, + ) + }) + + it('locks stay per workspace: a held budget row delays its workspace only', async () => { + const accounts = await Promise.all( + Array.from({ length: 10 }, (_, i) => confirmedAccount(`cl-iso-${i}`)), + ) + const spaces = await Promise.all(accounts.map((x) => workspaceOf(x.id))) + expect( + (await create(accounts[0], spaces[0], { display_name: 'Seed' })).status, + ).toBe(200) + const holder = + sql(`begin; select 1 from private.workspace_write_budgets where workspace_id = '${spaces[0]}' for update; + select pg_sleep(2); commit;`) + await new Promise((resolve) => setTimeout(resolve, 300)) + const started = Date.now() + const blocked = create(accounts[0], spaces[0], { + display_name: 'Waits', + }).then((r) => ({ r, ms: Date.now() - started })) + const others = await Promise.all( + accounts + .slice(1) + .map((x, i) => + create(x, spaces[i + 1], { display_name: 'Independent' }), + ), + ) + const othersMs = Date.now() - started + const waited = await blocked + await holder + expect(others.map((r) => r.status)).toEqual(Array(9).fill(200)) + expect(othersMs).toBeLessThan(1000) + expect(waited.r.status).toBe(200) + expect(waited.ms).toBeGreaterThan(1200) + console.log( + `[measure] budget row of one workspace held 2 s: 9 creates elsewhere ${othersMs} ms; the create in the held workspace waited ${waited.ms} ms`, + ) + }) + + it('a mixed burst of 60 writes in one workspace raises no deadlock', async () => { + const ids = await Promise.all( + Array.from({ length: 5 }, (_, i) => + create(a, wA, { display_name: `Burst base ${i}` }).then(idOf), + ), + ) + const started = Date.now() + const results = await Promise.all( + Array.from({ length: 60 }, (_, i) => { + const id = ids[i % 5] + if (i % 4 === 0) + return create(a, wA, { display_name: `Burst new ${i}` }) + if (i % 4 === 1) + return rpc( + 'set_client_archived', + { client_id: id, archived: i % 8 === 1 }, + a.token, + ) + return rpc( + 'update_client', + fullUpdate(id, 1, `Burst edit ${i}`), + a.token, + ) + }), + ) + const codes = results.map((r) => + r.status === 200 + ? 'ok' + : `${errorCode(r)}:${(r.body as { message: string }).message}`, + ) + expect( + codes.filter((c) => c.startsWith('40P01') || c.startsWith('40001')), + ).toEqual([]) + expect( + codes.every( + (c) => c === 'ok' || ['P0001:conflict', 'P0001:archived'].includes(c), + ), + ).toBe(true) + console.log( + `[measure] 60 mixed writes in one workspace: ${Date.now() - started} ms, ${codes.filter((c) => c === 'ok').length} applied`, + ) + }) +}) + +describe('search on 20 000 clients', () => { + it('records the time of name and phone searches (measurement, not a gate)', async () => { + const a = await confirmedAccount('cl-volume') + const ws = await workspaceOf(a.id) + await sql(`insert into public.clients (workspace_id, kind, display_name, city, email, phone, create_request_id, create_request_digest) + select '${ws}', 'person', 'Client ' || g || ' Dupont', 'Ville ' || (g % 500), 'client' || g || '@example.test', + '+336' || lpad(g::text, 8, '0'), gen_random_uuid(), '\\x00' + from generate_series(1, 20000) g; analyze public.clients;`) + const terms = [ + 'dupont', + 'client 1999', + 'ville 42', + 'example', + '06 00 01', + 'zzz-none', + '', + ] + const times: number[] = [] + for (let round = 0; round < 3; round++) { + for (const query of terms) { + const started = performance.now() + const result = await rpc( + 'search_clients', + { workspace_id: ws, query }, + a.token, + ) + times.push(performance.now() - started) + expect(result.status).toBe(200) + } + } + times.sort((x, y) => x - y) + const p95 = times[Math.ceil(times.length * 0.95) - 1] + console.log( + `[measure] search_clients over 20 000 clients, ${times.length} HTTP calls: median ${times[times.length >> 1].toFixed(1)} ms, p95 ${p95.toFixed(1)} ms, max ${times[times.length - 1].toFixed(1)} ms`, + ) + expect( + await sql( + `select count(*) from public.clients where workspace_id = '${ws}'`, + ), + ).toBe('20000') + }) +}) diff --git a/supabase/migrations/20261025110000_clients.sql b/supabase/migrations/20261025110000_clients.sql new file mode 100644 index 00000000..1594bc35 --- /dev/null +++ b/supabase/migrations/20261025110000_clients.sql @@ -0,0 +1,514 @@ +-- V1-1.2 Clients (M2): the clients of a workspace, written only through RPCs, +-- read through RLS, searched through a POST RPC. Contract: +-- docs/development/V1-1_OWNERS_ANIMALS.md §5 (text rules), §5.1 (fields), +-- §8 (schema), §9 (helpers, RLS, RPCs, failures), §10 (limits), §13.2 (N2, +-- N3, N6, N7, N9). +-- +-- Invariants pinned by supabase/tests/013_clients.sql and the sandbox suite: +-- * a client belongs to one workspace; only a member with a write role of +-- an active, confirmed account writes it, through the four RPCs; every +-- foreign or unknown id is answered with the same 42501 `not_found`; +-- * a create is idempotent by (workspace, create_request_id); a replay +-- with other content is refused (`request_conflict`), never applied; +-- * an update needs the current revision; an archived client is read-only +-- until restored; +-- * writes are capped per workspace (20 000 clients; 1 000 audited writes +-- per UTC hour, 5 000 per UTC day) under locks, so concurrent calls +-- cannot pass a cap and a refused or replayed call consumes nothing; +-- * audit rows carry ids only, and platform staff do not read them (N9). + +-- --------------------------------------------------------------------------- +-- Text folding for search keys +-- --------------------------------------------------------------------------- +create extension if not exists unaccent with schema extensions; + +-- Accents removed with the explicit dictionary, then ASCII lower case +-- (collation "C"), so PGlite and the real image fold identically. Letters +-- outside ASCII that unaccent keeps (Cyrillic, Greek) keep their case. +-- Declared immutable for the generated columns: the dictionary is fixed by +-- the extension version (contract §8). +create or replace function private.fold_text(p_value text) +returns text +language sql +immutable +parallel safe +set search_path = '' +as $$ + select lower(extensions.unaccent('extensions.unaccent'::regdictionary, p_value) collate "C"); +$$; + +comment on function private.fold_text(text) is + 'Search key folding: unaccent (explicit dictionary) then ASCII lower case. Used by generated columns and by search_clients.'; + +-- The text rule of contract §5: 1 to p_max characters (code points), no +-- leading or trailing space, no control character of the explicit ranges. +-- Null passes (an absent value is null, never an empty string). +create or replace function private.is_clean_text(p_value text, p_max integer) +returns boolean +language sql +immutable +parallel safe +set search_path = '' +as $$ + select p_value is null + or (char_length(p_value) between 1 and p_max + and p_value = btrim(p_value) + and p_value !~ '[\u0001-\u001f\u007f-\u009f\u2028\u2029]'); +$$; + +comment on function private.is_clean_text(text, integer) is + 'Contract §5 text rule for CHECK constraints: length 1..p_max in code points, trimmed, no control character.'; + +-- --------------------------------------------------------------------------- +-- clients +-- --------------------------------------------------------------------------- +create type public.client_kind as enum ('person', 'organization'); + +create table public.clients ( + id uuid primary key default gen_random_uuid(), + -- restrict: an account whose workspace holds clients cannot be deleted (D9a). + workspace_id uuid not null references public.workspaces (id) on delete restrict, + kind public.client_kind not null, + display_name text not null + constraint clients_display_name_text check (private.is_clean_text(display_name, 120)), + email text + constraint clients_email_format check ( + private.is_clean_text(email, 254) + and email = lower(email) + and email ~ '^[^@\s]+@[^@\s]+\.[^@\s]+$' + ), + phone text + constraint clients_phone_e164 check (phone ~ '^\+[1-9][0-9]{6,14}$'), + address_line1 text + constraint clients_address_line1_text check (private.is_clean_text(address_line1, 120)), + address_line2 text + constraint clients_address_line2_text check (private.is_clean_text(address_line2, 120)), + postal_code text + constraint clients_postal_code_text check (private.is_clean_text(postal_code, 16)), + city text + constraint clients_city_text check (private.is_clean_text(city, 80)), + country text + constraint clients_country_code check (country ~ '^[A-Z]{2}$'), + name_key text collate "C" + generated always as (private.fold_text(display_name)) stored, + search_key text collate "C" + generated always as ( + private.fold_text(display_name || ' ' || coalesce(city, '') || ' ' || coalesce(email, '')) + ) stored, + phone_digits text collate "C" generated always as (ltrim(phone, '+')) stored, + -- Idempotency: the form sends one uuid per create attempt. The digest of the + -- creation content tells a replay from a divergent reuse; never readable + -- through the API. + create_request_id uuid not null, + create_request_digest bytea not null, + revision integer not null default 1 + constraint clients_revision_positive check (revision >= 1), + archived_at timestamptz, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + constraint clients_workspace_id_unique unique (workspace_id, id), + constraint clients_create_request_unique unique (workspace_id, create_request_id) +); + +comment on table public.clients is + 'Clients of a workspace (person or organization). Writes only through create_client, update_client, set_client_archived; reads through RLS and search_clients.'; +comment on column public.clients.display_name is + 'The single name reference (N2): display, search, sorting, documents.'; + +-- Workspace filter, name order, keyset pagination and the search scan. +create index clients_workspace_name_idx on public.clients (workspace_id, name_key, id); + +create trigger clients_set_updated_at + before update on public.clients + for each row execute function private.set_updated_at(); + +-- --------------------------------------------------------------------------- +-- Write budget per workspace (N6, owner decision on the counter) +-- --------------------------------------------------------------------------- +-- One row per workspace, fixed UTC windows: the hour starting at hh:00:00 UTC +-- and the day starting at 00:00:00 UTC. A window that has passed restarts at +-- 1 on the next write. The row lock of the upsert serialises the writes of +-- one workspace only; it is the last lock a write RPC takes, so no lock +-- cycle can form. The counts are rolled back with any refused write. +create table private.workspace_write_budgets ( + workspace_id uuid primary key references public.workspaces (id) on delete cascade, + hour_start timestamptz not null, + hour_count integer not null, + day_start timestamptz not null, + day_count integer not null +); + +comment on table private.workspace_write_budgets is + 'Audited writes per workspace in the current UTC hour and day (contract §10). Written only by private.consume_write_budget.'; + +create or replace function private.consume_write_budget(p_workspace_id uuid) +returns void +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_hour timestamptz := date_trunc('hour', now(), 'UTC'); + v_day timestamptz := date_trunc('day', now(), 'UTC'); + v_hour_count integer; + v_day_count integer; +begin + insert into private.workspace_write_budgets as b (workspace_id, hour_start, hour_count, day_start, day_count) + values (p_workspace_id, v_hour, 1, v_day, 1) + on conflict (workspace_id) do update set + hour_count = case when b.hour_start = excluded.hour_start then b.hour_count + 1 else 1 end, + hour_start = excluded.hour_start, + day_count = case when b.day_start = excluded.day_start then b.day_count + 1 else 1 end, + day_start = excluded.day_start + returning b.hour_count, b.day_count into v_hour_count, v_day_count; + + -- Raising undoes the increment with the rest of the refused write. + if v_hour_count > 1000 or v_day_count > 5000 then + raise exception 'rate_limited' using errcode = 'P0001'; + end if; +end; +$$; + +comment on function private.consume_write_budget(uuid) is + 'Counts one audited write of the workspace in its UTC hour and day; raises rate_limited past 1 000 / 5 000. Call last, after the entity locks.'; + +-- --------------------------------------------------------------------------- +-- Write RPCs (contract §9.3). Each one: authorise and lock in one statement +-- (no row = 42501 not_found, the same for a foreign and an unknown id), then +-- archived, then revision, then rules; the budget last; one audit row with +-- ids only; returns ids and revision. +-- --------------------------------------------------------------------------- +create or replace function public.create_client( + workspace_id uuid, + create_request_id uuid, + kind text, + display_name text, + email text default null, + phone text default null, + address_line1 text default null, + address_line2 text default null, + postal_code text default null, + city text default null, + country text default null +) +returns jsonb +language plpgsql +volatile +security definer +set search_path = '' +as $$ +#variable_conflict use_column +declare + v_kind public.client_kind; + v_email text := lower(create_client.email); + v_digest bytea; + v_existing_id uuid; + v_existing_revision integer; + v_existing_digest bytea; + v_id uuid; +begin + -- Serialises the creates of this workspace (replay check, cap, insert). + perform 1 from public.workspaces w + where w.id = create_client.workspace_id + and w.id in (select private.writable_workspace_ids()) + for no key update; + if not found then + raise exception 'not_found' using errcode = '42501'; + end if; + + begin + v_kind := create_client.kind::public.client_kind; + exception when invalid_text_representation then + raise exception 'invalid_input' using errcode = 'P0001'; + end; + v_digest := sha256(convert_to(jsonb_build_array( + v_kind, create_client.display_name, v_email, create_client.phone, + create_client.address_line1, create_client.address_line2, + create_client.postal_code, create_client.city, create_client.country + )::text, 'UTF8')); + + select c.id, c.revision, c.create_request_digest + into v_existing_id, v_existing_revision, v_existing_digest + from public.clients c + where c.workspace_id = create_client.workspace_id + and c.create_request_id = create_client.create_request_id; + if found then + if v_existing_digest <> v_digest then + raise exception 'request_conflict' using errcode = 'P0001'; + end if; + return jsonb_build_object('id', v_existing_id, 'revision', v_existing_revision); + end if; + + if (select count(*) from public.clients c where c.workspace_id = create_client.workspace_id) >= 20000 then + raise exception 'limit_reached' using errcode = 'P0001'; + end if; + perform private.consume_write_budget(create_client.workspace_id); + + begin + insert into public.clients ( + workspace_id, kind, display_name, email, phone, address_line1, address_line2, + postal_code, city, country, create_request_id, create_request_digest + ) + values ( + create_client.workspace_id, v_kind, create_client.display_name, v_email, create_client.phone, + create_client.address_line1, create_client.address_line2, create_client.postal_code, + create_client.city, create_client.country, create_client.create_request_id, v_digest + ) + returning id into v_id; + exception when check_violation or not_null_violation or string_data_right_truncation + or invalid_text_representation then + raise exception 'invalid_input' using errcode = 'P0001'; + end; + + perform private.log_event( + auth.uid(), 'client.created', 'client', v_id, null, null, + jsonb_build_object('workspace_id', create_client.workspace_id) + ); + return jsonb_build_object('id', v_id, 'revision', 1); +end; +$$; + +create or replace function public.update_client( + client_id uuid, + expected_revision integer, + kind text, + display_name text, + email text, + phone text, + address_line1 text, + address_line2 text, + postal_code text, + city text, + country text +) +returns jsonb +language plpgsql +volatile +security definer +set search_path = '' +as $$ +#variable_conflict use_column +declare + v_row public.clients; + v_kind public.client_kind; + v_email text := lower(update_client.email); +begin + select c.* into v_row + from public.clients c + where c.id = update_client.client_id + and c.workspace_id in (select private.writable_workspace_ids()) + for update; + if not found then + raise exception 'not_found' using errcode = '42501'; + end if; + if v_row.archived_at is not null then + raise exception 'archived' using errcode = 'P0001'; + end if; + if update_client.expected_revision is distinct from v_row.revision then + raise exception 'conflict' using errcode = 'P0001'; + end if; + + begin + v_kind := update_client.kind::public.client_kind; + exception when invalid_text_representation then + raise exception 'invalid_input' using errcode = 'P0001'; + end; + + -- No change: nothing written, nothing counted. + if (v_kind, update_client.display_name, v_email, update_client.phone, update_client.address_line1, + update_client.address_line2, update_client.postal_code, update_client.city, update_client.country) + is not distinct from + (v_row.kind, v_row.display_name, v_row.email, v_row.phone, v_row.address_line1, + v_row.address_line2, v_row.postal_code, v_row.city, v_row.country) then + return jsonb_build_object('revision', v_row.revision); + end if; + + perform private.consume_write_budget(v_row.workspace_id); + begin + update public.clients c + set kind = v_kind, display_name = update_client.display_name, email = v_email, + phone = update_client.phone, address_line1 = update_client.address_line1, + address_line2 = update_client.address_line2, postal_code = update_client.postal_code, + city = update_client.city, country = update_client.country, + revision = c.revision + 1 + where c.id = v_row.id; + exception when check_violation or not_null_violation or string_data_right_truncation + or invalid_text_representation then + raise exception 'invalid_input' using errcode = 'P0001'; + end; + + perform private.log_event( + auth.uid(), 'client.updated', 'client', v_row.id, null, null, + jsonb_build_object('workspace_id', v_row.workspace_id) + ); + return jsonb_build_object('revision', v_row.revision + 1); +end; +$$; + +create or replace function public.set_client_archived( + client_id uuid, + archived boolean +) +returns jsonb +language plpgsql +volatile +security definer +set search_path = '' +as $$ +#variable_conflict use_column +declare + v_row public.clients; +begin + select c.* into v_row + from public.clients c + where c.id = set_client_archived.client_id + and c.workspace_id in (select private.writable_workspace_ids()) + for update; + if not found then + raise exception 'not_found' using errcode = '42501'; + end if; + if set_client_archived.archived is null then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + -- Already in that state: nothing written, nothing counted. + if (v_row.archived_at is not null) = set_client_archived.archived then + return jsonb_build_object('revision', v_row.revision); + end if; + + perform private.consume_write_budget(v_row.workspace_id); + update public.clients c + set archived_at = case when set_client_archived.archived then now() end, + revision = c.revision + 1 + where c.id = v_row.id; + + perform private.log_event( + auth.uid(), + case when set_client_archived.archived then 'client.archived' else 'client.restored' end, + 'client', v_row.id, null, null, + jsonb_build_object('workspace_id', v_row.workspace_id) + ); + return jsonb_build_object('revision', v_row.revision + 1); +end; +$$; + +-- --------------------------------------------------------------------------- +-- Search (contract §9.3): security invoker, so RLS limits it to the caller's +-- workspaces; a foreign workspace id returns no row. Called with POST, so the +-- term and the cursor stay out of URLs. +-- --------------------------------------------------------------------------- +create or replace function public.search_clients( + workspace_id uuid, + query text default '', + archived boolean default false, + page_size integer default 25, + after_name_key text default null, + after_id uuid default null +) +returns table ( + id uuid, + kind public.client_kind, + display_name text, + city text, + phone text, + email text, + archived_at timestamptz, + name_key text +) +language plpgsql +stable +security invoker +set search_path = '' +as $$ +#variable_conflict use_column +declare + v_term text := btrim(coalesce(search_clients.query, '')); + v_pattern text; + v_digits text; +begin + if char_length(v_term) > 100 + or search_clients.archived is null + or search_clients.page_size is null + or search_clients.page_size not between 1 and 100 + or (search_clients.after_name_key is null) <> (search_clients.after_id is null) then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + + -- Folded term inside search_key; LIKE wildcards escaped, backslash first. + v_pattern := '%' || replace(replace(replace(private.fold_text(v_term), '\', '\\'), '%', '\%'), '_', '\_') || '%'; + -- A phone-like term (digits, spaces, dots, hyphens, +; at least 4 digits) + -- is also looked for in phone_digits, without one leading 0. + if v_term ~ '^[0-9 .+-]+$' and char_length(regexp_replace(v_term, '[^0-9]', '', 'g')) >= 4 then + v_digits := regexp_replace(regexp_replace(v_term, '[^0-9]', '', 'g'), '^0', ''); + end if; + + return query + select c.id, c.kind, c.display_name, c.city, c.phone, c.email, c.archived_at, c.name_key + from public.clients c + where c.workspace_id = search_clients.workspace_id + and (c.archived_at is not null) = search_clients.archived + and (v_term = '' + or c.search_key like v_pattern + or (v_digits is not null and c.phone_digits like '%' || v_digits || '%')) + and (search_clients.after_name_key is null + or (c.name_key, c.id) > (search_clients.after_name_key collate "C", search_clients.after_id)) + order by c.name_key, c.id + limit search_clients.page_size; +end; +$$; + +comment on function public.create_client(uuid, uuid, text, text, text, text, text, text, text, text, text) is + 'Creates a client in a writable workspace; idempotent by create_request_id (divergent replay: request_conflict). Returns {id, revision}.'; +comment on function public.update_client(uuid, integer, text, text, text, text, text, text, text, text, text) is + 'Replaces the nine fields of an active client at expected_revision. Returns {revision}.'; +comment on function public.set_client_archived(uuid, boolean) is + 'Archives or restores a client (same state: no write). Returns {revision}.'; +comment on function public.search_clients(uuid, text, boolean, integer, text, uuid) is + 'Folded search (name, city, email; phone digits) in one workspace, keyset pages on (name_key, id), 25 by default, 100 at most.'; + +-- --------------------------------------------------------------------------- +-- Audit (N9): platform owners and admins keep reading platform events, not +-- the activity of private records. +-- --------------------------------------------------------------------------- +alter policy audit_logs_select_admin on audit.audit_logs + using ( + private.is_platform_admin((select auth.uid())) + and split_part(action, '.', 1) not in ('client', 'animal', 'animal_client_relation') + ); + +-- --------------------------------------------------------------------------- +-- Privileges + RLS (N7: nothing for anon or service_role) +-- --------------------------------------------------------------------------- +revoke all on public.clients from public, anon, authenticated, service_role; +grant select ( + id, workspace_id, kind, display_name, email, phone, address_line1, address_line2, + postal_code, city, country, name_key, search_key, phone_digits, create_request_id, + revision, archived_at, created_at, updated_at +) on public.clients to authenticated; + +alter table public.clients enable row level security; + +create policy clients_select_member + on public.clients + for select + to authenticated + using (workspace_id in (select private.caller_workspace_ids())); + +revoke all on private.workspace_write_budgets from public, anon, authenticated, service_role; + +revoke all on function private.fold_text(text) from public, anon, authenticated, service_role; +revoke all on function private.is_clean_text(text, integer) from public, anon, authenticated, service_role; +revoke all on function private.consume_write_budget(uuid) from public, anon, authenticated, service_role; +revoke all on function public.create_client(uuid, uuid, text, text, text, text, text, text, text, text, text) + from public, anon, authenticated, service_role; +revoke all on function public.update_client(uuid, integer, text, text, text, text, text, text, text, text, text) + from public, anon, authenticated, service_role; +revoke all on function public.set_client_archived(uuid, boolean) from public, anon, authenticated, service_role; +revoke all on function public.search_clients(uuid, text, boolean, integer, text, uuid) + from public, anon, authenticated, service_role; + +grant execute on function public.create_client(uuid, uuid, text, text, text, text, text, text, text, text, text) to authenticated; +grant execute on function public.update_client(uuid, integer, text, text, text, text, text, text, text, text, text) to authenticated; +grant execute on function public.set_client_archived(uuid, boolean) to authenticated; +grant execute on function public.search_clients(uuid, text, boolean, integer, text, uuid) to authenticated; +-- The invoker search folds its term as the caller. +grant execute on function private.fold_text(text) to authenticated; diff --git a/supabase/tests/001_schema.sql b/supabase/tests/001_schema.sql index ce66814d..37283f66 100644 --- a/supabase/tests/001_schema.sql +++ b/supabase/tests/001_schema.sql @@ -62,7 +62,7 @@ select is( (select string_agg(p.proname::text, ',' order by p.proname::text collate "C") from pg_proc p join pg_namespace n on n.oid = p.pronamespace where n.nspname in ('private', 'audit') and has_function_privilege('authenticated', p.oid, 'execute')), - 'caller_workspace_ids,can_edit_sheet,can_read_avatar_object,can_read_sheet_asset_object,can_upload_avatar_object,can_use_sheet,has_platform_role,is_platform_admin,is_platform_moderator,is_platform_owner,is_support', + 'caller_workspace_ids,can_edit_sheet,can_read_avatar_object,can_read_sheet_asset_object,can_upload_avatar_object,can_use_sheet,fold_text,has_platform_role,is_platform_admin,is_platform_moderator,is_platform_owner,is_support', 'authenticated executes only the policy predicates in private' ); diff --git a/supabase/tests/013_clients.sql b/supabase/tests/013_clients.sql new file mode 100644 index 00000000..38857966 --- /dev/null +++ b/supabase/tests/013_clients.sql @@ -0,0 +1,452 @@ +-- V1-1.2 Clients (M2): fields and text rules, idempotent creates, revisions, +-- archive, search, isolation between workspaces, refusals for every other +-- actor, caps and write budget, minimised audit, privileges and census. +-- Contract: docs/development/V1-1_OWNERS_ANIMALS.md §5, §9, §10, §12.1. +-- Actors: A and B confirmed and active; C unconfirmed; D deactivated after +-- creating a client; S a platform owner; E (cap) and F (budget) confirmed; +-- G an account without clients. +begin; +select plan(130); + +insert into auth.users (id, email, email_confirmed_at) values + ('60000000-0000-0000-0000-00000000000a', 'alice-cl@test.local', now()), + ('60000000-0000-0000-0000-00000000000b', 'bob-cl@test.local', now()), + ('60000000-0000-0000-0000-00000000000c', 'carol-cl@test.local', null), + ('60000000-0000-0000-0000-00000000000d', 'dave-cl@test.local', now()), + ('60000000-0000-0000-0000-000000000005', 'staff-cl@test.local', now()), + ('60000000-0000-0000-0000-00000000000e', 'cap-cl@test.local', now()), + ('60000000-0000-0000-0000-00000000000f', 'budget-cl@test.local', now()), + ('60000000-0000-0000-0000-000000000010', 'empty-cl@test.local', now()); +select private.assign_platform_role(null, '60000000-0000-0000-0000-000000000005', 'owner'); + +create function pg_temp.ws(p_user uuid) returns uuid language sql stable security definer +as $$ select id from public.workspaces where personal_user_id = p_user $$; +create function pg_temp.act_as(p_user uuid) returns text language sql +as $$ select set_config('request.jwt.claims', + json_build_object('sub', p_user, 'role', 'authenticated')::text, true) $$; +create function pg_temp.client(p_id uuid) returns public.clients language sql stable security definer +as $$ select c from public.clients c where c.id = p_id $$; +create function pg_temp.budget(p_ws uuid) returns text language sql stable security definer +as $$ select coalesce((select hour_count || '/' || day_count from private.workspace_write_budgets where workspace_id = p_ws), 'none') $$; +create function pg_temp.audit_count(p_resource uuid) returns bigint language sql stable security definer +as $$ select count(*) from audit.audit_logs where resource_id = p_resource $$; +-- The whole error of a statement, run as the calling role: SQLSTATE, message, detail, hint. +create function pg_temp.err(p_sql text) returns text language plpgsql +as $$ +declare v_state text; v_msg text; v_detail text; v_hint text; +begin + execute p_sql; + return 'no error'; +exception when others then + get stacked diagnostics v_state = returned_sqlstate, v_msg = message_text, + v_detail = pg_exception_detail, v_hint = pg_exception_hint; + return v_state || '|' || v_msg || '|' || coalesce(v_detail, '') || '|' || coalesce(v_hint, ''); +end; +$$; +-- SQLSTATE and message only: the real image appends a hint to table-privilege +-- refusals ("Grant the required privileges ..."), PGlite does not. +create function pg_temp.denial(p_sql text) returns text language sql +as $$ select split_part(pg_temp.err(p_sql), '|', 1) || '|' || split_part(pg_temp.err(p_sql), '|', 2) $$; +create table pg_temp.ids (key text primary key, id uuid not null); +grant all on pg_temp.ids to authenticated, anon, service_role; +grant execute on function pg_temp.ws(uuid), pg_temp.act_as(uuid), pg_temp.client(uuid), pg_temp.budget(uuid), + pg_temp.audit_count(uuid), pg_temp.err(text), pg_temp.denial(text) to authenticated, anon, service_role; + +-- --------------------------------------------------------------------------- +-- 1. Schema, privileges, census +-- --------------------------------------------------------------------------- +select has_table('public', 'clients', 'table public.clients exists'); +select ok((select relrowsecurity from pg_class where oid = 'public.clients'::regclass), 'RLS enabled on clients'); +select enum_has_labels('public', 'client_kind', array['person', 'organization'], 'client_kind: person, organization'); +select is((select tableowner::text from pg_tables where schemaname = 'public' and tablename = 'clients'), 'postgres', 'clients belongs to postgres'); +select is( + (select count(*) from (values ('anon'), ('service_role')) r(role) + cross join (values ('select'), ('insert'), ('update'), ('delete'), ('truncate'), ('references'), ('trigger')) p(priv) + where has_table_privilege(r.role, 'public.clients', p.priv)), + 0::bigint, 'anon and service_role hold no privilege on clients' +); +select is( + (select count(*) from (values ('insert'), ('update'), ('delete'), ('truncate'), ('references'), ('trigger')) p(priv) + where has_table_privilege('authenticated', 'public.clients', p.priv)), + 0::bigint, 'authenticated holds no write privilege on clients' +); +select ok(has_column_privilege('authenticated', 'public.clients', 'display_name', 'select') + and not has_column_privilege('authenticated', 'public.clients', 'create_request_digest', 'select'), + 'authenticated reads the record columns, never the request digest'); +select is( + (select count(*) from (values ('anon'), ('authenticated'), ('service_role')) r(role) + cross join (values ('select'), ('insert'), ('update'), ('delete')) p(priv) + where has_table_privilege(r.role, 'private.workspace_write_budgets', p.priv)), + 0::bigint, 'no API role touches the budget table' +); +select is( + (select string_agg(policyname || ':' || cmd || ':' || array_to_string(roles, '+'), ',') + from pg_policies where schemaname = 'public' and tablename = 'clients'), + 'clients_select_member:SELECT:authenticated', 'one SELECT policy on clients, for authenticated' +); +select is( + (select count(*) from pg_policies where schemaname = 'public' and tablename = 'clients' + and (qual not like '%caller_workspace_ids()%' or qual like '%platform%')), + 0::bigint, 'the clients policy goes through caller_workspace_ids() and names no platform role' +); +select is( + (select string_agg(p.proname || ':' || case when p.prosecdef then 'definer' else 'invoker' end, ',' order by p.proname::text collate "C") + from pg_proc p join pg_namespace n on n.oid = p.pronamespace + where p.proname in ('create_client', 'update_client', 'set_client_archived', 'search_clients', + 'fold_text', 'is_clean_text', 'consume_write_budget') + and p.proconfig = array['search_path=""'] and pg_get_userbyid(p.proowner) = 'postgres'), + 'consume_write_budget:definer,create_client:definer,fold_text:invoker,is_clean_text:invoker,search_clients:invoker,set_client_archived:definer,update_client:definer', + 'definer and invoker as designed; search_path empty; owner postgres' +); +select is( + (select string_agg(r.role || ':' || p.proname::text, ',' order by r.role, p.proname::text collate "C") + from pg_proc p cross join (values ('anon'), ('authenticated'), ('service_role')) r(role) + where p.proname in ('create_client', 'update_client', 'set_client_archived', 'search_clients', + 'fold_text', 'is_clean_text', 'consume_write_budget') + and has_function_privilege(r.role, p.oid, 'execute')), + 'authenticated:create_client,authenticated:fold_text,authenticated:search_clients,authenticated:set_client_archived,authenticated:update_client', + 'EXECUTE: authenticated on the four RPCs and the fold; anon and service_role on none' +); + +-- --------------------------------------------------------------------------- +-- 2. Creation by A: fields, normalisation, derived keys +-- --------------------------------------------------------------------------- +set local role authenticated; +select pg_temp.act_as('60000000-0000-0000-0000-00000000000a'); +insert into pg_temp.ids values + ('lac', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000001', + 'organization', 'Écurie du Lac', 'contact@ecurie-lac.test', '+33612345678', '1 chemin du Lac', null, '69000', 'Lyon', 'FR') ->> 'id')::uuid), + ('marie', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000002', + 'person', 'Marie Dupont', 'MARIE@Example.TEST', null, null, null, null, 'Évian') ->> 'id')::uuid), + ('ab', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000003', 'organization', 'A_B Haras') ->> 'id')::uuid), + ('axb', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000004', 'organization', 'AxB Haras') ->> 'id')::uuid), + ('pct', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000005', 'person', '100% Cheval') ->> 'id')::uuid), + ('bsl', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000006', 'person', 'Back\slash') ->> 'id')::uuid); + +select results_eq( + $$ select kind::text, display_name, email, phone, city, country, revision, archived_at is null + from public.clients where id = (select id from pg_temp.ids where key = 'lac') $$, + $$ values ('organization'::text, 'Écurie du Lac'::text, 'contact@ecurie-lac.test'::text, '+33612345678'::text, + 'Lyon'::text, 'FR'::text, 1, true) $$, + 'A reads the created organization with revision 1' +); +select is((pg_temp.client((select id from pg_temp.ids where key = 'marie'))).email, 'marie@example.test', 'the email is stored lower-case'); +select is((pg_temp.client((select id from pg_temp.ids where key = 'lac'))).name_key, 'ecurie du lac', 'name_key folds accents and case'); +select is((pg_temp.client((select id from pg_temp.ids where key = 'lac'))).phone_digits, '33612345678', 'phone_digits drops the +'); +select is((pg_temp.client((select id from pg_temp.ids where key = 'ab'))).country, null, 'no country is set by default'); +select is((select count(*) from public.clients), 6::bigint, 'A reads its six clients'); + +-- --------------------------------------------------------------------------- +-- 3. Text rules: refused with the bare code, nothing echoed +-- --------------------------------------------------------------------------- +create function pg_temp.try_create(p_kind text, p_name text, p_email text default null, p_phone text default null, + p_postal text default null, p_country text default null) returns text language sql +as $$ select pg_temp.err(format( + 'select public.create_client(%L, gen_random_uuid(), %L, %L, %L, %L, null, null, %L, null, %L)', + pg_temp.ws('60000000-0000-0000-0000-00000000000a'), p_kind, p_name, p_email, p_phone, p_postal, p_country)) $$; +grant execute on function pg_temp.try_create(text, text, text, text, text, text) to authenticated; + +select is(pg_temp.try_create('person', ''), 'P0001|invalid_input||', 'an empty name is refused'); +select is(pg_temp.try_create('person', null), 'P0001|invalid_input||', 'a missing name is refused'); +select is(pg_temp.try_create('person', ' Lead'), 'P0001|invalid_input||', 'a leading space is refused'); +select is(pg_temp.try_create('person', e'Tab\there'), 'P0001|invalid_input||', 'a tab (control character) is refused'); +select is(pg_temp.try_create('person', e'Line\u2028sep'), 'P0001|invalid_input||', 'U+2028 is refused'); +select is(pg_temp.try_create('person', e'C1\u0085'), 'P0001|invalid_input||', 'a C1 control (U+0085) is refused'); +select is(pg_temp.try_create('person', repeat('x', 121)), 'P0001|invalid_input||', '121 characters are refused'); +select is(pg_temp.try_create('person', repeat('é', 121)), 'P0001|invalid_input||', '121 accented characters (code points) are refused'); +select is(pg_temp.try_create('robot', 'Kind'), 'P0001|invalid_input||', 'an unknown kind is refused'); +select is(pg_temp.try_create(null, 'Kind'), 'P0001|invalid_input||', 'a missing kind is refused'); +select is(pg_temp.try_create('person', 'Mail', 'not-an-email'), 'P0001|invalid_input||', 'a malformed email is refused'); +select is(pg_temp.try_create('person', 'Mail', 'a b@c.test'), 'P0001|invalid_input||', 'an email with a space is refused'); +select is(pg_temp.try_create('person', 'Mail', repeat('a', 247) || '@ex.test'), 'P0001|invalid_input||', 'a 255-character email is refused'); +select is(pg_temp.try_create('person', 'Mail', repeat('a', 246) || '@ex.test'), 'no error', 'a 254-character email is accepted'); +select is(pg_temp.try_create('person', 'Phone', null, '0612345678'), 'P0001|invalid_input||', 'a national phone (not E.164) is refused'); +select is(pg_temp.try_create('person', 'Postal', null, null, repeat('9', 17)), 'P0001|invalid_input||', 'a 17-character postal code is refused'); +select is(pg_temp.try_create('person', 'Country', null, null, null, 'fr'), 'P0001|invalid_input||', 'a lower-case country code is refused'); +select is(pg_temp.try_create('person', 'Country', null, null, null, 'FRA'), 'P0001|invalid_input||', 'a three-letter country code is refused'); +select is(pg_temp.try_create('person', repeat('é', 120)), 'no error', '120 accented characters are accepted'); +select is((select count(*) from public.clients), 8::bigint, 'only the two valid creates were written'); + +-- --------------------------------------------------------------------------- +-- 4. Idempotent create: replay, normalised replay, divergent replay +-- --------------------------------------------------------------------------- +select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000a')), '8/8', 'eight writes counted so far'); +select is( + (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000002', + 'person', 'Marie Dupont', 'marie@example.test', null, null, null, null, 'Évian') ->> 'id')::uuid, + (select id from pg_temp.ids where key = 'marie'), + 'a replay (email in another case) returns the first client' +); +select is(pg_temp.audit_count((select id from pg_temp.ids where key = 'marie')), 1::bigint, 'the replay writes no audit row'); +select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000a')), '8/8', 'the replay consumes no budget'); +select is( + pg_temp.err($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000002', + 'person', 'Marie Durand') $$), + 'P0001|request_conflict||', 'the same request id with other content is refused' +); +select is((select count(*) from public.clients where display_name like 'Marie%'), 1::bigint, 'no divergent client was created'); + +-- --------------------------------------------------------------------------- +-- 5. Update, revision, archive +-- --------------------------------------------------------------------------- +select is( + public.update_client((select id from pg_temp.ids where key = 'marie'), 1, 'person', 'Marie Dupont', 'marie@example.test', + '+41791234567', null, null, '1800', 'Vevey', 'CH') ->> 'revision', '2', 'an update at the current revision gives revision 2'); +select is( + pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'marie'), 1, 'person', 'Marie D.', + null, null, null, null, null, null, null) $$), + 'P0001|conflict||', 'a stale revision is refused' +); +select is((pg_temp.client((select id from pg_temp.ids where key = 'marie'))).city, 'Vevey', 'the stale update overwrote nothing'); +select is( + pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'marie'), null, 'person', 'Marie D.', + null, null, null, null, null, null, null) $$), + 'P0001|conflict||', 'a missing revision is refused' +); +select is( + public.update_client((select id from pg_temp.ids where key = 'marie'), 2, 'person', 'Marie Dupont', 'MARIE@example.test', + '+41791234567', null, null, '1800', 'Vevey', 'CH') ->> 'revision', '2', 'an update that changes nothing keeps the revision'); +select is(pg_temp.audit_count((select id from pg_temp.ids where key = 'marie')), 2::bigint, 'and writes no audit row'); +select is( + pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'marie'), 2, 'person', '', + null, null, null, null, null, null, null) $$), + 'P0001|invalid_input||', 'an update breaking a rule is refused' +); +select is(public.set_client_archived((select id from pg_temp.ids where key = 'axb'), true) ->> 'revision', '2', 'archiving adds one revision'); +select ok((pg_temp.client((select id from pg_temp.ids where key = 'axb'))).archived_at is not null, 'the client is archived'); +select is(public.set_client_archived((select id from pg_temp.ids where key = 'axb'), true) ->> 'revision', '2', 'archiving again changes nothing'); +select is( + pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'axb'), 1, 'organization', 'AxB', + null, null, null, null, null, null, null) $$), + 'P0001|archived||', 'an archived client refuses edits, archived reported before the stale revision' +); +select is(pg_temp.err($$ select public.set_client_archived((select id from pg_temp.ids where key = 'axb'), null) $$), + 'P0001|invalid_input||', 'a missing archive state is refused'); + +-- --------------------------------------------------------------------------- +-- 6. Search: folding, escaping, phone formats, filters, keyset pages +-- --------------------------------------------------------------------------- +create function pg_temp.names(p_query text, p_archived boolean default false, p_size integer default 25, + p_after_key text default null, p_after_id uuid default null) returns text language sql +as $$ select coalesce(string_agg(s.display_name, '|' order by s.ord), '') + from public.search_clients(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), p_query, p_archived, p_size, + p_after_key, p_after_id) with ordinality s(id, kind, display_name, city, phone, email, + archived_at, name_key, ord) $$; +grant execute on function pg_temp.names(text, boolean, integer, text, uuid) to authenticated; + +select is(pg_temp.names(''), '100% Cheval|A_B Haras|Back\slash|Écurie du Lac|' || repeat('é', 120) || '|Mail|Marie Dupont', + 'an empty term lists the active clients in name order (archived left out)'); +select is(pg_temp.names('', true), 'AxB Haras', 'the archived filter lists the archived client only'); +select is(pg_temp.names('ECU'), 'Écurie du Lac', 'search folds case and accents'); +select is(pg_temp.names('vevey'), 'Marie Dupont', 'search reads the city'); +select is(pg_temp.names('EXAMPLE.test'), 'Marie Dupont', 'search reads the email'); +select is(pg_temp.names('_'), 'A_B Haras', 'an underscore is a character, not a wildcard'); +select is(pg_temp.names('%'), '100% Cheval', 'a percent sign is a character, not a wildcard'); +select is(pg_temp.names('\'), 'Back\slash', 'a backslash is a character'); +select is(pg_temp.names('06 12'), 'Écurie du Lac', 'a national phone fragment finds the number'); +select is(pg_temp.names('0612345678'), 'Écurie du Lac', 'a full national number finds it'); +select is(pg_temp.names('+33 6 12'), 'Écurie du Lac', 'an international fragment finds it'); +select is(pg_temp.names('061'), '', 'fewer than four digits is not a phone search'); +select is(pg_temp.names(repeat('z', 100)), '', 'a 100-character term is accepted'); +select is(pg_temp.names('', false, 2), '100% Cheval|A_B Haras', 'page 1 of 2'); +select is(pg_temp.names('', false, 2, (pg_temp.client((select id from pg_temp.ids where key = 'ab'))).name_key, + (select id from pg_temp.ids where key = 'ab')), 'Back\slash|Écurie du Lac', 'page 2 continues after the cursor, no gap, no repeat'); +select is(pg_temp.names('', false, 2, (pg_temp.client((select id from pg_temp.ids where key = 'marie'))).name_key, + (select id from pg_temp.ids where key = 'marie')), '', 'after the last client the page is empty'); +select is(pg_temp.err($$ select pg_temp.names(repeat('z', 101)) $$), 'P0001|invalid_input||', 'a 101-character term is refused'); +select is(pg_temp.err($$ select pg_temp.names('', false, 0) $$), 'P0001|invalid_input||', 'page size 0 is refused'); +select is(pg_temp.err($$ select pg_temp.names('', false, 101) $$), 'P0001|invalid_input||', 'page size 101 is refused'); +select is(pg_temp.err($$ select pg_temp.names('', false, 25, 'a') $$), 'P0001|invalid_input||', 'a cursor without its id is refused'); +select is(pg_temp.err($$ select pg_temp.names('', null) $$), 'P0001|invalid_input||', 'a missing archive filter is refused'); + +-- Restore: editable again, back in the default list. +select is(public.set_client_archived((select id from pg_temp.ids where key = 'axb'), false) ->> 'revision', '3', 'restoring adds one revision'); +select is(public.update_client((select id from pg_temp.ids where key = 'axb'), 3, 'organization', 'AxB Haras', null, null, + null, null, null, 'Annecy', null) ->> 'revision', '4', 'a restored client is editable'); + +-- D creates a client while active (used after its deactivation). +select pg_temp.act_as('60000000-0000-0000-0000-00000000000d'); +insert into pg_temp.ids values ('dave', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000d'), + gen_random_uuid(), 'person', 'Client de Dave') ->> 'id')::uuid); +reset role; +update public.profiles set active = false where id = '60000000-0000-0000-0000-00000000000d'; + +-- --------------------------------------------------------------------------- +-- 7. Isolation: the same not_found for a foreign and an unknown id +-- --------------------------------------------------------------------------- +set local role authenticated; +select pg_temp.act_as('60000000-0000-0000-0000-00000000000b'); +select is((select count(*) from public.clients), 0::bigint, 'B reads no client'); +select is((select count(*) from public.clients where id = (select id from pg_temp.ids where key = 'lac')), 0::bigint, + 'B naming a client of A reads nothing'); +select is((select count(*) from public.search_clients(pg_temp.ws('60000000-0000-0000-0000-00000000000a'))), 0::bigint, + 'B searching the workspace of A finds nothing'); +select is(pg_temp.err($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), gen_random_uuid(), 'person', 'X') $$), + pg_temp.err($$ select public.create_client(gen_random_uuid(), gen_random_uuid(), 'person', 'X') $$), + 'B creating in the workspace of A gets the error of an unknown workspace'); +select is(pg_temp.err($$ select public.create_client(gen_random_uuid(), gen_random_uuid(), 'person', 'X') $$), + '42501|not_found||', 'that error is 42501 not_found, no detail, no hint'); +select is(pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'lac'), 1, 'person', 'X', null, null, null, null, null, null, null) $$), + pg_temp.err($$ select public.update_client(gen_random_uuid(), 1, 'person', 'X', null, null, null, null, null, null, null) $$), + 'B updating a client of A gets the error of an unknown client'); +select is(pg_temp.err($$ select public.set_client_archived((select id from pg_temp.ids where key = 'lac'), true) $$), + '42501|not_found||', 'B archiving a client of A gets not_found'); +select is(pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'lac'), 1, 'person', '', null, null, null, null, null, null, null) $$), + '42501|not_found||', 'invalid content on a foreign id still answers not_found (authorisation first)'); +select is(pg_temp.denial($$ insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest) + values (pg_temp.ws('60000000-0000-0000-0000-00000000000b'), 'person', 'Direct', gen_random_uuid(), '\x00') $$), + '42501|permission denied for table clients', 'a direct insert is refused by privilege'); +select is(pg_temp.denial($$ update public.clients set display_name = 'Direct' $$), + '42501|permission denied for table clients', 'a direct update is refused by privilege'); +select is(pg_temp.denial($$ delete from public.clients $$), + '42501|permission denied for table clients', 'a direct delete is refused by privilege'); + +select pg_temp.act_as('60000000-0000-0000-0000-00000000000c'); +select is((select count(*) from public.clients), 0::bigint, 'C (unconfirmed) reads no client'); +select is(pg_temp.err($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000c'), gen_random_uuid(), 'person', 'X') $$), + '42501|not_found||', 'C cannot create, even in its own workspace'); + +select pg_temp.act_as('60000000-0000-0000-0000-00000000000d'); +select is((select count(*) from public.clients), 0::bigint, 'D (deactivated) no longer reads its own client'); +select is((select count(*) from public.search_clients(pg_temp.ws('60000000-0000-0000-0000-00000000000d'))), 0::bigint, + 'D finds nothing through search'); +select is(pg_temp.err($$ select public.set_client_archived((select id from pg_temp.ids where key = 'dave'), true) $$), + '42501|not_found||', 'D cannot write its own client'); + +select pg_temp.act_as('60000000-0000-0000-0000-000000000005'); +select is((select count(*) from public.clients), 0::bigint, 'S (platform owner) reads no client: no platform-role branch'); +select is(pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'lac'), 1, 'person', 'X', null, null, null, null, null, null, null) $$), + '42501|not_found||', 'S cannot write a client of A'); +reset role; + +set local role anon; +select is(pg_temp.denial($$ select id from public.clients $$), '42501|permission denied for table clients', 'anon cannot read clients'); +select is(pg_temp.err($$ select public.create_client(gen_random_uuid(), gen_random_uuid(), 'person', 'X') $$), + '42501|permission denied for function create_client||', 'anon cannot execute create_client'); +select is(pg_temp.err($$ select * from public.search_clients(gen_random_uuid()) $$), + '42501|permission denied for function search_clients||', 'anon cannot execute search_clients'); +reset role; +set local role service_role; +select is(pg_temp.denial($$ select id from public.clients $$), '42501|permission denied for table clients', + 'service_role cannot read clients despite BYPASSRLS'); +select is(pg_temp.err($$ select public.update_client(gen_random_uuid(), 1, 'person', 'X', null, null, null, null, null, null, null) $$), + '42501|permission denied for function update_client||', 'service_role cannot execute update_client'); +select is(pg_temp.err($$ select private.consume_write_budget(gen_random_uuid()) $$), + '42501|permission denied for function consume_write_budget||', 'service_role cannot touch the budget'); +reset role; +set local role authenticated; +select pg_temp.act_as('60000000-0000-0000-0000-00000000000a'); +select is(pg_temp.err($$ select private.consume_write_budget(pg_temp.ws('60000000-0000-0000-0000-00000000000a')) $$), + '42501|permission denied for function consume_write_budget||', 'A cannot call the budget directly'); +select is(pg_temp.err($$ select private.is_clean_text('x', 1) $$), + '42501|permission denied for function is_clean_text||', 'A cannot call the text rule directly'); +reset role; + +-- --------------------------------------------------------------------------- +-- 8. Write budget per workspace (fixed UTC windows), refused writes not counted +-- --------------------------------------------------------------------------- +insert into private.workspace_write_budgets values + (pg_temp.ws('60000000-0000-0000-0000-00000000000f'), date_trunc('hour', now(), 'UTC'), 999, date_trunc('day', now(), 'UTC'), 999); +set local role authenticated; +select pg_temp.act_as('60000000-0000-0000-0000-00000000000f'); +insert into pg_temp.ids values ('f1', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000f'), + '62000000-0000-0000-0000-000000000001', 'person', 'Budget One') ->> 'id')::uuid); +select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000f')), '1000/1000', 'the 1 000th write of the hour passes'); +select is(pg_temp.err($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000f'), gen_random_uuid(), 'person', 'Budget Two') $$), + 'P0001|rate_limited||', 'the 1 001st write of the hour is refused'); +select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000f')), '1000/1000', 'the refused write consumed nothing'); +select is((public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000f'), '62000000-0000-0000-0000-000000000001', + 'person', 'Budget One') ->> 'id')::uuid, (select id from pg_temp.ids where key = 'f1'), 'a replay at the limit still answers'); +select is(public.set_client_archived((select id from pg_temp.ids where key = 'f1'), false) ->> 'revision', '1', + 'a no-op at the limit still answers'); +select is(pg_temp.err($$ select public.set_client_archived((select id from pg_temp.ids where key = 'f1'), true) $$), + 'P0001|rate_limited||', 'an archive at the limit is refused'); +reset role; +update private.workspace_write_budgets set hour_start = hour_start - interval '1 hour' +where workspace_id = pg_temp.ws('60000000-0000-0000-0000-00000000000f'); +set local role authenticated; +select pg_temp.act_as('60000000-0000-0000-0000-00000000000f'); +select lives_ok($$ select public.set_client_archived((select id from pg_temp.ids where key = 'f1'), true) $$, + 'a new UTC hour restarts the hourly count'); +select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000f')), '1/1001', 'hour restarted at 1, the day keeps counting'); +reset role; +update private.workspace_write_budgets set day_count = 5000 where workspace_id = pg_temp.ws('60000000-0000-0000-0000-00000000000f'); +set local role authenticated; +select pg_temp.act_as('60000000-0000-0000-0000-00000000000f'); +select is(pg_temp.err($$ select public.set_client_archived((select id from pg_temp.ids where key = 'f1'), false) $$), + 'P0001|rate_limited||', 'the 5 001st write of the UTC day is refused'); +select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000f')), '1/5000', 'and consumed nothing'); +select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000b')), 'none', 'the budget of another workspace is untouched'); +reset role; + +-- --------------------------------------------------------------------------- +-- 9. Cap: 20 000 clients per workspace +-- --------------------------------------------------------------------------- +insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest) +select pg_temp.ws('60000000-0000-0000-0000-00000000000e'), 'person', 'Cap ' || g, gen_random_uuid(), '\x00' +from generate_series(1, 19999) g; +set local role authenticated; +select pg_temp.act_as('60000000-0000-0000-0000-00000000000e'); +select lives_ok($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000e'), + '63000000-0000-0000-0000-000000000001', 'person', 'Cap last') $$, 'the 20 000th client is accepted'); +select is(pg_temp.err($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000e'), gen_random_uuid(), 'person', 'Cap over') $$), + 'P0001|limit_reached||', 'the 20 001st client is refused'); +select lives_ok($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000e'), + '63000000-0000-0000-0000-000000000001', 'person', 'Cap last') $$, 'a replay at the cap still answers'); +reset role; + +-- --------------------------------------------------------------------------- +-- 10. Audit: ids only, hidden from platform staff (N9) +-- --------------------------------------------------------------------------- +select is( + (select string_agg(action, ',' order by occurred_at, action) from audit.audit_logs + where resource_id = (select id from pg_temp.ids where key = 'axb')), + 'client.archived,client.created,client.restored,client.updated', + 'each write of a client leaves one audit row' +); +select is( + (select count(*) from audit.audit_logs a join pg_temp.ids i on i.id = a.resource_id + where a.metadata <> jsonb_build_object('workspace_id', pg_temp.ws('60000000-0000-0000-0000-00000000000a')) + and i.key in ('lac', 'marie', 'ab', 'axb', 'pct', 'bsl')), + 0::bigint, 'audit metadata is the workspace id only' +); +select is( + (select count(*) from audit.audit_logs a join pg_temp.ids i on i.id = a.resource_id + where a.actor_user_id is distinct from '60000000-0000-0000-0000-00000000000a' and i.key in ('lac', 'marie', 'axb')), + 0::bigint, 'the actor is the caller' +); +select is( + (select count(*) from audit.audit_logs where action like 'client.%' + and (metadata::text ~* '(lac|marie|dupont|vevey|example|cheval|haras)' or correlation_id is not null)), + 0::bigint, 'no name, contact or place in the audit rows' +); +set local role authenticated; +select pg_temp.act_as('60000000-0000-0000-0000-000000000005'); +select is((select count(*) from audit.audit_logs where action like 'client.%'), 0::bigint, 'S reads no client audit row'); +select ok((select count(*) from audit.audit_logs where action like 'platform_role.%') > 0, 'S still reads platform audit rows'); +reset role; + +-- --------------------------------------------------------------------------- +-- 11. Integrity and account deletion (D9a) +-- --------------------------------------------------------------------------- +select throws_ok( + $$ insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest) + values (gen_random_uuid(), 'person', 'Orphan', gen_random_uuid(), '\x00') $$, + '23503', null, 'a client of an unknown workspace is refused by the foreign key' +); +select throws_ok( + $$ insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest) + values (pg_temp.ws('60000000-0000-0000-0000-00000000000a'), 'person', 'Twice', '61000000-0000-0000-0000-000000000001', '\x00') $$, + '23505', null, 'a request id is unique per workspace' +); +select throws_ok( + $$ delete from auth.users where id = '60000000-0000-0000-0000-00000000000a' $$, + '23503', null, 'an account whose workspace holds clients cannot be deleted (D9a)' +); +select is((select count(*) from public.clients where workspace_id = pg_temp.ws('60000000-0000-0000-0000-00000000000a')), + 8::bigint, 'its clients are intact'); +select lives_ok($$ delete from auth.users where id = '60000000-0000-0000-0000-000000000010' $$, + 'an account without clients is deleted as before'); + +select * from finish(); +rollback;