From d05f75da84f18a27bbaf49a4ec29588ad3416323 Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 28 Oct 2026 18:14:09 +0100 Subject: [PATCH] fix(supabase): V1-2.1 audit M1 M2 M3 and LOW fixes in M5 Approval needs an active sheet (lock sheet, version, round); a base only from a still-published round version; rights.mfa before rights.capability; withdrawal of a published round refused; approver separation at publish; deprecate and working copy serialised; closed codes; append-only acks; upload policy bound to the registering editor. pgTAP 017-019 added. --- packages/supabase/src/sheets.ts | 5 + packages/supabase/tests/db/supabase-shim.sql | 5 +- packages/supabase/tests/sheets.test.ts | 44 ++ .../20261028110000_sheet_review_workflow.sql | 432 ++++++++++---- supabase/tests/006_sheet_asset_storage.sql | 45 +- supabase/tests/015_catalog_access.sql | 5 +- supabase/tests/016_sheet_review_workflow.sql | 24 +- supabase/tests/017_sheet_review_rules.sql | 564 ++++++++++++++++++ supabase/tests/018_sheet_access_matrix.sql | 295 +++++++++ supabase/tests/019_sheet_immutability.sql | 185 ++++++ 10 files changed, 1477 insertions(+), 127 deletions(-) create mode 100644 packages/supabase/tests/sheets.test.ts create mode 100644 supabase/tests/017_sheet_review_rules.sql create mode 100644 supabase/tests/018_sheet_access_matrix.sql create mode 100644 supabase/tests/019_sheet_immutability.sql diff --git a/packages/supabase/src/sheets.ts b/packages/supabase/src/sheets.ts index e62b5cb1..62f7e0e1 100644 --- a/packages/supabase/src/sheets.ts +++ b/packages/supabase/src/sheets.ts @@ -47,7 +47,9 @@ export const SHEET_FAILURE_KINDS = [ 'draft.unchanged', 'draft.frozen', 'draft.not_a_draft', + 'draft.exists', 'document.shape', + 'document.schema_version', 'document.species', 'document.too_large', // sheet and species state @@ -57,6 +59,7 @@ export const SHEET_FAILURE_KINDS = [ 'sheet.published_history', 'sheet.historical_read_only', 'sheet.species_invalid', + 'sheet.slug_taken', 'species.exists', 'species.not_active', 'species.not_inactive', @@ -83,9 +86,11 @@ export const SHEET_FAILURE_KINDS = [ 'publish.species.other', 'publish.drawing.missing', 'publish.drawing.changed', + 'view.asset.unknown', // uploads and working copy 'upload_missing', 'size_mismatch', + 'asset.referenced', 'working_copy.source_invalid', 'working_copy.exists', 'working_copy.assets_missing', diff --git a/packages/supabase/tests/db/supabase-shim.sql b/packages/supabase/tests/db/supabase-shim.sql index 2aee3e7e..c1f04281 100644 --- a/packages/supabase/tests/db/supabase-shim.sql +++ b/packages/supabase/tests/db/supabase-shim.sql @@ -28,8 +28,9 @@ create table auth.users ( -- MFA state read by the V1-2 assurance checks (private.has_aal2_session, -- private.has_verified_totp). Types, names and NOT NULL columns as in GoTrue --- v2.197.0 (checked on the pinned image by tests/sandbox/mfa.sandbox.ts); --- the columns the migrations never read are left out. +-- v2.197.0 (compared with the pinned image by +-- tests/sandbox/shim-columns.sandbox.ts); the columns the migrations never read +-- are left out. create type auth.aal_level as enum ('aal1', 'aal2', 'aal3'); create type auth.factor_type as enum ('totp', 'webauthn', 'phone', 'recovery_code'); create type auth.factor_status as enum ('unverified', 'verified'); diff --git a/packages/supabase/tests/sheets.test.ts b/packages/supabase/tests/sheets.test.ts new file mode 100644 index 00000000..290f9e15 --- /dev/null +++ b/packages/supabase/tests/sheets.test.ts @@ -0,0 +1,44 @@ +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { SHEET_FAILURE_KINDS, SheetFailure, classifySheetError } from '../src/sheets' +import { migrationsDir } from './db/harness' + +/** + * The closed failure kinds of the sheet workflow (V1-2.1). The census reads + * every closed code M4 and M5 raise (`raise exception ''`, a lowercase + * dotted word; free-text messages are not codes) so a code added on the server + * can never reach a page as `unavailable` for want of a kind. + */ +const SHEET_MIGRATIONS = [ + '20261028100000_sheet_access_hardening.sql', + '20261028110000_sheet_review_workflow.sql', +] + +async function raisedCodes(): Promise { + const codes = new Set() + for (const file of SHEET_MIGRATIONS) { + const sql = await readFile(join(migrationsDir, file), 'utf8') + for (const match of sql.matchAll(/raise exception '([a-z_]+(?:\.[a-z_]+)*)'/g)) + codes.add(match[1]) + } + return [...codes].sort() +} + +describe('sheet failure kinds', () => { + it('names every closed code the sheet migrations raise', async () => { + const kinds = new Set(SHEET_FAILURE_KINDS) + const codes = await raisedCodes() + expect(codes.length).toBeGreaterThan(50) + expect(codes.filter((code) => !kinds.has(code))).toEqual([]) + }) + + it('folds an answer into its kind and fails closed on anything else', () => { + expect(classifySheetError({ code: 'P0001', message: 'view.asset.unknown' })).toBe('view.asset.unknown') + expect(classifySheetError({ code: '42501', message: 'rights.mfa' })).toBe('rights.mfa') + expect(classifySheetError({ code: '40P01', message: 'deadlock detected' })).toBe('conflict_retry') + expect(classifySheetError({ code: '23505', message: 'duplicate key value' })).toBe('unavailable') + expect(classifySheetError({}, 401)).toBe('session_expired') + expect(classifySheetError(new TypeError('fetch failed'))).toBe('network') + expect(classifySheetError(new SheetFailure('draft.exists'))).toBe('draft.exists') + }) +}) diff --git a/supabase/migrations/20261028110000_sheet_review_workflow.sql b/supabase/migrations/20261028110000_sheet_review_workflow.sql index e8443b0f..bf323ddf 100644 --- a/supabase/migrations/20261028110000_sheet_review_workflow.sql +++ b/supabase/migrations/20261028110000_sheet_review_workflow.sql @@ -307,9 +307,11 @@ $$; -- =========================================================================== -- 4. Authoring helpers and RPCs -- =========================================================================== --- Require the sheet_editor capability at aal2 on an official, non-deleted --- sheet other than the historical one (writes), returning the actor. -create or replace function private.require_sheet_author(p_sheet_id uuid) +-- The calling session: an active account with a confirmed email, at aal2 +-- (contract §5.6, §6.7). Every catalogue RPC except the readers calls it +-- before any lookup or capability check, so an aal1 session gets one answer +-- (`rights.mfa`) whatever it asks for and whatever it holds. +create or replace function private.require_catalog_actor() returns uuid language plpgsql stable @@ -319,12 +321,50 @@ as $$ declare v_actor uuid := private.require_actor(); begin - if p_sheet_id = private.historical_sheet_id() then - raise exception 'sheet.historical_read_only' using errcode = '42501'; + if not private.has_mfa() then + raise exception 'rights.mfa' using errcode = '42501'; end if; + return v_actor; +end; +$$; + +-- The calling session holds one capability at aal2, returning the actor. +create or replace function private.require_capability(p_kind public.catalog_grant_kind) +returns uuid +language plpgsql +stable +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_catalog_actor(); +begin + if not private.grant_active(v_actor, p_kind) then + raise exception 'rights.capability' using errcode = '42501'; + end if; + return v_actor; +end; +$$; + +-- Require the sheet_editor capability at aal2 on an official, non-deleted +-- sheet other than the historical one (writes), returning the actor. The +-- capability is checked first, so only an editor learns a sheet is historical. +create or replace function private.require_sheet_author(p_sheet_id uuid) +returns uuid +language plpgsql +stable +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_catalog_actor(); +begin if not private.can_edit_sheet(v_actor, p_sheet_id) then raise exception 'rights.capability' using errcode = '42501'; end if; + if p_sheet_id = private.historical_sheet_id() then + raise exception 'sheet.historical_read_only' using errcode = '42501'; + end if; return v_actor; end; $$; @@ -338,9 +378,9 @@ security definer set search_path = '' as $$ declare - v_actor uuid := private.require_actor(); + v_actor uuid := private.require_catalog_actor(); begin - if not (private.caller_has('sheet_publisher') and exists ( + if not (private.grant_active(v_actor, 'sheet_publisher') and exists ( select 1 from public.anatomical_sheets s where s.id = p_sheet_id and s.is_official and s.status <> 'deleted' )) then @@ -350,6 +390,65 @@ begin end; $$; +-- The structural guards a stored document passes at creation, save and +-- working copy (contract §12.2): an object whose id-bearing collections are +-- arrays, schema version 2, at most 2 MiB serialised. The table's own size +-- CHECK (`pg_column_size(content)`, base migration) measures the binary jsonb, +-- which a document of many small objects makes larger than its text: both +-- measures are checked here, so either limit answers the closed code rather +-- than a raw constraint error. +create or replace function private.check_document_structure(p_doc jsonb) +returns void +language plpgsql +immutable +set search_path = '' +as $$ +begin + if not private.sheet_document_has_shape(p_doc) then + raise exception 'document.shape' using errcode = '23514'; + end if; + if (p_doc -> 'schema_version') is distinct from '2'::jsonb then + raise exception 'document.schema_version' using errcode = '23514'; + end if; + if octet_length(p_doc::text) > 2097152 or pg_column_size(p_doc) > 2097152 then + raise exception 'document.too_large' using errcode = '23514'; + end if; +end; +$$; + +-- A new official sheet row (creation and working copy). A slug outside the +-- table's format is invalid input; one already used by a non-deleted official +-- sheet answers `sheet.slug_taken`, the race included (unique index). +create or replace function private.insert_official_sheet( + p_species text, + p_name text, + p_slug text, + p_description text, + p_source uuid +) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_sheet uuid; +begin + if p_slug is null or p_slug !~ '^[a-z0-9][a-z0-9-]{1,79}$' then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + begin + insert into public.anatomical_sheets (species_id, name, slug, description, creator_user_id, is_official, + visibility, working_copy_source_version_id) + values (p_species, p_name, p_slug, p_description, null, true, 'private', p_source) + returning id into v_sheet; + exception when unique_violation then + raise exception 'sheet.slug_taken' using errcode = 'P0001'; + end; + return v_sheet; +end; +$$; + -- Create an official sheet and its draft v1 from a core-built document. create or replace function public.create_official_sheet( slug text, @@ -363,18 +462,13 @@ set search_path = '' as $$ #variable_conflict use_column declare - v_actor uuid := private.require_actor(); + v_actor uuid := private.require_capability('sheet_editor'); v_species text := document ->> 'species_id'; v_name text; v_description text; v_sheet uuid; begin - if not private.caller_has('sheet_editor') then - raise exception 'rights.capability' using errcode = '42501'; - end if; - if not private.sheet_document_has_shape(document) then - raise exception 'document.shape' using errcode = '23514'; - end if; + perform private.check_document_structure(document); v_name := left(coalesce(document -> 'name' ->> 'fr', document -> 'name' ->> 'en', 'Sans nom'), 120); v_description := left(coalesce(document -> 'description' ->> 'fr', ''), 2000); -- An official sheet accepts an active or inactive species, never `other` (§7.2). @@ -384,9 +478,7 @@ begin end if; perform private.consume_catalog_write_budget(v_actor); - insert into public.anatomical_sheets (species_id, name, slug, description, creator_user_id, is_official, visibility) - values (v_species, v_name, slug, v_description, null, true, 'private') - returning id into v_sheet; + v_sheet := private.insert_official_sheet(v_species, v_name, create_official_sheet.slug, v_description, null); perform private.log_event( v_actor, 'anatomical_sheet.created', 'anatomical_sheet', v_sheet, null, null, @@ -427,10 +519,17 @@ begin if v_source.id is null then raise exception 'sheet.no_source' using errcode = 'P0002'; end if; + if exists (select 1 from public.anatomical_sheet_versions v + where v.sheet_id = create_sheet_draft.sheet_id and v.status = 'draft') then + raise exception 'draft.exists' using errcode = 'P0001'; + end if; perform private.consume_catalog_write_budget(v_actor); - -- Base only from a version published through a V1-2 round (§6.2). - v_base := case when v_source.published_review_id is not null then v_source.id else null end; + -- Base only from a version still `published` that was published through a + -- V1-2 round (§6.2): a deprecated source gives no base, so every group of + -- the new draft is to cover again. + v_base := case when v_source.status = 'published' and v_source.published_review_id is not null + then v_source.id end; v_draft := private.insert_sheet_draft(v_actor, sheet_id, v_source.content, change_note); update public.anatomical_sheet_versions set source_version_id = v_base where id = v_draft; return v_draft; @@ -452,14 +551,14 @@ set search_path = '' as $$ #variable_conflict use_column declare + v_actor uuid := private.require_catalog_actor(); v_row public.anatomical_sheet_versions%rowtype; - v_actor uuid; begin select v.* into v_row from public.anatomical_sheet_versions v where v.id = save_sheet_draft.version_id for update; if v_row.id is null then raise exception 'not_found' using errcode = '42501'; end if; - v_actor := private.require_sheet_author(v_row.sheet_id); + perform private.require_sheet_author(v_row.sheet_id); if v_row.status <> 'draft' then raise exception 'draft.not_a_draft' using errcode = '55000'; end if; @@ -474,15 +573,10 @@ begin if save_sheet_draft.expected_revision is distinct from v_row.revision then raise exception 'draft_conflict' using errcode = 'P0001'; end if; - if not private.sheet_document_has_shape(document) then - raise exception 'document.shape' using errcode = '23514'; - end if; + perform private.check_document_structure(document); if (document ->> 'species_id') is distinct from (select species_id from public.anatomical_sheets where id = v_row.sheet_id) then raise exception 'document.species' using errcode = '23514'; end if; - if octet_length(document::text) > 2097152 then - raise exception 'document.too_large' using errcode = '23514'; - end if; if document = v_row.content then raise exception 'draft.unchanged' using errcode = 'P0001'; end if; @@ -516,8 +610,8 @@ set search_path = '' as $$ #variable_conflict use_column declare + v_actor uuid := private.require_catalog_actor(); v_row public.anatomical_sheet_versions%rowtype; - v_actor uuid; v_round integer; v_id uuid; begin @@ -525,7 +619,7 @@ begin if v_row.id is null then raise exception 'not_found' using errcode = '42501'; end if; - v_actor := private.require_sheet_author(v_row.sheet_id); + perform private.require_sheet_author(v_row.sheet_id); if v_row.status <> 'draft' then raise exception 'draft.not_a_draft' using errcode = '55000'; end if; @@ -542,6 +636,11 @@ begin if char_length(note) > 1000 then raise exception 'invalid_input' using errcode = 'P0001'; end if; + -- Every drawing id of the document is registered for the sheet (§12.2, + -- kept at submission and publication). + if cardinality(private.sheet_document_unknown_assets(v_row.sheet_id, v_row.content)) > 0 then + raise exception 'view.asset.unknown' using errcode = 'P0001'; + end if; perform private.consume_catalog_write_budget(v_actor); select coalesce(max(round), 0) + 1 into v_round @@ -561,7 +660,9 @@ begin end; $$; --- Withdraw a round in verifying, open or approved; the draft unfreezes. +-- Withdraw a round of a draft in verifying, open or approved; the draft +-- unfreezes. The round of a published version stays approved (§6.1): it is +-- the version's review link and never withdrawn. create or replace function public.withdraw_sheet_review(review_id uuid, note text default null) returns uuid language plpgsql @@ -571,22 +672,33 @@ set search_path = '' as $$ #variable_conflict use_column declare + v_actor uuid := private.require_catalog_actor(); v_review public.anatomical_sheet_reviews%rowtype; + v_version public.anatomical_sheet_versions%rowtype; v_sheet uuid; - v_actor uuid; begin - select r.* into v_review from public.anatomical_sheet_reviews r where r.id = withdraw_sheet_review.review_id for update; - if v_review.id is null then + select r.version_id into v_review.version_id from public.anatomical_sheet_reviews r + where r.id = withdraw_sheet_review.review_id; + if v_review.version_id is null then raise exception 'not_found' using errcode = '42501'; end if; - select sheet_id into v_sheet from public.anatomical_sheet_versions where id = v_review.version_id; - v_actor := private.require_sheet_author(v_sheet); + -- Lock order version, then round (§6.1): a publication holding the version + -- either completes first (the version is then no draft) or sees the round + -- withdrawn. + select v.* into v_version from public.anatomical_sheet_versions v where v.id = v_review.version_id for share; + v_sheet := v_version.sheet_id; + perform private.require_sheet_author(v_sheet); + select r.* into v_review from public.anatomical_sheet_reviews r where r.id = withdraw_sheet_review.review_id for update; + if v_version.status <> 'draft' then + raise exception 'draft.not_a_draft' using errcode = '55000'; + end if; if v_review.status not in ('verifying', 'open', 'approved') then raise exception 'round.terminal' using errcode = '55000'; end if; if char_length(note) > 1000 then raise exception 'invalid_input' using errcode = 'P0001'; end if; + perform private.consume_catalog_write_budget(v_actor); update public.anatomical_sheet_reviews set status = 'withdrawn', withdrawn_by = v_actor, withdrawn_at = now(), withdrawal_note = note @@ -613,7 +725,7 @@ set search_path = '' as $$ #variable_conflict use_column declare - v_actor uuid := private.require_actor(); + v_actor uuid := private.require_catalog_actor(); v_review public.anatomical_sheet_reviews%rowtype; v_sheet uuid; v_id uuid; @@ -671,15 +783,12 @@ set search_path = '' as $$ #variable_conflict use_column declare - v_actor uuid := private.require_actor(); + v_actor uuid := private.require_capability('sheet_reviewer'); v_review public.anatomical_sheet_reviews%rowtype; v_sheet uuid; v_group jsonb; v_id uuid; begin - if not private.caller_has('sheet_reviewer') then - raise exception 'rights.capability' using errcode = '42501'; - end if; select r.* into v_review from public.anatomical_sheet_reviews r where r.id = acknowledge_sheet_review_group.review_id for update; if v_review.id is null then raise exception 'not_found' using errcode = '42501'; @@ -705,10 +814,18 @@ begin end if; perform private.consume_catalog_write_budget(v_actor); + -- Append-only (§6.3): acknowledging a group twice in the same round keeps the + -- first row (the verdict, hence the digest, is fixed while the round is open). insert into public.anatomical_sheet_review_acknowledgments (review_id, group_key, group_digest, reviewer) values (acknowledge_sheet_review_group.review_id, group_key, group_digest, v_actor) - on conflict (review_id, group_key, reviewer) do update set group_digest = excluded.group_digest, created_at = now() + on conflict (review_id, group_key, reviewer) do nothing returning id into v_id; + if v_id is null then + select a.id into v_id from public.anatomical_sheet_review_acknowledgments a + where a.review_id = acknowledge_sheet_review_group.review_id + and a.group_key = acknowledge_sheet_review_group.group_key and a.reviewer = v_actor; + return v_id; + end if; perform private.log_event( v_actor, 'anatomical_sheet_review.acknowledged', 'anatomical_sheet_review', v_review.id, null, null, jsonb_build_object('sheet_id', v_sheet, 'group_key', group_key) @@ -785,23 +902,27 @@ set search_path = '' as $$ #variable_conflict use_column declare - v_actor uuid := private.require_actor(); + v_actor uuid := private.require_capability('sheet_reviewer'); v_review public.anatomical_sheet_reviews%rowtype; v_version public.anatomical_sheet_versions%rowtype; + v_sheet public.anatomical_sheets%rowtype; v_uncovered text[]; begin - if not private.caller_has('sheet_reviewer') then - raise exception 'rights.capability' using errcode = '42501'; - end if; if char_length(note) not between 1 and 4000 then raise exception 'invalid_input' using errcode = 'P0001'; end if; - -- Lock order version then round (contract §6.1), matching publish, so the - -- two never deadlock. - select version_id into v_version.id from public.anatomical_sheet_reviews where id = decide_sheet_review.review_id; + -- Lock order sheet, then version, then round (contract §6.1), as publish + -- does. The sheet is share-locked: an archive (which updates the row) waits + -- for the decision or is seen by it, so no approval lands on a sheet archived + -- in the meantime (§6.7, M1). + select v.sheet_id, v.id into v_sheet.id, v_version.id + from public.anatomical_sheet_reviews r + join public.anatomical_sheet_versions v on v.id = r.version_id + where r.id = decide_sheet_review.review_id; if v_version.id is null then raise exception 'not_found' using errcode = '42501'; end if; + select s.* into v_sheet from public.anatomical_sheets s where s.id = v_sheet.id for share; select v.* into v_version from public.anatomical_sheet_versions v where v.id = v_version.id for update; select r.* into v_review from public.anatomical_sheet_reviews r where r.id = decide_sheet_review.review_id for update; if v_review.status <> 'open' then @@ -813,9 +934,19 @@ begin perform private.consume_catalog_write_budget(v_actor); if approve then + -- Sheet active, official, other than the historical sheet (§6.7). + if v_sheet.status <> 'active' then + raise exception 'sheet.inactive' using errcode = '55000'; + end if; + if v_sheet.id = private.historical_sheet_id() then + raise exception 'sheet.historical_read_only' using errcode = '42501'; + end if; -- Publishable content: verdict present on the current revision, no -- to_confirm / inherited element, groups covered. - if v_review.verdict is null or v_review.revision <> v_version.revision then + if v_review.verdict is null then + raise exception 'verdict.missing' using errcode = 'P0001'; + end if; + if v_review.revision <> v_version.revision then raise exception 'verdict.stale' using errcode = 'P0001'; end if; if private.sheet_has_to_confirm(v_version.content) then @@ -871,6 +1002,7 @@ declare v_name text; v_description text; begin + perform private.require_catalog_actor(); -- Lock order sheet, then version, then round (contract §6.1). select v.sheet_id, v.id into v_sheet.id, v_version.id from public.anatomical_sheet_versions v @@ -899,9 +1031,11 @@ begin if v_review.verdict is null then raise exception 'verdict.missing' using errcode = 'P0001'; end if; - -- The approving reviewer's grant must still be active at publication (§5.2, - -- §6.7): a revoked reviewer's approval does not carry a publication. - if not private.grant_active(v_review.decided_by, 'sheet_reviewer') then + -- The approver is outside the round's authors and its reviewer grant is + -- still active at publication (§5.2, §6.7): a revoked reviewer's approval + -- does not carry a publication. + if v_review.decided_by is null or v_review.authors @> array[v_review.decided_by] + or not private.grant_active(v_review.decided_by, 'sheet_reviewer') then raise exception 'publish.approval.invalid' using errcode = 'P0001'; end if; -- Species active and not `other` (§6.7). @@ -925,7 +1059,11 @@ begin if coalesce(array_length(private.uncovered_review_groups(v_review.id), 1), 0) > 0 then raise exception 'review.groups.uncovered' using errcode = 'P0001'; end if; - -- Each referenced drawing confirmed, size and sha256 equal to the verdict's. + -- Every drawing id registered for the sheet (§12.2), each referenced + -- drawing confirmed, size and sha256 equal to the verdict's. + if cardinality(private.sheet_document_unknown_assets(v_version.sheet_id, v_version.content)) > 0 then + raise exception 'view.asset.unknown' using errcode = 'P0001'; + end if; if exists ( select 1 from unnest(private.sheet_document_asset_ids(v_version.content)) as ref where not exists ( @@ -950,6 +1088,7 @@ begin end if; v_name := left(coalesce(v_version.content -> 'name' ->> 'fr', v_sheet.name), 120); v_description := left(coalesce(v_version.content -> 'description' ->> 'fr', ''), 2000); + perform private.consume_catalog_write_budget(v_actor); update public.anatomical_sheet_versions set status = 'published', published_at = now(), published_by = v_actor, @@ -980,21 +1119,27 @@ set search_path = '' as $$ #variable_conflict use_column declare + v_actor uuid := private.require_catalog_actor(); v_version public.anatomical_sheet_versions%rowtype; - v_actor uuid; v_next uuid; begin if char_length(reason) > 500 then raise exception 'invalid_input' using errcode = 'P0001'; end if; - select v.* into v_version from public.anatomical_sheet_versions v where v.id = deprecate_sheet_version.version_id for update; - if v_version.id is null then + select v.sheet_id into v_version.sheet_id from public.anatomical_sheet_versions v where v.id = deprecate_sheet_version.version_id; + if v_version.sheet_id is null then raise exception 'not_found' using errcode = '42501'; end if; - v_actor := private.require_sheet_publisher(v_version.sheet_id); + perform private.require_sheet_publisher(v_version.sheet_id); + -- Lock order sheet, then version (§6.1). Two deprecations of the same sheet + -- are serialised on the sheet row, so each picks the next current version + -- from the other's committed state and never names a deprecated one. + perform 1 from public.anatomical_sheets s where s.id = v_version.sheet_id for update; + select v.* into v_version from public.anatomical_sheet_versions v where v.id = deprecate_sheet_version.version_id for update; if v_version.status <> 'published' then raise exception 'version.not_published' using errcode = '55000'; end if; + perform private.consume_catalog_write_budget(v_actor); update public.anatomical_sheet_versions set status = 'deprecated', deprecated_at = now(), deprecated_by = v_actor @@ -1038,6 +1183,7 @@ begin if v_status <> p_from then raise exception 'sheet.state' using errcode = '55000'; end if; + perform private.consume_catalog_write_budget(p_actor); update public.anatomical_sheets set status = p_to, archived_at = case when p_to = 'archived' then now() when p_to = 'active' then null else archived_at end, @@ -1062,6 +1208,9 @@ begin end; $$; +-- Restoring a working copy of the historical sheet keeps the single active +-- slot (§14.3): refused while another copy is active. The historical sheet +-- row is locked as in create_sheet_working_copy, so the two serialise. create or replace function public.restore_anatomical_sheet(sheet_id uuid) returns uuid language plpgsql @@ -1069,10 +1218,17 @@ volatile security definer set search_path = '' as $$ +#variable_conflict use_column declare v_actor uuid := private.require_sheet_publisher(sheet_id); begin - return private.set_sheet_status(v_actor, sheet_id, 'archived', 'active', 'anatomical_sheet.restored'); + if private.is_historical_working_copy(restore_anatomical_sheet.sheet_id) then + perform 1 from public.anatomical_sheets s where s.id = private.historical_sheet_id() for no key update; + if private.historical_working_copy_active(restore_anatomical_sheet.sheet_id) then + raise exception 'working_copy.exists' using errcode = 'P0001'; + end if; + end if; + return private.set_sheet_status(v_actor, restore_anatomical_sheet.sheet_id, 'archived', 'active', 'anatomical_sheet.restored'); end; $$; @@ -1114,17 +1270,18 @@ set search_path = '' as $$ #variable_conflict use_column declare + v_actor uuid := private.require_catalog_actor(); v_version public.anatomical_sheet_versions%rowtype; - v_actor uuid; begin - select v.* into v_version from public.anatomical_sheet_versions v where v.id = delete_sheet_version.version_id; + select v.* into v_version from public.anatomical_sheet_versions v where v.id = delete_sheet_version.version_id for update; if v_version.id is null then raise exception 'not_found' using errcode = '42501'; end if; - v_actor := private.require_sheet_author(v_version.sheet_id); + perform private.require_sheet_author(v_version.sheet_id); if exists (select 1 from public.anatomical_sheet_reviews r where r.version_id = v_version.id) then raise exception 'version.has_rounds' using errcode = '55000'; end if; + perform private.consume_catalog_write_budget(v_actor); delete from public.anatomical_sheet_versions where id = v_version.id; perform private.log_event( v_actor, 'anatomical_sheet_version.deleted', 'anatomical_sheet_version', v_version.id, null, null, @@ -1137,6 +1294,36 @@ $$; -- =========================================================================== -- 8. Equine working copy (contract §14.3) -- =========================================================================== +-- A sheet created as a working copy of a version of the historical sheet. +create or replace function private.is_historical_working_copy(p_sheet_id uuid) +returns boolean +language sql +stable +security definer +set search_path = '' +as $$ + select exists ( + select 1 from public.anatomical_sheets s + join public.anatomical_sheet_versions v on v.id = s.working_copy_source_version_id + where s.id = p_sheet_id and v.sheet_id = private.historical_sheet_id() + ); +$$; + +-- An active working copy of the historical sheet other than p_except. +create or replace function private.historical_working_copy_active(p_except uuid) +returns boolean +language sql +stable +security definer +set search_path = '' +as $$ + select exists ( + select 1 from public.anatomical_sheets s + where s.status = 'active' and s.id is distinct from p_except + and private.is_historical_working_copy(s.id) + ); +$$; + create or replace function public.create_sheet_working_copy(source_version_id uuid, slug text) returns uuid language plpgsql @@ -1146,7 +1333,7 @@ set search_path = '' as $$ #variable_conflict use_column declare - v_actor uuid := private.require_actor(); + v_actor uuid := private.require_capability('sheet_editor'); v_source public.anatomical_sheet_versions%rowtype; v_sheet uuid; v_draft uuid; @@ -1154,22 +1341,16 @@ declare v_new uuid; r record; begin - if not private.caller_has('sheet_editor') then - raise exception 'rights.capability' using errcode = '42501'; - end if; select v.* into v_source from public.anatomical_sheet_versions v where v.id = create_sheet_working_copy.source_version_id; -- Source restricted to the historical sheet, and no other (§14.3). if v_source.id is null or v_source.sheet_id <> private.historical_sheet_id() then raise exception 'working_copy.source_invalid' using errcode = 'P0001'; end if; - -- At most one active working copy of the historical sheet. - if exists ( - select 1 from public.anatomical_sheets s - where s.working_copy_source_version_id is not null and s.status = 'active' - and s.id <> private.historical_sheet_id() - and exists (select 1 from public.anatomical_sheet_versions vv - where vv.id = s.working_copy_source_version_id and vv.sheet_id = private.historical_sheet_id()) - ) then + -- At most one active working copy of the historical sheet. Two concurrent + -- creations (or a creation and a restore) serialise on the historical sheet + -- row; the lock writes nothing, so its protection trigger never fires. + perform 1 from public.anatomical_sheets s where s.id = private.historical_sheet_id() for no key update; + if private.historical_working_copy_active(null) then raise exception 'working_copy.exists' using errcode = 'P0001'; end if; -- Every referenced drawing uploaded, with an object of the recorded size. @@ -1187,11 +1368,10 @@ begin end if; perform private.consume_catalog_write_budget(v_actor); - insert into public.anatomical_sheets (species_id, name, slug, description, creator_user_id, is_official, visibility, working_copy_source_version_id) - select species_id, left(coalesce(v_source.content -> 'name' ->> 'fr', name), 120), create_sheet_working_copy.slug, - description, null, true, 'private', v_source.id - from public.anatomical_sheets where id = v_source.sheet_id - returning id into v_sheet; + select private.insert_official_sheet(s.species_id, left(coalesce(v_source.content -> 'name' ->> 'fr', s.name), 120), + create_sheet_working_copy.slug, s.description, v_source.id) + into v_sheet + from public.anatomical_sheets s where s.id = v_source.sheet_id; -- Register the source drawings for the new sheet (same bytes, shared object). for r in @@ -1206,9 +1386,7 @@ begin end loop; -- Size checked as in §6.2: the remapped document must fit the 2 MiB cap. - if octet_length(private.remap_document_assets(v_source.content, v_map)::text) > 2097152 then - raise exception 'document.too_large' using errcode = '23514'; - end if; + perform private.check_document_structure(private.remap_document_assets(v_source.content, v_map)); v_draft := private.insert_sheet_draft( v_actor, v_sheet, private.remap_document_assets(v_source.content, v_map), 'Copie de travail de la fiche historique (version ' || v_source.version_number || ', révision ' || v_source.revision || ')' @@ -1234,11 +1412,8 @@ set search_path = '' as $$ #variable_conflict use_column declare - v_actor uuid := private.require_actor(); + v_actor uuid := private.require_capability('sheet_editor'); begin - if not private.caller_has('sheet_editor') then - raise exception 'rights.capability' using errcode = '42501'; - end if; if create_species.id is null or create_species.id !~ '^[a-z0-9][a-z0-9_-]{0,63}$' or create_species.id = 'other' or char_length(name_fr) not between 1 and 80 or char_length(name_en) not between 1 and 80 then raise exception 'invalid_input' using errcode = 'P0001'; @@ -1264,11 +1439,8 @@ set search_path = '' as $$ #variable_conflict use_column declare - v_actor uuid := private.require_actor(); + v_actor uuid := private.require_capability('sheet_editor'); begin - if not private.caller_has('sheet_editor') then - raise exception 'rights.capability' using errcode = '42501'; - end if; if char_length(name_fr) not between 1 and 80 or char_length(name_en) not between 1 and 80 then raise exception 'invalid_input' using errcode = 'P0001'; end if; @@ -1293,15 +1465,16 @@ set search_path = '' as $$ #variable_conflict use_column declare - v_actor uuid := private.require_actor(); + v_actor uuid := private.require_catalog_actor(); begin - if not (private.has_mfa() and private.is_platform_owner(v_actor)) then + if not private.is_platform_owner(v_actor) then raise exception 'rights.owner' using errcode = '42501'; end if; perform 1 from public.species s where s.id = activate_species.id for update; if not found then raise exception 'not_found' using errcode = '42501'; end if; + perform private.consume_catalog_write_budget(v_actor); update public.species s set active = true where s.id = activate_species.id and not s.active; perform private.log_event(v_actor, 'species.activated', 'species', null, null, null, jsonb_build_object('id', activate_species.id)); return activate_species.id; @@ -1317,9 +1490,9 @@ set search_path = '' as $$ #variable_conflict use_column declare - v_actor uuid := private.require_actor(); + v_actor uuid := private.require_catalog_actor(); begin - if not (private.has_mfa() and private.is_platform_owner(v_actor)) then + if not private.is_platform_owner(v_actor) then raise exception 'rights.owner' using errcode = '42501'; end if; if char_length(name_fr) not between 1 and 80 or char_length(name_en) not between 1 and 80 then @@ -1329,6 +1502,7 @@ begin if not found then raise exception 'species.not_active' using errcode = 'P0001'; end if; + perform private.consume_catalog_write_budget(v_actor); update public.species s set name_fr = rename_species.name_fr, name_en = rename_species.name_en where s.id = rename_species.id; perform private.log_event(v_actor, 'species.renamed', 'species', null, null, null, jsonb_build_object('id', rename_species.id)); return rename_species.id; @@ -1344,7 +1518,8 @@ security definer set search_path = '' as $$ begin - if not (private.caller_is_catalog_staff() or (private.has_mfa() and private.is_platform_owner((select auth.uid())))) then + perform private.require_catalog_actor(); + if not (private.caller_is_catalog_staff() or private.is_platform_owner((select auth.uid()))) then raise exception 'rights.capability' using errcode = '42501'; end if; return coalesce(( @@ -1494,17 +1669,21 @@ set search_path = '' as $$ #variable_conflict use_column declare + v_actor uuid; v_row public.anatomical_sheet_assets%rowtype; v_object storage.objects%rowtype; begin - select a.* into v_row from public.anatomical_sheet_assets a where a.id = confirm_sheet_asset_upload.asset_id; + if auth.uid() is not null then + v_actor := private.require_catalog_actor(); + elsif auth.role() is distinct from 'service_role' then + raise exception 'rights.capability' using errcode = '42501'; + end if; + select a.* into v_row from public.anatomical_sheet_assets a where a.id = confirm_sheet_asset_upload.asset_id for update; if v_row.id is null then raise exception 'not_found' using errcode = '42501'; end if; - if auth.uid() is not null then + if v_actor is not null then perform private.require_sheet_author(v_row.sheet_id); - elsif auth.role() is distinct from 'service_role' then - raise exception 'rights.capability' using errcode = '42501'; end if; select o.* into v_object from storage.objects o where o.bucket_id = 'anatomical-sheet-assets' and o.name = v_row.sha256 || '.svg'; @@ -1515,6 +1694,10 @@ begin raise exception 'size_mismatch' using errcode = 'P0001'; end if; if v_row.uploaded_at is null then + -- The operator tool (service role, no actor) has no budget row. + if v_actor is not null then + perform private.consume_catalog_write_budget(v_actor); + end if; update public.anatomical_sheet_assets set uploaded_at = now() where id = v_row.id; perform private.log_event(auth.uid(), 'anatomical_sheet_asset.uploaded', 'anatomical_sheet_asset', v_row.id); end if; @@ -1548,10 +1731,11 @@ begin end; $$; --- An editor uploads the pending key of their own sheet (contract §9.3 step 2). --- Routed through a single granted predicate, as the avatar bucket is, so that --- evaluating this policy against another bucket's insert needs no EXECUTE on --- the internal helpers. +-- The editor who registered a pending row uploads its key (contract §9.3 +-- step 2: "exactly that key for the caller of a pending row"). Routed through +-- a single granted predicate, as the avatar bucket is, so that evaluating this +-- policy against another bucket's insert needs no EXECUTE on the internal +-- helpers. create or replace function private.can_upload_sheet_asset_object(p_user_id uuid, p_object_name text) returns boolean language sql @@ -1566,12 +1750,48 @@ as $$ where a.sha256 = left(p_object_name, 64) and p_object_name = a.sha256 || '.svg' and a.uploaded_at is null + and a.created_by = p_user_id and private.caller_can_see_official_sheet(a.sheet_id) ); $$; comment on function private.can_upload_sheet_asset_object(uuid, text) is - 'Storage INSERT predicate for bucket anatomical-sheet-assets: the caller holds sheet_editor at aal2 and the pending key .svg belongs to a non-deleted official sheet (contract §9.3).'; + 'Storage INSERT predicate for bucket anatomical-sheet-assets: the caller holds sheet_editor at aal2 and registered a pending row of a non-deleted official sheet whose key is exactly .svg (contract §9.3).'; + +-- Delete an unreferenced asset row (editor, aal2), replacing the base +-- version: closed codes, the historical sheet refused, the write budget. The +-- object stays in Storage (objects are never deleted, §9.5). +create or replace function public.delete_sheet_asset(asset_id uuid) +returns uuid +language plpgsql +volatile +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_catalog_actor(); + v_row public.anatomical_sheet_assets%rowtype; +begin + select a.* into v_row from public.anatomical_sheet_assets a where a.id = delete_sheet_asset.asset_id for update; + if v_row.id is null then + raise exception 'not_found' using errcode = '42501'; + end if; + perform private.require_sheet_author(v_row.sheet_id); + if exists ( + select 1 from public.anatomical_sheet_versions v + where v.sheet_id = v_row.sheet_id and v_row.id::text = any (private.sheet_document_asset_ids(v.content)) + ) then + raise exception 'asset.referenced' using errcode = '55000'; + end if; + perform private.consume_catalog_write_budget(v_actor); + delete from public.anatomical_sheet_assets where id = v_row.id; + perform private.log_event( + v_actor, 'anatomical_sheet_asset.deleted', 'anatomical_sheet_asset', v_row.id, null, null, + jsonb_build_object('sheet_id', v_row.sheet_id) + ); + return v_row.id; +end; +$$; revoke all on function private.can_upload_sheet_asset_object(uuid, text) from public, anon, authenticated, service_role; grant execute on function private.can_upload_sheet_asset_object(uuid, text) to authenticated; @@ -1688,6 +1908,12 @@ revoke all on function private.sheet_has_to_confirm(jsonb) from public, anon, au revoke all on function private.sheet_disclaimer_ok(jsonb) from public, anon, authenticated, service_role; revoke all on function private.on_sheet_version_content() from public, anon, authenticated, service_role; revoke all on function private.guard_sheet_version_update() from public, anon, authenticated, service_role; +revoke all on function private.require_catalog_actor() from public, anon, authenticated, service_role; +revoke all on function private.require_capability(public.catalog_grant_kind) from public, anon, authenticated, service_role; +revoke all on function private.check_document_structure(jsonb) from public, anon, authenticated, service_role; +revoke all on function private.insert_official_sheet(text, text, text, text, uuid) from public, anon, authenticated, service_role; +revoke all on function private.is_historical_working_copy(uuid) from public, anon, authenticated, service_role; +revoke all on function private.historical_working_copy_active(uuid) from public, anon, authenticated, service_role; revoke all on function private.require_sheet_author(uuid) from public, anon, authenticated, service_role; revoke all on function private.require_sheet_publisher(uuid) from public, anon, authenticated, service_role; revoke all on function private.verdict_group_digest(jsonb, text) from public, anon, authenticated, service_role; diff --git a/supabase/tests/006_sheet_asset_storage.sql b/supabase/tests/006_sheet_asset_storage.sql index 04cea5cc..91353ee7 100644 --- a/supabase/tests/006_sheet_asset_storage.sql +++ b/supabase/tests/006_sheet_asset_storage.sql @@ -3,7 +3,7 @@ -- upload INSERT policy exists, no UPDATE/DELETE policy. Rows are seeded -- directly (table owner) to exercise the policy, not the RPCs (those are 016). begin; -select plan(15); +select plan(16); -- Bucket select is((select public from storage.buckets where id = 'anatomical-sheet-assets'), false, 'the bucket is private'); @@ -21,22 +21,27 @@ select is( 0::bigint, 'no UPDATE or DELETE policy on the bucket' ); --- Accounts: owner, editor (admin + capability), reader (catalog_reader), plain. +-- Accounts: owner, two editors (admin + capability), reader (catalog_reader), plain. insert into auth.users (id, email, email_confirmed_at) values ('30000000-0000-0000-0000-000000000001', 'own-st@test.local', now()), ('30000000-0000-0000-0000-00000000000e', 'ed-st@test.local', now()), + ('30000000-0000-0000-0000-0000000000e2', 'ed2-st@test.local', now()), ('30000000-0000-0000-0000-0000000000d0', 'rd-st@test.local', now()), ('30000000-0000-0000-0000-0000000000d1', 'pl-st@test.local', now()); insert into auth.mfa_factors (id, user_id, factor_type, status, created_at, updated_at) - values (gen_random_uuid(), '30000000-0000-0000-0000-00000000000e', 'totp', 'verified', now(), now()); + values (gen_random_uuid(), '30000000-0000-0000-0000-00000000000e', 'totp', 'verified', now(), now()), + (gen_random_uuid(), '30000000-0000-0000-0000-0000000000e2', 'totp', 'verified', now(), now()); insert into auth.sessions (id, user_id, aal) values ('31000000-0000-0000-0000-000000000001', '30000000-0000-0000-0000-000000000001', 'aal2'), - ('31000000-0000-0000-0000-00000000000e', '30000000-0000-0000-0000-00000000000e', 'aal2'); + ('31000000-0000-0000-0000-00000000000e', '30000000-0000-0000-0000-00000000000e', 'aal2'), + ('31000000-0000-0000-0000-0000000000e2', '30000000-0000-0000-0000-0000000000e2', 'aal2'); select set_config('request.jwt.claims', '', true); select private.assign_platform_role(null, '30000000-0000-0000-0000-000000000001', 'owner'); select private.assign_platform_role(null, '30000000-0000-0000-0000-00000000000e', 'admin'); +select private.assign_platform_role(null, '30000000-0000-0000-0000-0000000000e2', 'admin'); insert into public.anatomical_catalog_grants (user_id, grant_kind, reason, verification_note, granted_by) values ('30000000-0000-0000-0000-00000000000e', 'sheet_editor', 'author', 'checked', '30000000-0000-0000-0000-000000000001'), + ('30000000-0000-0000-0000-0000000000e2', 'sheet_editor', 'author', 'checked', '30000000-0000-0000-0000-000000000001'), ('30000000-0000-0000-0000-0000000000d0', 'catalog_reader', 'beta', null, '30000000-0000-0000-0000-000000000001'); -- An official sheet with a published version (asset A), a deprecated version @@ -82,12 +87,21 @@ create function pg_temp.act(p_uid uuid, p_sid uuid, p_aal text) returns void lan select set_config('request.jwt.claims', jsonb_build_object('sub',p_uid,'role','authenticated','aal',p_aal,'session_id',p_sid)::text, true); $$; grant execute on function pg_temp.act(uuid,uuid,text) to authenticated; +-- The objects of this file's keys the caller reads: the stack may hold other +-- drawings (sandbox suites, DEV after its first publications, LRN-093). +create function pg_temp.objects_seen() returns table (name text) language sql as $$ + select o.name from storage.objects o + where o.bucket_id = 'anatomical-sheet-assets' + and o.name in (select repeat(c, 64) || '.svg' from unnest(array['a', 'b', 'c', 'd', 'e']) c) + order by o.name; +$$; +grant execute on function pg_temp.objects_seen() to authenticated; -- Reader (catalog_reader, aal1): the published and deprecated drawings only. set local role authenticated; select pg_temp.act('30000000-0000-0000-0000-0000000000d0', gen_random_uuid(), 'aal1'); select results_eq( - $$ select name from storage.objects where bucket_id='anatomical-sheet-assets' order by name $$, + $$ select name from pg_temp.objects_seen() $$, $$ values (repeat('a',64)||'.svg'), (repeat('b',64)||'.svg') $$, 'a catalogue reader reads the published and deprecated drawings, not the draft or pending ones' ); @@ -95,7 +109,7 @@ select results_eq( -- Editor at aal2: every uploaded drawing of the official sheet (a, b, c), not the pending d. select pg_temp.act('30000000-0000-0000-0000-00000000000e', '31000000-0000-0000-0000-00000000000e', 'aal2'); select results_eq( - $$ select name from storage.objects where bucket_id='anatomical-sheet-assets' order by name $$, + $$ select name from pg_temp.objects_seen() $$, $$ values (repeat('a',64)||'.svg'), (repeat('b',64)||'.svg'), (repeat('c',64)||'.svg') $$, 'an editor at aal2 reads every confirmed drawing of the official sheet, not the pending one' ); @@ -105,14 +119,14 @@ select results_eq( -- shows the published and deprecated drawings (not the draft's). select pg_temp.act('30000000-0000-0000-0000-00000000000e', gen_random_uuid(), 'aal1'); select results_eq( - $$ select name from storage.objects where bucket_id='anatomical-sheet-assets' order by name $$, + $$ select name from pg_temp.objects_seen() $$, $$ values (repeat('a',64)||'.svg'), (repeat('b',64)||'.svg') $$, 'the editor at aal1 falls back to the reader branch: published and deprecated only' ); -- A plain confirmed account with no right: nothing. select pg_temp.act('30000000-0000-0000-0000-0000000000d1', gen_random_uuid(), 'aal1'); -select is((select count(*) from storage.objects where bucket_id='anatomical-sheet-assets'), 0::bigint, +select is((select count(*) from pg_temp.objects_seen()), 0::bigint, 'a confirmed account without any right reads nothing'); -- The INSERT policy only allows a pending key of one''s own sheet: a confirmed @@ -125,16 +139,23 @@ select throws_ok( '42501', null, 'an editor cannot insert a confirmed (non-pending) object key' ); --- A fifth asset, pending, with no object yet: the editor uploads its key. +-- A fifth asset, pending, registered by the first editor, with no object yet: +-- only the editor who registered it uploads its key (§9.3 step 2). reset role; select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-000000000001"}', true); -insert into public.anatomical_sheet_assets (id, sheet_id, sha256, byte_size, file_name) - values ('32000000-0000-0000-0000-00000000000e', '32000000-0000-0000-0000-000000000001', repeat('e',64), 100, 'e.svg'); +insert into public.anatomical_sheet_assets (id, sheet_id, sha256, byte_size, file_name, created_by) + values ('32000000-0000-0000-0000-00000000000e', '32000000-0000-0000-0000-000000000001', repeat('e',64), 100, 'e.svg', + '30000000-0000-0000-0000-00000000000e'); set local role authenticated; +select pg_temp.act('30000000-0000-0000-0000-0000000000e2', '31000000-0000-0000-0000-0000000000e2', 'aal2'); +select throws_ok( + $$ insert into storage.objects (bucket_id, name, metadata) values ('anatomical-sheet-assets', repeat('e',64)||'.svg', '{"size":100}') $$, + '42501', null, 'another editor cannot upload a pending key it did not register' +); select pg_temp.act('30000000-0000-0000-0000-00000000000e', '31000000-0000-0000-0000-00000000000e', 'aal2'); select lives_ok( $$ insert into storage.objects (bucket_id, name, metadata) values ('anatomical-sheet-assets', repeat('e',64)||'.svg', '{"size":100}') $$, - 'an editor uploads the pending key of their own sheet' + 'the editor who registered the pending row uploads its key' ); -- confirm with the storage check: a wrong size is refused, the right one works. diff --git a/supabase/tests/015_catalog_access.sql b/supabase/tests/015_catalog_access.sql index 5a79f04d..9ea51701 100644 --- a/supabase/tests/015_catalog_access.sql +++ b/supabase/tests/015_catalog_access.sql @@ -1,8 +1,9 @@ -- V1-2.1 M4: AR-1 B (MFA on every platform role change) and catalogue rights. -- Contract docs/development/V1-2_ANATOMICAL_SHEETS.md §5.2, §5.7, §15. -- The aal2 session check reads auth.sessions; here those rows are fabricated, --- as the shim allows. Real GoTrue MFA is proven in tests/sandbox/mfa.sandbox.ts, --- the F18 race in tests/sandbox (two sessions). +-- as the shim allows. Real GoTrue MFA and the F18 race (two sessions) are +-- proven in packages/supabase/tests/sandbox/sheets.sandbox.ts, the seed owner's +-- factors on an upgraded stack in seed-owner-mfa.sandbox.ts. begin; select plan(36); diff --git a/supabase/tests/016_sheet_review_workflow.sql b/supabase/tests/016_sheet_review_workflow.sql index d4bbabd1..aead7086 100644 --- a/supabase/tests/016_sheet_review_workflow.sql +++ b/supabase/tests/016_sheet_review_workflow.sql @@ -158,7 +158,9 @@ insert into public.anatomical_catalog_grants (user_id,grant_kind,reason,granted_ -- A catalogue reader sees the published version and its drawing; not the grants. set local role authenticated; select pg_temp.act('e0000000-0000-0000-0000-0000000000cc', gen_random_uuid()); -select is((select jsonb_array_length(public.list_official_catalog())), 1, 'the reader sees one catalogue sheet'); +select is((select count(*) from jsonb_array_elements(public.list_official_catalog()) e + where (e ->> 'sheet_id')::uuid = (select id from pg_temp.k where key='sheet')), 1::bigint, + 'the reader sees the published sheet in the catalogue'); select is((select (public.get_sheet_version((select id from pg_temp.k where key='v1'))) ->> 'status'), 'published', 'the reader reads the published version by id'); @@ -168,7 +170,9 @@ select public.deprecate_sheet_version((select id from pg_temp.k where key='v1'), select pg_temp.act('e0000000-0000-0000-0000-0000000000cc', gen_random_uuid()); select is((select (public.get_sheet_version((select id from pg_temp.k where key='v1'))) ->> 'status'), 'deprecated', 'a deprecated version stays readable by id (D8)'); -select is((select jsonb_array_length(public.list_official_catalog())), 0, 'the sheet leaves the catalogue list once its last version is deprecated'); +select is((select count(*) from jsonb_array_elements(public.list_official_catalog()) e + where (e ->> 'sheet_id')::uuid = (select id from pg_temp.k where key='sheet')), 0::bigint, + 'the sheet leaves the catalogue list once its last version is deprecated'); -- ============ Species rules (§7.2) ============ select pg_temp.act('e0000000-0000-0000-0000-00000000000e','e1000000-0000-0000-0000-00000000000e'); @@ -189,16 +193,16 @@ select pg_temp.act('e0000000-0000-0000-0000-00000000000e','e1000000-0000-0000-00 select throws_ok($$ select public.create_sheet_working_copy((select id from pg_temp.k where key='v1'), 'copie') $$, 'P0001', 'working_copy.source_invalid', 'a working copy of a non-historical version is refused'); --- ============ Base only from a round-published version (§6.2) ============ --- v1 was published through r2 (a V1-2 round), so a new draft takes it as base --- (passed explicitly, since deprecating the only published version cleared the --- sheet's current version). +-- ============ Base only from a version still published through a round (§6.2) ============ +-- v1 was published through r2 and then deprecated (passed explicitly, since +-- deprecating the only published version cleared the sheet's current +-- version): a deprecated source gives no base. The positive base case is in 017. insert into pg_temp.k select 'v2', public.create_sheet_draft( (select id from pg_temp.k where key='sheet'), (select id from pg_temp.k where key='v1'), 'new edition'); reset role; select is( - (select (source_version_id = (select id from pg_temp.k where key='v1')) from public.anatomical_sheet_versions where id=(select id from pg_temp.k where key='v2')), - true, 'a draft derived from a round-published version records it as its base'); + (select source_version_id from public.anatomical_sheet_versions where id=(select id from pg_temp.k where key='v2')), + null, 'a draft derived from a deprecated version has no base'); -- The publish gate: a direct UPDATE of a real draft to published is refused for -- the table owner (no approved round named). select throws_ok($$ update public.anatomical_sheet_versions set status='published', published_at=now(), document_fingerprint=repeat('a',64) @@ -336,7 +340,11 @@ select throws_ok($$ select public.delete_sheet_version((select id from pg_temp.k -- ============ Working copy of the historical sheet, positive path (§14.3) ============ -- Confirm the seeded historical drawing object, then create the working copy. +-- A working copy already active on this stack is archived inside this +-- transaction first (LRN-093: scope to the fixture, never to the stack state). reset role; +update public.anatomical_sheets set status = 'archived', archived_at = now() + where status = 'active' and private.is_historical_working_copy(id); insert into storage.objects (bucket_id, name, metadata) select 'anatomical-sheet-assets', a.sha256 || '.svg', jsonb_build_object('size', a.byte_size) from public.anatomical_sheet_assets a where a.sheet_id = '503dc301-a8b1-50d4-9e44-0919b2fc2916' diff --git a/supabase/tests/017_sheet_review_rules.sql b/supabase/tests/017_sheet_review_rules.sql new file mode 100644 index 00000000..5b32f709 --- /dev/null +++ b/supabase/tests/017_sheet_review_rules.sql @@ -0,0 +1,564 @@ +-- V1-2.1 M5: the submission, approval and publication rules of contract §6.2, +-- §6.3, §6.7 and §6.9 taken one at a time, after the independent audit (M1, +-- M2, M3): approval on an archived sheet, the base of a derived draft, each +-- rule failing alone, removal groups, no carry for an author, F2, D8 reads +-- after archive, species, working copy, closed codes, audit. The verdict (and, +-- for the publication rules, the approval) is written as the table owner, +-- standing in for the worker of M6 (§12.2). Every assertion is scoped to the +-- ids created here, so the file also runs on a stack that already holds +-- sheets, rounds or a working copy. +begin; +select plan(78); + +-- Accounts: O owner, E admin + editor + publisher, V reviewer, V2 admin + +-- editor + reviewer (an author of a later round), V3 reviewer, R reader. +insert into auth.users (id, email, email_confirmed_at) values + ('17000000-0000-0000-0000-000000000001', 'own@r17.local', now()), + ('17000000-0000-0000-0000-00000000000e', 'edpub@r17.local', now()), + ('17000000-0000-0000-0000-0000000000f1', 'rev@r17.local', now()), + ('17000000-0000-0000-0000-0000000000f2', 'edrev@r17.local', now()), + ('17000000-0000-0000-0000-0000000000f3', 'rev3@r17.local', now()), + ('17000000-0000-0000-0000-0000000000cc', 'reader@r17.local', now()); +insert into auth.mfa_factors (id, user_id, factor_type, status, created_at, updated_at) +select gen_random_uuid(), id, 'totp', 'verified', now(), now() from auth.users where email like '%@r17.local'; +insert into auth.sessions (id, user_id, aal) +select ('17100000' || substr(id::text, 9))::uuid, id, 'aal2' from auth.users where email like '%@r17.local'; + +select set_config('request.jwt.claims', '', true); +select private.assign_platform_role(null, '17000000-0000-0000-0000-000000000001', 'owner'); +select private.assign_platform_role(null, '17000000-0000-0000-0000-00000000000e', 'admin'); +select private.assign_platform_role(null, '17000000-0000-0000-0000-0000000000f2', 'admin'); +insert into public.anatomical_catalog_grants (user_id, grant_kind, reason, verification_note, granted_by) values + ('17000000-0000-0000-0000-00000000000e', 'sheet_editor', 'a', 'c', '17000000-0000-0000-0000-000000000001'), + ('17000000-0000-0000-0000-00000000000e', 'sheet_publisher', 'a', 'c', '17000000-0000-0000-0000-000000000001'), + ('17000000-0000-0000-0000-0000000000f1', 'sheet_reviewer', 'a', 'c', '17000000-0000-0000-0000-000000000001'), + ('17000000-0000-0000-0000-0000000000f2', 'sheet_editor', 'a', 'c', '17000000-0000-0000-0000-000000000001'), + ('17000000-0000-0000-0000-0000000000f2', 'sheet_reviewer', 'a', 'c', '17000000-0000-0000-0000-000000000001'), + ('17000000-0000-0000-0000-0000000000f3', 'sheet_reviewer', 'a', 'c', '17000000-0000-0000-0000-000000000001'), + ('17000000-0000-0000-0000-0000000000cc', 'catalog_reader', 'a', null, '17000000-0000-0000-0000-000000000001'); + +create table pg_temp.k (key text primary key, id uuid); +create function pg_temp.id(p_key text) returns uuid language sql stable as $$ select id from pg_temp.k where key = p_key $$; +create function pg_temp.u(p text) returns uuid language sql immutable as $$ + select ('17000000-0000-0000-0000-0000000000' || case p when 'O' then '01' when 'E' then '0e' when 'V' then 'f1' + when 'V2' then 'f2' when 'V3' then 'f3' when 'R' then 'cc' end)::uuid; +$$; +-- The calling session of an account at aal2 (its session row exists). +create function pg_temp.as_user(p text) returns void language plpgsql as $$ +begin + perform set_config('role', 'authenticated', true); + perform set_config('request.jwt.claims', jsonb_build_object('sub', pg_temp.u(p), 'role', 'authenticated', 'aal', 'aal2', + 'session_id', ('17100000' || substr(pg_temp.u(p)::text, 9))::uuid)::text, true); +end $$; +-- A small document: one main view, one annotation, one zone (z1) or two +-- (z1, z2); `st` is the review status of every status-bearing element. +create function pg_temp.doc(p_asset uuid, st text, p_zones int default 1) returns jsonb language sql as $$ + select jsonb_build_object('schema_version', 2, 'species_id', 'equine', + 'name', jsonb_build_object('fr', 'Cheval R', 'en', 'R horse'), + 'description', jsonb_build_object('fr', 'd', 'en', 'd'), + 'scope_disclaimer', jsonb_build_object('fr', 'x', 'en', 'x'), + 'attribution', jsonb_build_object('authors', jsonb_build_array('F'), 'license', null, 'notes', null), + 'vertebral_config', jsonb_build_object('regions', '[]'::jsonb), 'references', '[]'::jsonb, + 'categories', jsonb_build_array(jsonb_build_object('id', 'c', 'name', jsonb_build_object('fr', 'C', 'en', 'C'), 'color', null)), + 'views', jsonb_build_array(jsonb_build_object('id', 'main', 'kind', 'main', 'name', jsonb_build_object('fr', 'V', 'en', 'V'), + 'svg_asset_id', p_asset, 'view_box', null)), + 'annotations', jsonb_build_array(jsonb_build_object('id', 'a1', 'kind', 'point', 'view_id', 'main', 'category_id', 'c', + 'laterality', 'unpaired', 'geometry', null, 'review_status', st, 'name', jsonb_build_object('fr', 'P', 'en', 'P'), + 'finding_zone_id', 'z1', 'vertebral_region_code', null)), + 'finding_zones', (select jsonb_agg(jsonb_build_object('id', 'z' || i, 'name', jsonb_build_object('fr', 'Z', 'en', 'Z'), + 'categories', jsonb_build_array(jsonb_build_object('id', 'cat', 'kind', 'dysfunction', 'name', jsonb_build_object('fr', 'D', 'en', 'D'), + 'review_status', st, 'children', jsonb_build_array(jsonb_build_object('id', 'n1', 'name', jsonb_build_object('fr', 'N', 'en', 'N'), + 'review_status', st)))))) from generate_series(1, p_zones) i)); +$$; +-- A verdict group, and the three groups of the one-zone document (1, 2, 3). +create function pg_temp.g(p_key text, p_digest text, p_coverable boolean default true) returns jsonb language sql as $$ + select jsonb_build_object('key', p_key, 'digest', repeat(p_digest, 64), 'coverable', p_coverable); +$$; +create function pg_temp.groups3() returns jsonb language sql as $$ + select jsonb_build_array(pg_temp.g('general', '1'), pg_temp.g('view:main', '2'), pg_temp.g('zone:z1', '3')); +$$; +-- The same three groups, every digest made of one hex character (one per +-- content variant, so no acknowledgment carries between variants). +create function pg_temp.groups_of(ch text) returns jsonb language sql as $$ + select jsonb_build_array(pg_temp.g('general', ch), pg_temp.g('view:main', ch), pg_temp.g('zone:z1', ch)); +$$; +-- Writes a passing verdict and opens the round (the worker's stand-in). +create function pg_temp.open_round(p_review uuid, p_asset uuid, p_sha text, p_groups jsonb) returns void language sql as $$ + update public.anatomical_sheet_reviews set status = 'open', verified_at = now(), verified_with = 'test', + verdict = jsonb_build_object('fingerprint', repeat('a', 64), + 'drawings', jsonb_build_array(jsonb_build_object('asset_id', p_asset, 'sha256', p_sha)), 'groups', p_groups) + where id = p_review; +$$; +-- An official sheet whose draft references a confirmed drawing, saved fully +-- reviewed (revision 1); keys

,

.v,

.asset. As E. +create function pg_temp.sheet(p text, p_sha text) returns void language plpgsql as $$ +begin + perform pg_temp.as_user('E'); + insert into pg_temp.k select p, public.create_official_sheet('r17-' || p, pg_temp.doc(null, 'reviewed')); + insert into pg_temp.k select p || '.v', id from public.anatomical_sheet_versions where sheet_id = pg_temp.id(p); + insert into pg_temp.k select p || '.asset', public.register_sheet_asset(pg_temp.id(p), p_sha, 100, 'd.svg'); + perform set_config('role', 'postgres', true); + insert into storage.objects (bucket_id, name, metadata) + values ('anatomical-sheet-assets', p_sha || '.svg', '{"size":100}') on conflict do nothing; + perform pg_temp.as_user('E'); + perform public.confirm_sheet_asset_upload(pg_temp.id(p || '.asset')); + perform public.save_sheet_draft(pg_temp.id(p || '.v'), 0, pg_temp.doc(pg_temp.id(p || '.asset'), 'reviewed'), 'wire'); +end $$; +-- E submits the draft of

at ; the round opens with . +create function pg_temp.round(p text, rk text, rev int, p_sha text, p_groups jsonb) returns void language plpgsql as $$ +begin + perform pg_temp.as_user('E'); + insert into pg_temp.k select rk, public.submit_sheet_review(pg_temp.id(p || '.v'), rev, 'round'); + perform set_config('role', 'postgres', true); + perform pg_temp.open_round(pg_temp.id(rk), pg_temp.id(p || '.asset'), p_sha, p_groups); + perform pg_temp.as_user('E'); +end $$; +-- V acknowledges every group of a round. +create function pg_temp.ack_all(rk text) returns void language plpgsql as $$ +declare g jsonb; +begin + perform pg_temp.as_user('V'); + for g in select e from public.anatomical_sheet_reviews r, jsonb_array_elements(r.verdict -> 'groups') e where r.id = pg_temp.id(rk) loop + perform public.acknowledge_sheet_review_group(pg_temp.id(rk), g ->> 'key', g ->> 'digest'); + end loop; +end $$; +-- saves on

, E submits, the round opens with digests +-- and the fixture approves it as with every group acknowledged by +-- (none when null). Ends as E. +create function pg_temp.fixture_round(p text, rk text, ch text, p_doc jsonb, p_saver text, p_decider text, p_acker text) +returns void language plpgsql as $$ +declare v_rev int; g jsonb; +begin + perform pg_temp.as_user(p_saver); + select revision into v_rev from public.anatomical_sheet_versions where id = pg_temp.id(p || '.v'); + perform public.save_sheet_draft(pg_temp.id(p || '.v'), v_rev, p_doc, 'variant'); + perform pg_temp.round(p, rk, v_rev + 1, repeat('b6', 32), pg_temp.groups_of(ch)); + perform set_config('role', 'postgres', true); + update public.anatomical_sheet_reviews set status = 'approved', decided_by = pg_temp.u(p_decider), + decided_at = now(), decision_note = 'fixture' where id = pg_temp.id(rk); + if p_acker is not null then + for g in select e from public.anatomical_sheet_reviews r, jsonb_array_elements(r.verdict -> 'groups') e where r.id = pg_temp.id(rk) loop + insert into public.anatomical_sheet_review_acknowledgments (review_id, group_key, group_digest, reviewer) + values (pg_temp.id(rk), g ->> 'key', g ->> 'digest', pg_temp.u(p_acker)); + end loop; + end if; + perform pg_temp.as_user('E'); +end $$; +grant all on pg_temp.k to authenticated; +grant execute on all functions in schema pg_temp to authenticated; + +-- ============ M1: approval needs an active sheet (§6.7) ============ +select pg_temp.sheet('m1', repeat('a1', 32)); +select pg_temp.round('m1', 'm1.r', 1, repeat('a1', 32), pg_temp.groups3()); +select pg_temp.ack_all('m1.r'); +select pg_temp.as_user('E'); +select public.archive_anatomical_sheet(pg_temp.id('m1')); +select pg_temp.as_user('V'); +select throws_ok($$ select public.decide_sheet_review(pg_temp.id('m1.r'), true, 'ok') $$, + '55000', 'sheet.inactive', 'M1: an approval on an archived sheet is refused (§6.7)'); +select is((select status::text from public.anatomical_sheet_reviews where id = pg_temp.id('m1.r')), 'open', + 'M1: the refused approval leaves the round open'); +select pg_temp.as_user('E'); +select public.restore_anatomical_sheet(pg_temp.id('m1')); +select pg_temp.as_user('V'); +select lives_ok($$ select public.decide_sheet_review(pg_temp.id('m1.r'), true, 'ok') $$, + 'M1: once the sheet is restored the same approval succeeds'); + +-- ============ M2: a base only from a round-published version (§6.2) ============ +-- m2: v1 published through a round, then deprecated; a draft from it has no base. +select pg_temp.sheet('m2', repeat('a2', 32)); +select pg_temp.round('m2', 'm2.r1', 1, repeat('a2', 32), pg_temp.groups3()); +select pg_temp.ack_all('m2.r1'); +select public.decide_sheet_review(pg_temp.id('m2.r1'), true, 'ok'); +select pg_temp.as_user('E'); +select public.publish_sheet_version(pg_temp.id('m2.r1')); +select public.deprecate_sheet_version(pg_temp.id('m2.v'), 'superseded'); +insert into pg_temp.k select 'm2b.v', public.create_sheet_draft(pg_temp.id('m2'), pg_temp.id('m2.v'), 'from deprecated'); +reset role; +select is((select source_version_id from public.anatomical_sheet_versions where id = pg_temp.id('m2b.v')), null, + 'M2: a draft from a deprecated version has no base'); +-- Same digests as the deprecated version's round: still every group to cover. +insert into pg_temp.k values ('m2b', pg_temp.id('m2')), ('m2b.asset', pg_temp.id('m2.asset')); +select pg_temp.round('m2b', 'm2b.r', 0, repeat('a2', 32), pg_temp.groups3()); +select pg_temp.as_user('V'); +select throws_ok($$ select public.decide_sheet_review(pg_temp.id('m2b.r'), true, 'ok') $$, + 'P0001', 'review.groups.uncovered', 'M2: groups unchanged against a deprecated version still need an acknowledgment'); +select pg_temp.ack_all('m2b.r'); +select lives_ok($$ select public.decide_sheet_review(pg_temp.id('m2b.r'), true, 'ok') $$, + 'M2: once every group is acknowledged the approval succeeds'); + +-- m3: the positive base. v1 published through a round and still published: a +-- draft from it takes it as base, and its unchanged groups need no new ack. +select pg_temp.sheet('m3', repeat('a3', 32)); +select pg_temp.round('m3', 'm3.r1', 1, repeat('a3', 32), pg_temp.groups3()); +select pg_temp.ack_all('m3.r1'); +select public.decide_sheet_review(pg_temp.id('m3.r1'), true, 'ok'); +select pg_temp.as_user('E'); +select public.publish_sheet_version(pg_temp.id('m3.r1')); +insert into pg_temp.k select 'm3b.v', public.create_sheet_draft(pg_temp.id('m3'), null, 'next edition'); +reset role; +select is((select source_version_id from public.anatomical_sheet_versions where id = pg_temp.id('m3b.v')), pg_temp.id('m3.v'), + 'M2: a draft from a version published through a round takes it as base'); +insert into pg_temp.k values ('m3b', pg_temp.id('m3')), ('m3b.asset', pg_temp.id('m3.asset')); +select pg_temp.round('m3b', 'm3b.r', 0, repeat('a3', 32), pg_temp.groups3()); +select pg_temp.as_user('V'); +select lives_ok($$ select public.decide_sheet_review(pg_temp.id('m3b.r'), true, 'ok') $$, + 'M2: groups equal to the base are covered by the base''s approved round'); + +-- m4: a version published before M5 (no published_review_id) gives no base. +reset role; +select set_config('request.jwt.claims', '{"sub":"17000000-0000-0000-0000-00000000000e"}', true); +insert into public.anatomical_sheets (id, species_id, name, slug, is_official, visibility, status) + values ('17200000-0000-0000-0000-000000000004', 'equine', 'Pre', 'r17-pre-m5', true, 'private', 'active'); +insert into public.anatomical_sheet_versions (id, sheet_id, version_number, status, document_schema_version, content, published_at, document_fingerprint) + values ('17300000-0000-0000-0000-000000000004', '17200000-0000-0000-0000-000000000004', 1, 'published', 2, + pg_temp.doc(null, 'reviewed'), now(), repeat('0', 64)); +update public.anatomical_sheets set current_version_id = '17300000-0000-0000-0000-000000000004', last_version_number = 1 + where id = '17200000-0000-0000-0000-000000000004'; +select pg_temp.as_user('E'); +insert into pg_temp.k select 'm4b.v', public.create_sheet_draft('17200000-0000-0000-0000-000000000004', null, 'from pre-M5'); +reset role; +select is((select source_version_id from public.anatomical_sheet_versions where id = pg_temp.id('m4b.v')), null, + 'M2: a version published before M5 (no review) gives no base'); + +-- ============ Submission and approval rules one at a time (§6.7, §15) ============ +select pg_temp.sheet('s5', repeat('b5', 32)); +select throws_ok($$ select public.submit_sheet_review(pg_temp.id('s5.v'), 0, 'stale') $$, + 'P0001', 'draft_conflict', 'submit with a stale revision is a conflict'); +select public.save_sheet_draft(pg_temp.id('s5.v'), 1, pg_temp.doc('ffffffff-ffff-ffff-ffff-ffffffffffff', 'reviewed'), 'unknown drawing'); +select throws_ok($$ select public.submit_sheet_review(pg_temp.id('s5.v'), 2, 'x') $$, + 'P0001', 'view.asset.unknown', 'submit refuses a drawing id not registered for the sheet (§12.2)'); +select public.save_sheet_draft(pg_temp.id('s5.v'), 2, pg_temp.doc(pg_temp.id('s5.asset'), 'reviewed'), 'back'); +select pg_temp.round('s5', 's5.r1', 3, repeat('b5', 32), + jsonb_build_array(pg_temp.g('general', '1'), pg_temp.g('view:main', '2'), pg_temp.g('zone:z1', '3', false))); +select pg_temp.as_user('V'); +select throws_ok($$ select public.acknowledge_sheet_review_group(pg_temp.id('s5.r1'), 'zone:z1', repeat('3', 64)) $$, + 'P0001', 'review.uncoverable', 'a group the verdict marks as holding unread elements cannot be acknowledged'); +-- Acknowledgments are append-only (§6.3): the second one keeps the first row. +insert into pg_temp.k select 's5.ack', public.acknowledge_sheet_review_group(pg_temp.id('s5.r1'), 'general', repeat('1', 64)); +select is(public.acknowledge_sheet_review_group(pg_temp.id('s5.r1'), 'general', repeat('1', 64)), pg_temp.id('s5.ack'), + 'acknowledging a group twice returns the first acknowledgment'); +reset role; +select is((select count(*) from public.anatomical_sheet_review_acknowledgments + where review_id = pg_temp.id('s5.r1') and group_key = 'general'), 1::bigint, + 'one acknowledgment row per reviewer and group'); +select is((select count(*) from audit.audit_logs where action = 'anatomical_sheet_review.acknowledged' + and resource_id = pg_temp.id('s5.r1') and metadata ->> 'group_key' = 'general'), 1::bigint, + 'the repeated acknowledgment writes no second audit row (append-only)'); +-- An open round without a verdict, then a verdict of another revision. +select pg_temp.as_user('E'); +select public.withdraw_sheet_review(pg_temp.id('s5.r1'), 'redo'); +insert into pg_temp.k select 's5.r2', public.submit_sheet_review(pg_temp.id('s5.v'), 3, 'r2'); +reset role; +update public.anatomical_sheet_reviews set status = 'open' where id = pg_temp.id('s5.r2'); +select pg_temp.as_user('V'); +select throws_ok($$ select public.decide_sheet_review(pg_temp.id('s5.r2'), true, 'ok') $$, + 'P0001', 'verdict.missing', 'approval refused without a verdict'); +reset role; +-- The verdict names a drawing sha256 other than the row's (checked at publication). +select pg_temp.open_round(pg_temp.id('s5.r2'), pg_temp.id('s5.asset'), repeat('9', 64), pg_temp.groups3()); +update public.anatomical_sheet_versions set revision = revision + 1 where id = pg_temp.id('s5.v'); +select pg_temp.ack_all('s5.r2'); +select throws_ok($$ select public.decide_sheet_review(pg_temp.id('s5.r2'), true, 'ok') $$, + 'P0001', 'verdict.stale', 'approval refused on a verdict of another revision'); +reset role; +update public.anatomical_sheet_versions set revision = revision - 1 where id = pg_temp.id('s5.v'); +select pg_temp.as_user('E'); +select throws_ok($$ select public.publish_sheet_version(pg_temp.id('s5.r2')) $$, + '55000', 'publish.review.missing', 'publication refused while the round is not approved'); +select pg_temp.as_user('V'); +select public.decide_sheet_review(pg_temp.id('s5.r2'), true, 'ok'); +select pg_temp.as_user('E'); +select throws_ok($$ select public.publish_sheet_version(pg_temp.id('s5.r2')) $$, + 'P0001', 'publish.drawing.changed', 'publication refused when a drawing''s sha256 differs from the verdict''s'); + +-- ============ Publication rules one at a time (§6.7) on fixture approvals ============ +select pg_temp.sheet('s6', repeat('b6', 32)); +select pg_temp.fixture_round('s6', 's6.a', '4', pg_temp.doc(pg_temp.id('s6.asset'), 'to_confirm'), 'E', 'V', 'V'); +select throws_ok($$ select public.publish_sheet_version(pg_temp.id('s6.a')) $$, + 'P0001', 'publish.to_confirm.open', 'publication refused while an element is to_confirm'); +select public.withdraw_sheet_review(pg_temp.id('s6.a'), 'next'); +select pg_temp.fixture_round('s6', 's6.b', '5', + pg_temp.doc(pg_temp.id('s6.asset'), 'reviewed') #- '{annotations,0,review_status}', 'E', 'V', 'V'); +select throws_ok($$ select public.publish_sheet_version(pg_temp.id('s6.b')) $$, + 'P0001', 'publish.inherited.present', 'publication refused with an omitted (inherited) status'); +select public.withdraw_sheet_review(pg_temp.id('s6.b'), 'next'); +select pg_temp.fixture_round('s6', 's6.c', '6', + jsonb_set(pg_temp.doc(pg_temp.id('s6.asset'), 'reviewed'), '{scope_disclaimer,fr}', '" "'), 'E', 'V', 'V'); +select throws_ok($$ select public.publish_sheet_version(pg_temp.id('s6.c')) $$, + 'P0001', 'publish.disclaimer.missing', 'publication refused with a blank scope disclaimer'); +select public.withdraw_sheet_review(pg_temp.id('s6.c'), 'next'); +select pg_temp.fixture_round('s6', 's6.d', '7', pg_temp.doc(pg_temp.id('s6.asset'), 'reviewed'), 'E', 'V', null); +select throws_ok($$ select public.publish_sheet_version(pg_temp.id('s6.d')) $$, + 'P0001', 'review.groups.uncovered', 'publication refused while a group is uncovered'); +select public.withdraw_sheet_review(pg_temp.id('s6.d'), 'next'); +-- V2 saves this variant, so V2 is an author of the round it then "approves". +select pg_temp.fixture_round('s6', 's6.e', '8', + jsonb_set(pg_temp.doc(pg_temp.id('s6.asset'), 'reviewed'), '{description,fr}', '"e"'), 'V2', 'V2', 'V'); +select throws_ok($$ select public.publish_sheet_version(pg_temp.id('s6.e')) $$, + 'P0001', 'publish.approval.invalid', 'publication refused when the approver is an author of the round'); +select public.withdraw_sheet_review(pg_temp.id('s6.e'), 'next'); +-- Groups acknowledged by V3, whose grant is then revoked: no longer covered. +select pg_temp.fixture_round('s6', 's6.f', '9', + jsonb_set(pg_temp.doc(pg_temp.id('s6.asset'), 'reviewed'), '{description,fr}', '"f"'), 'E', 'V', 'V3'); +reset role; +update public.anatomical_catalog_grants set revoked_at = now(), revoked_by = pg_temp.u('O'), revocation_reason = 'left' + where user_id = pg_temp.u('V3') and revoked_at is null; +select pg_temp.as_user('E'); +select throws_ok($$ select public.publish_sheet_version(pg_temp.id('s6.f')) $$, + 'P0001', 'review.groups.uncovered', 'acknowledgments of a reviewer whose grant was revoked no longer cover'); +select public.withdraw_sheet_review(pg_temp.id('s6.f'), 'next'); +select pg_temp.fixture_round('s6', 's6.g', 'a', + jsonb_set(pg_temp.doc(pg_temp.id('s6.asset'), 'reviewed'), '{description,fr}', '"g"'), 'E', 'V', 'V'); +select is(public.publish_sheet_version(pg_temp.id('s6.g')), pg_temp.id('s6.v'), + 'with every rule met the same sheet publishes (each refusal above was alone)'); + +-- ============ No carry for an author (§6.3) ============ +select pg_temp.sheet('s7', repeat('b7', 32)); +select pg_temp.round('s7', 's7.r1', 1, repeat('b7', 32), pg_temp.groups3()); +select pg_temp.as_user('V2'); +select public.acknowledge_sheet_review_group(pg_temp.id('s7.r1'), 'general', repeat('1', 64)); +select pg_temp.as_user('V'); +select public.decide_sheet_review(pg_temp.id('s7.r1'), false, 'one more pass'); +-- V2 edits the draft: an author of the next round. +select pg_temp.as_user('V2'); +select public.save_sheet_draft(pg_temp.id('s7.v'), 1, + jsonb_set(pg_temp.doc(pg_temp.id('s7.asset'), 'reviewed'), '{description,en}', '"v2 edit"'), 'v2'); +select pg_temp.round('s7', 's7.r2', 2, repeat('b7', 32), pg_temp.groups3()); +select pg_temp.as_user('V'); +select public.acknowledge_sheet_review_group(pg_temp.id('s7.r2'), 'view:main', repeat('2', 64)); +select public.acknowledge_sheet_review_group(pg_temp.id('s7.r2'), 'zone:z1', repeat('3', 64)); +select throws_ok($$ select public.decide_sheet_review(pg_temp.id('s7.r2'), true, 'ok') $$, + 'P0001', 'review.groups.uncovered', 'an acknowledgment does not carry to a round its reviewer has since authored'); +select public.acknowledge_sheet_review_group(pg_temp.id('s7.r2'), 'general', repeat('1', 64)); +select lives_ok($$ select public.decide_sheet_review(pg_temp.id('s7.r2'), true, 'ok') $$, + 'the group acknowledged again by a non-author is covered'); + +-- ============ Removal group (§6.3) and D8 reads after archive (§6.9) ============ +select pg_temp.as_user('E'); +insert into pg_temp.k select 's8', public.create_official_sheet('r17-s8', pg_temp.doc(null, 'reviewed', 2)); +insert into pg_temp.k select 's8.v', id from public.anatomical_sheet_versions where sheet_id = pg_temp.id('s8'); +insert into pg_temp.k select 's8.asset', public.register_sheet_asset(pg_temp.id('s8'), repeat('b8', 32), 100, 'd.svg'); +reset role; +insert into storage.objects (bucket_id, name, metadata) + values ('anatomical-sheet-assets', repeat('b8', 32) || '.svg', '{"size":100}') on conflict do nothing; +select pg_temp.as_user('E'); +select public.confirm_sheet_asset_upload(pg_temp.id('s8.asset')); +select public.save_sheet_draft(pg_temp.id('s8.v'), 0, pg_temp.doc(pg_temp.id('s8.asset'), 'reviewed', 2), 'two zones'); +select pg_temp.round('s8', 's8.r1', 1, repeat('b8', 32), pg_temp.groups3() || jsonb_build_array(pg_temp.g('zone:z2', '4'))); +select pg_temp.ack_all('s8.r1'); +select public.decide_sheet_review(pg_temp.id('s8.r1'), true, 'ok'); +select pg_temp.as_user('E'); +select public.publish_sheet_version(pg_temp.id('s8.r1')); +-- The round of a published version is its review link: never withdrawn (§6.1). +select throws_ok($$ select public.withdraw_sheet_review(pg_temp.id('s8.r1'), 'late') $$, + '55000', 'draft.not_a_draft', 'the round of a published version cannot be withdrawn'); +select is((select status::text from public.anatomical_sheet_reviews where id = pg_temp.id('s8.r1')), 'approved', + 'a published round stays approved'); +-- The next edition drops zone z2: its removal group is to cover although every +-- other group equals the base. +insert into pg_temp.k select 's8b.v', public.create_sheet_draft(pg_temp.id('s8'), null, 'drop z2'); +select public.save_sheet_draft(pg_temp.id('s8b.v'), 0, pg_temp.doc(pg_temp.id('s8.asset'), 'reviewed', 1), 'z2 removed'); +insert into pg_temp.k values ('s8b', pg_temp.id('s8')), ('s8b.asset', pg_temp.id('s8.asset')); +select pg_temp.round('s8b', 's8b.r', 1, repeat('b8', 32), pg_temp.groups3() || jsonb_build_array(pg_temp.g('zone:z2', 'e'))); +select pg_temp.as_user('V'); +select throws_ok($$ select public.decide_sheet_review(pg_temp.id('s8b.r'), true, 'ok') $$, + 'P0001', 'review.groups.uncovered', 'a removal group is to cover even when every other group equals the base'); +select public.acknowledge_sheet_review_group(pg_temp.id('s8b.r'), 'zone:z2', repeat('e', 64)); +select lives_ok($$ select public.decide_sheet_review(pg_temp.id('s8b.r'), true, 'ok') $$, + 'acknowledging the removal group completes the coverage'); +select pg_temp.as_user('E'); +select public.publish_sheet_version(pg_temp.id('s8b.r')); +select public.deprecate_sheet_version(pg_temp.id('s8.v'), 'superseded'); +select public.archive_anatomical_sheet(pg_temp.id('s8')); +select pg_temp.as_user('R'); +select is(public.get_sheet_version(pg_temp.id('s8.v')) ->> 'status', 'deprecated', + 'D8: a deprecated version of an archived sheet stays readable by id'); +select is(public.get_sheet_version(pg_temp.id('s8b.v')) ->> 'status', 'published', + 'D8: a published version of an archived sheet stays readable by id'); +select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets' and name = repeat('b8', 32) || '.svg'), + 1::bigint, 'D8: the drawing of an archived sheet stays readable'); +select is((select count(*) from jsonb_array_elements(public.list_official_catalog()) e where (e ->> 'sheet_id')::uuid = pg_temp.id('s8')), + 0::bigint, 'an archived sheet leaves the catalogue list'); + +-- ============ F2: an archived sheet is frozen (§6.7, §12.1) ============ +select pg_temp.sheet('s9', repeat('b9', 32)); +select pg_temp.round('s9', 's9.r1', 1, repeat('b9', 32), pg_temp.groups3()); +select pg_temp.ack_all('s9.r1'); +select public.decide_sheet_review(pg_temp.id('s9.r1'), true, 'ok'); +select pg_temp.as_user('E'); +select public.archive_anatomical_sheet(pg_temp.id('s9')); +select throws_ok($$ select public.publish_sheet_version(pg_temp.id('s9.r1')) $$, + '55000', 'sheet.inactive', 'F2: the approved round of an archived sheet is not published'); +select throws_ok($$ select public.save_sheet_draft(pg_temp.id('s9.v'), 1, + jsonb_set(pg_temp.doc(pg_temp.id('s9.asset'), 'reviewed'), '{description,fr}', '"z"'), 'x') $$, + '55000', 'sheet.inactive', 'F2: the draft of an archived sheet is not saved'); +select public.withdraw_sheet_review(pg_temp.id('s9.r1'), 'archived'); +select throws_ok($$ select public.submit_sheet_review(pg_temp.id('s9.v'), 1, 'x') $$, + '55000', 'sheet.inactive', 'F2: the draft of an archived sheet is not submitted'); +select throws_ok($$ select public.create_sheet_draft(pg_temp.id('s9'), null, 'x') $$, + '55000', 'sheet.inactive', 'F2: no draft is opened on an archived sheet'); +select throws_ok($$ select public.delete_sheet_version(pg_temp.id('s9.v')) $$, + '55000', 'version.has_rounds', 'a draft that has rounds is never deleted (D6 trail)'); + +-- ============ Species (§7.2) ============ +select pg_temp.as_user('E'); +select public.create_species('r17sp', 'Espèce', 'Species', 90); +select throws_ok($$ select public.create_species('r17sp', 'Espèce', 'Species', 90) $$, + 'P0001', 'species.exists', 'an existing species id gets one answer'); +select throws_ok($$ select public.create_official_sheet('r17-other', jsonb_set(pg_temp.doc(null, 'reviewed'), '{species_id}', '"other"')) $$, + 'P0001', 'sheet.species_invalid', 'no official sheet for the species other'); +select throws_ok($$ select public.create_official_sheet('r17-nosuch', jsonb_set(pg_temp.doc(null, 'reviewed'), '{species_id}', '"r17nosuch"')) $$, + 'P0001', 'sheet.species_invalid', 'no official sheet for an unknown species'); +select throws_ok($$ select public.rename_species('r17sp', 'A', 'A') $$, + '42501', 'rights.owner', 'an editor cannot rename a species'); +select pg_temp.as_user('V'); +select throws_ok($$ select public.update_inactive_species('r17sp', 'A', 'A', 1) $$, + '42501', 'rights.capability', 'a reviewer cannot edit an inactive species'); +select pg_temp.as_user('E'); +select lives_ok($$ select public.update_inactive_species('r17sp', 'Espèce B', 'Species B', 91) $$, + 'an editor edits an inactive species'); +select pg_temp.as_user('O'); +select throws_ok($$ select public.rename_species('r17sp', 'A', 'A') $$, + 'P0001', 'species.not_active', 'renaming applies to an active species only'); +select public.activate_species('r17sp'); +select lives_ok($$ select public.rename_species('r17sp', 'Espèce C', 'Species C') $$, + 'the owner corrects an active species'' names'); +select pg_temp.as_user('E'); +select throws_ok($$ select public.update_inactive_species('r17sp', 'A', 'A', 1) $$, + 'P0001', 'species.not_inactive', 'an editor no longer edits an active species'); + +-- ============ Working copy of the historical sheet (§14.3) ============ +reset role; +-- Any working copy already active on this stack is archived inside this +-- transaction, so the slot rules are tested from a known state (LRN-093). +update public.anatomical_sheets set status = 'archived', archived_at = now() + where status = 'active' and private.is_historical_working_copy(id); +insert into pg_temp.k select 'h.v', id from public.anatomical_sheet_versions where sheet_id = '503dc301-a8b1-50d4-9e44-0919b2fc2916'; +insert into pg_temp.k select 'h.pending', '00000000-0000-0000-0000-000000000001'::uuid + where exists (select 1 from public.anatomical_sheet_assets + where sheet_id = '503dc301-a8b1-50d4-9e44-0919b2fc2916' and uploaded_at is null); +select pg_temp.as_user('E'); +select case when pg_temp.id('h.pending') is not null + then throws_ok($$ select public.create_sheet_working_copy(pg_temp.id('h.v'), 'r17-wc0') $$, + 'P0001', 'working_copy.assets_missing', 'a working copy is refused while a source drawing is not confirmed') + else skip('the historical drawing is already confirmed on this stack', 1) end; +reset role; +insert into storage.objects (bucket_id, name, metadata) + select 'anatomical-sheet-assets', a.sha256 || '.svg', jsonb_build_object('size', a.byte_size) + from public.anatomical_sheet_assets a where a.sheet_id = '503dc301-a8b1-50d4-9e44-0919b2fc2916' + on conflict do nothing; +update public.anatomical_sheet_assets set uploaded_at = now() + where sheet_id = '503dc301-a8b1-50d4-9e44-0919b2fc2916' and uploaded_at is null; +create table pg_temp.h_version as + select id, content, revision, authors, status, change_note, updated_at from public.anatomical_sheet_versions + where sheet_id = '503dc301-a8b1-50d4-9e44-0919b2fc2916'; +create table pg_temp.h_assets as + select * from public.anatomical_sheet_assets where sheet_id = '503dc301-a8b1-50d4-9e44-0919b2fc2916'; +create table pg_temp.h_sheet as + select * from public.anatomical_sheets where id = '503dc301-a8b1-50d4-9e44-0919b2fc2916'; +select pg_temp.as_user('E'); +insert into pg_temp.k select 'wc1', public.create_sheet_working_copy(pg_temp.id('h.v'), 'r17-wc1'); +reset role; +select results_eq( + $$ select id, content, revision, authors, status, change_note, updated_at from public.anatomical_sheet_versions + where sheet_id = '503dc301-a8b1-50d4-9e44-0919b2fc2916' $$, + $$ select * from pg_temp.h_version $$, + 'the working copy leaves the source version unchanged'); +select results_eq( + $$ select * from public.anatomical_sheet_assets where sheet_id = '503dc301-a8b1-50d4-9e44-0919b2fc2916' order by id $$, + $$ select * from pg_temp.h_assets order by id $$, + 'the working copy leaves the source drawing rows unchanged'); +select results_eq( + $$ select * from public.anatomical_sheets where id = '503dc301-a8b1-50d4-9e44-0919b2fc2916' $$, + $$ select * from pg_temp.h_sheet $$, + 'the working copy leaves the historical sheet row unchanged'); +select is( + (select c.content from public.anatomical_sheet_versions c where c.sheet_id = pg_temp.id('wc1')), + (select private.remap_document_assets(s.content, + (select jsonb_object_agg(ha.id::text, ca.id::text) + from public.anatomical_sheet_assets ha + join public.anatomical_sheet_assets ca on ca.sha256 = ha.sha256 and ca.sheet_id = pg_temp.id('wc1') + where ha.sheet_id = '503dc301-a8b1-50d4-9e44-0919b2fc2916')) + from public.anatomical_sheet_versions s where s.id = pg_temp.id('h.v')), + 'statuses verbatim: the copy is the source document with only its drawing ids remapped'); +select pg_temp.as_user('E'); +select throws_ok($$ select public.create_sheet_working_copy(pg_temp.id('h.v'), 'r17-wc2') $$, + 'P0001', 'working_copy.exists', 'one active working copy of the historical sheet at a time'); +select public.archive_anatomical_sheet(pg_temp.id('wc1')); +select throws_ok($$ select public.create_sheet_working_copy(pg_temp.id('h.v'), 'r17-wc1') $$, + 'P0001', 'sheet.slug_taken', 'an archived sheet keeps its slug'); +insert into pg_temp.k select 'wc2', public.create_sheet_working_copy(pg_temp.id('h.v'), 'r17-wc2'); +select ok(pg_temp.id('wc2') is not null, 'archiving a working copy frees the slot'); +select throws_ok($$ select public.restore_anatomical_sheet(pg_temp.id('wc1')) $$, + 'P0001', 'working_copy.exists', 'restoring a copy while another one is active is refused'); + +-- ============ Closed codes and the lifecycle (§6.2, §6.9, §9.3, §12.2) ============ +select pg_temp.sheet('s13', repeat('bd', 32)); +insert into pg_temp.k select 's13.extra', public.register_sheet_asset(pg_temp.id('s13'), repeat('be', 32), 100, 'e.svg'); +select lives_ok($$ select public.delete_sheet_asset(pg_temp.id('s13.extra')) $$, 'an unreferenced drawing row is deleted'); +select throws_ok($$ select public.delete_sheet_asset(pg_temp.id('s13.asset')) $$, + '55000', 'asset.referenced', 'a drawing referenced by a version is kept'); +select throws_ok($$ select public.delete_sheet_asset((select id from public.anatomical_sheet_assets + where sheet_id = '503dc301-a8b1-50d4-9e44-0919b2fc2916' limit 1)) $$, + '42501', 'sheet.historical_read_only', 'the historical sheet''s drawing row is never deleted'); +select throws_ok($$ select public.create_official_sheet('r17-s13', pg_temp.doc(null, 'reviewed')) $$, + 'P0001', 'sheet.slug_taken', 'a slug already used by an official sheet'); +select throws_ok($$ select public.create_official_sheet('Bad Slug', pg_temp.doc(null, 'reviewed')) $$, + 'P0001', 'invalid_input', 'a slug outside the format'); +select throws_ok($$ select public.save_sheet_draft(pg_temp.id('s13.v'), 1, + jsonb_set(pg_temp.doc(pg_temp.id('s13.asset'), 'reviewed'), '{pad}', to_jsonb(repeat('x', 2100000))), 'x') $$, + '23514', 'document.too_large', 'save refuses a document over 2 MiB serialised'); +select throws_ok($$ select public.save_sheet_draft(pg_temp.id('s13.v'), 1, + jsonb_set(pg_temp.doc(pg_temp.id('s13.asset'), 'reviewed'), '{pad}', + (select jsonb_agg(jsonb_build_object('a', 1)) from generate_series(1, 100000))), 'x') $$, + '23514', 'document.too_large', 'a document under 2 MiB as text but over it as stored jsonb gets the closed code'); +select throws_ok($$ select public.save_sheet_draft(pg_temp.id('s13.v'), 1, + jsonb_set(pg_temp.doc(pg_temp.id('s13.asset'), 'reviewed'), '{species_id}', '"canine"'), 'x') $$, + '23514', 'document.species', 'save refuses a document of another species'); +select throws_ok($$ select public.save_sheet_draft(pg_temp.id('s13.v'), 1, + jsonb_set(pg_temp.doc(pg_temp.id('s13.asset'), 'reviewed'), '{annotations}', '{}'), 'x') $$, + '23514', 'document.shape', 'save refuses a collection that is not an array'); +select throws_ok($$ select public.save_sheet_draft(pg_temp.id('s13.v'), 1, + jsonb_set(pg_temp.doc(pg_temp.id('s13.asset'), 'reviewed'), '{schema_version}', '3'), 'x') $$, + '23514', 'document.schema_version', 'save refuses another schema version'); +select throws_ok($$ select public.create_sheet_draft(pg_temp.id('m3'), null, 'x') $$, + 'P0001', 'draft.exists', 'one draft per sheet'); +select public.publish_sheet_version(pg_temp.id('m3b.r')); +select throws_ok($$ select public.publish_sheet_version(pg_temp.id('m3b.r')) $$, + '55000', 'draft.not_a_draft', 'a round is published once'); +select public.deprecate_sheet_version(pg_temp.id('m3b.v'), 'rollback'); +select is((select current_version_id from public.anatomical_sheets where id = pg_temp.id('m3')), pg_temp.id('m3.v'), + 'deprecating the current version makes the latest remaining published one current'); +select public.deprecate_sheet_version(pg_temp.id('m3.v'), 'gone'); +select is((select current_version_id from public.anatomical_sheets where id = pg_temp.id('m3')), null, + 'with no published version left the sheet has no current version'); +select throws_ok($$ select public.delete_anatomical_sheet(pg_temp.id('m3')) $$, + '55000', 'sheet.published_history', 'a sheet that was ever published is never deleted'); +select public.delete_sheet_version(pg_temp.id('m4b.v')); +insert into pg_temp.k select 'm4c.v', public.create_sheet_draft('17200000-0000-0000-0000-000000000004', null, 'again'); +select is((select version_number from public.anatomical_sheet_versions where id = pg_temp.id('m4c.v')), 3, + 'a deleted version''s number is never reused'); +select public.delete_sheet_version(pg_temp.id('s13.v')); +select lives_ok($$ select public.delete_anatomical_sheet(pg_temp.id('s13')) $$, 'a draft-only sheet is deleted'); +select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('s13')), 0::bigint, + 'a deleted sheet is invisible, capability holders included'); + +-- ============ Audit (§13): every lifecycle step of a sheet is recorded ============ +reset role; +select results_eq( + $$ select action from audit.audit_logs + where resource_id in (pg_temp.id('m1'), pg_temp.id('m1.v'), pg_temp.id('m1.asset'), pg_temp.id('m1.r'), + pg_temp.id('m2'), pg_temp.id('m2.v'), pg_temp.id('m2b.v'), pg_temp.id('m2.asset'), + pg_temp.id('m2.r1'), pg_temp.id('m2b.r')) + group by action order by action collate "C" $$, + $$ values ('anatomical_sheet.archived'), ('anatomical_sheet.created'), ('anatomical_sheet.restored'), + ('anatomical_sheet_asset.registered'), ('anatomical_sheet_asset.uploaded'), + ('anatomical_sheet_review.acknowledged'), ('anatomical_sheet_review.approved'), + ('anatomical_sheet_review.submitted'), ('anatomical_sheet_version.created'), + ('anatomical_sheet_version.deprecated'), ('anatomical_sheet_version.published'), + ('anatomical_sheet_version.saved') $$, + 'every lifecycle step left its audit event'); + +select * from finish(); +rollback; diff --git a/supabase/tests/018_sheet_access_matrix.sql b/supabase/tests/018_sheet_access_matrix.sql new file mode 100644 index 00000000..ee05ae1a --- /dev/null +++ b/supabase/tests/018_sheet_access_matrix.sql @@ -0,0 +1,295 @@ +-- V1-2.1 M4/M5: who reads and calls what (contract §5.3, §5.4, §5.6, §15), +-- after the independent audit (M3). Table-driven: every catalogue RPC is +-- called by every actor class that must be refused (owner, admin, moderator, +-- support and a plain account without capability at aal2; capability and +-- reader holders at aal1; deactivated and unconfirmed accounts), each policy +-- is read by every actor class, and the capabilities are crossed. The refused +-- calls write nothing. Fixtures are scoped to the ids created here. +begin; +select plan(337); + +-- Accounts. Suffixes: O owner, A admin, M moderator, S support, E admin + +-- editor, V reviewer, P admin + publisher, R reader, RX expired reader, RR +-- revoked reader, RD deactivated reader, RU unconfirmed reader, N no right. +create table pg_temp.who (label text primary key, id uuid not null); +insert into pg_temp.who values + ('O', '18000000-0000-0000-0000-000000000001'), ('A', '18000000-0000-0000-0000-00000000000a'), + ('M', '18000000-0000-0000-0000-00000000000b'), ('S', '18000000-0000-0000-0000-00000000000c'), + ('E', '18000000-0000-0000-0000-00000000000e'), ('V', '18000000-0000-0000-0000-0000000000f1'), + ('P', '18000000-0000-0000-0000-00000000000f'), ('R', '18000000-0000-0000-0000-0000000000cc'), + ('RX', '18000000-0000-0000-0000-0000000000c1'), ('RR', '18000000-0000-0000-0000-0000000000c2'), + ('RD', '18000000-0000-0000-0000-0000000000c3'), ('RU', '18000000-0000-0000-0000-0000000000c4'), + ('N', '18000000-0000-0000-0000-0000000000c5'); +insert into auth.users (id, email, email_confirmed_at) +select id, lower(label) || '@m18.local', case when label = 'RU' then null else now() end from pg_temp.who; +insert into auth.mfa_factors (id, user_id, factor_type, status, created_at, updated_at) +select gen_random_uuid(), id, 'totp', 'verified', now(), now() from pg_temp.who; +insert into auth.sessions (id, user_id, aal) +select ('18100000' || substr(id::text, 9))::uuid, id, 'aal2' from pg_temp.who; +update public.profiles set active = false where id = '18000000-0000-0000-0000-0000000000c3'; + +select set_config('request.jwt.claims', '', true); +select private.assign_platform_role(null, '18000000-0000-0000-0000-000000000001', 'owner'); +select private.assign_platform_role(null, '18000000-0000-0000-0000-00000000000a', 'admin'); +select private.assign_platform_role(null, '18000000-0000-0000-0000-00000000000b', 'moderator'); +select private.assign_platform_role(null, '18000000-0000-0000-0000-00000000000c', 'support'); +select private.assign_platform_role(null, '18000000-0000-0000-0000-00000000000e', 'admin'); +select private.assign_platform_role(null, '18000000-0000-0000-0000-00000000000f', 'admin'); +insert into public.anatomical_catalog_grants (user_id, grant_kind, reason, verification_note, granted_by, granted_at, expires_at, + revoked_at, revoked_by, revocation_reason) values + ('18000000-0000-0000-0000-00000000000e', 'sheet_editor', 'a', 'c', '18000000-0000-0000-0000-000000000001', now(), null, null, null, null), + ('18000000-0000-0000-0000-0000000000f1', 'sheet_reviewer', 'a', 'c', '18000000-0000-0000-0000-000000000001', now(), null, null, null, null), + ('18000000-0000-0000-0000-00000000000f', 'sheet_publisher', 'a', 'c', '18000000-0000-0000-0000-000000000001', now(), null, null, null, null), + ('18000000-0000-0000-0000-0000000000cc', 'catalog_reader', 'a', null, '18000000-0000-0000-0000-000000000001', now(), null, null, null, null), + ('18000000-0000-0000-0000-0000000000c1', 'catalog_reader', 'a', null, '18000000-0000-0000-0000-000000000001', + now() - interval '2 days', now() - interval '1 day', null, null, null), + ('18000000-0000-0000-0000-0000000000c2', 'catalog_reader', 'a', null, '18000000-0000-0000-0000-000000000001', + now(), null, now(), '18000000-0000-0000-0000-000000000001', 'ended'), + ('18000000-0000-0000-0000-0000000000c3', 'catalog_reader', 'a', null, '18000000-0000-0000-0000-000000000001', now(), null, null, null, null), + ('18000000-0000-0000-0000-0000000000c4', 'catalog_reader', 'a', null, '18000000-0000-0000-0000-000000000001', now(), null, null, null, null); + +-- Catalogue fixtures, labelled: SP active sheet with a deprecated v1 and a +-- published v2 (drawing a1), a draft v3 (drawing a2) under an open round with a +-- comment and an acknowledgment, a pending drawing a3; SD a draft-only sheet; +-- SA an archived sheet with a published v1 (drawing a4). Every drawing has an +-- object; a3's row is pending. +create table pg_temp.k (key text primary key, id uuid not null); +insert into pg_temp.k values + ('SP', '18200000-0000-0000-0000-000000000001'), ('SD', '18200000-0000-0000-0000-000000000002'), + ('SA', '18200000-0000-0000-0000-000000000003'), + ('SP.v1', '18300000-0000-0000-0000-000000000011'), ('SP.v2', '18300000-0000-0000-0000-000000000012'), + ('SP.v3', '18300000-0000-0000-0000-000000000013'), ('SD.v1', '18300000-0000-0000-0000-000000000021'), + ('SA.v1', '18300000-0000-0000-0000-000000000031'), + ('a1', '18400000-0000-0000-0000-000000000001'), ('a2', '18400000-0000-0000-0000-000000000002'), + ('a3', '18400000-0000-0000-0000-000000000003'), ('a4', '18400000-0000-0000-0000-000000000004'), + ('SP.r', '18500000-0000-0000-0000-000000000001'); +create function pg_temp.id(p_key text) returns uuid language sql stable as $$ select id from pg_temp.k where key = p_key $$; +create function pg_temp.doc(p_asset uuid) returns jsonb language sql as $$ + select jsonb_build_object('schema_version', 2, 'species_id', 'equine', 'name', jsonb_build_object('fr', 'M', 'en', 'M'), + 'description', jsonb_build_object('fr', 'd', 'en', 'd'), 'scope_disclaimer', jsonb_build_object('fr', 'x', 'en', 'x'), + 'attribution', jsonb_build_object('authors', '[]'::jsonb, 'license', null, 'notes', null), + 'vertebral_config', jsonb_build_object('regions', '[]'::jsonb), 'references', '[]'::jsonb, 'categories', '[]'::jsonb, + 'views', jsonb_build_array(jsonb_build_object('id', 'main', 'kind', 'main', 'name', jsonb_build_object('fr', 'V', 'en', 'V'), + 'svg_asset_id', p_asset, 'view_box', null)), + 'annotations', '[]'::jsonb, 'finding_zones', '[]'::jsonb); +$$; +select set_config('request.jwt.claims', '{"sub":"18000000-0000-0000-0000-00000000000e"}', true); +insert into public.anatomical_sheets (id, species_id, name, slug, is_official, visibility, status, archived_at) values + (pg_temp.id('SP'), 'equine', 'SP', 'm18-sp', true, 'private', 'active', null), + (pg_temp.id('SD'), 'equine', 'SD', 'm18-sd', true, 'private', 'active', null), + (pg_temp.id('SA'), 'equine', 'SA', 'm18-sa', true, 'private', 'archived', now()); +insert into public.anatomical_sheet_assets (id, sheet_id, sha256, byte_size, file_name, uploaded_at) values + (pg_temp.id('a1'), pg_temp.id('SP'), repeat('c1', 32), 100, 'a1.svg', now()), + (pg_temp.id('a2'), pg_temp.id('SP'), repeat('c2', 32), 100, 'a2.svg', now()), + (pg_temp.id('a3'), pg_temp.id('SP'), repeat('c3', 32), 100, 'a3.svg', null), + (pg_temp.id('a4'), pg_temp.id('SA'), repeat('c4', 32), 100, 'a4.svg', now()); +insert into storage.objects (bucket_id, name, metadata) +select 'anatomical-sheet-assets', repeat(c, 32) || '.svg', '{"size":100}' from unnest(array['c1', 'c2', 'c3', 'c4']) c +on conflict do nothing; +insert into public.anatomical_sheet_versions (id, sheet_id, version_number, status, document_schema_version, content, + published_at, deprecated_at, document_fingerprint) values + (pg_temp.id('SP.v1'), pg_temp.id('SP'), 1, 'deprecated', 2, pg_temp.doc(pg_temp.id('a1')), now(), now(), repeat('0', 64)), + (pg_temp.id('SP.v2'), pg_temp.id('SP'), 2, 'published', 2, pg_temp.doc(pg_temp.id('a1')), now(), null, repeat('0', 64)), + (pg_temp.id('SP.v3'), pg_temp.id('SP'), 3, 'draft', 2, pg_temp.doc(pg_temp.id('a2')), null, null, null), + (pg_temp.id('SD.v1'), pg_temp.id('SD'), 1, 'draft', 2, pg_temp.doc(null), null, null, null), + (pg_temp.id('SA.v1'), pg_temp.id('SA'), 1, 'published', 2, pg_temp.doc(pg_temp.id('a4')), now(), null, repeat('0', 64)); +update public.anatomical_sheets set current_version_id = pg_temp.id('SP.v2'), last_version_number = 3 where id = pg_temp.id('SP'); +update public.anatomical_sheets set last_version_number = 1 where id = pg_temp.id('SD'); +update public.anatomical_sheets set current_version_id = pg_temp.id('SA.v1'), last_version_number = 1 where id = pg_temp.id('SA'); +insert into public.anatomical_sheet_reviews (id, version_id, round, revision, authors, submitted_by, status, verdict, verified_at) + values (pg_temp.id('SP.r'), pg_temp.id('SP.v3'), 1, 0, array['18000000-0000-0000-0000-00000000000e'::uuid], + '18000000-0000-0000-0000-00000000000e', 'open', + jsonb_build_object('fingerprint', repeat('a', 64), 'drawings', '[]'::jsonb, + 'groups', jsonb_build_array(jsonb_build_object('key', 'general', 'digest', repeat('1', 64), 'coverable', true))), now()); +insert into public.anatomical_sheet_review_comments (review_id, author, body) values (pg_temp.id('SP.r'), '18000000-0000-0000-0000-0000000000f1', 'c'); +insert into public.anatomical_sheet_review_acknowledgments (review_id, group_key, group_digest, reviewer) + values (pg_temp.id('SP.r'), 'general', repeat('1', 64), '18000000-0000-0000-0000-0000000000f1'); +insert into public.species (id, name_fr, name_en, sort_order, active) values ('m18inactive', 'I', 'I', 99, false); +insert into pg_temp.k select 'h.v', id from public.anatomical_sheet_versions where sheet_id = '503dc301-a8b1-50d4-9e44-0919b2fc2916'; + +-- The calling session of an account at an assurance level (aal2 names its +-- live session row; aal1 a session that never reached aal2). +create function pg_temp.as_user(p text, p_aal text) returns void language plpgsql as $$ +declare v_id uuid := (select id from pg_temp.who where label = p); +begin + perform set_config('role', 'authenticated', true); + perform set_config('request.jwt.claims', jsonb_build_object('sub', v_id, 'role', 'authenticated', 'aal', p_aal, + 'session_id', case when p_aal = 'aal2' then ('18100000' || substr(v_id::text, 9))::uuid else gen_random_uuid() end)::text, true); +end $$; +-- The outcome of a statement: its single value, or its SQLSTATE and message. +create function pg_temp.val(p_sql text) returns text language plpgsql as $$ +declare v text; +begin + execute p_sql into v; + return coalesce(v, 'ok'); +exception when others then + return sqlstate || ' ' || sqlerrm; +end $$; +-- What the caller reads of the fixtures, through the policies. +create function pg_temp.visible() returns text language sql as $$ + select 'sheets=' || coalesce((select string_agg(k.key, ',' order by k.key collate "C") from public.anatomical_sheets s join pg_temp.k k on k.id = s.id), '') + || ';versions=' || coalesce((select string_agg(k.key, ',' order by k.key collate "C") from public.anatomical_sheet_versions v join pg_temp.k k on k.id = v.id and k.key <> 'h.v'), '') + || ';assets=' || coalesce((select string_agg(k.key, ',' order by k.key collate "C") from public.anatomical_sheet_assets a join pg_temp.k k on k.id = a.id), '') + || ';objects=' || coalesce((select string_agg(k.key, ',' order by k.key collate "C") from storage.objects o + join pg_temp.k k on k.key in ('a1', 'a2', 'a3', 'a4') and o.name = repeat('c' || right(k.key, 1), 32) || '.svg' + where o.bucket_id = 'anatomical-sheet-assets'), '') + || ';reviews=' || (select count(*) from public.anatomical_sheet_reviews where id = pg_temp.id('SP.r')) + || ';comments=' || (select count(*) from public.anatomical_sheet_review_comments where review_id = pg_temp.id('SP.r')) + || ';acks=' || (select count(*) from public.anatomical_sheet_review_acknowledgments where review_id = pg_temp.id('SP.r')); +$$; +-- The fixture sheets the catalogue list names, or the refusal. +create function pg_temp.catalogue() returns text language plpgsql as $$ +begin + return coalesce((select string_agg(k.key, ',' order by k.key collate "C") from jsonb_array_elements(public.list_official_catalog()) e + join pg_temp.k k on k.id = (e ->> 'sheet_id')::uuid), ''); +exception when others then + return sqlstate || ' ' || sqlerrm; +end $$; + +-- Every catalogue RPC an actor without the matching right must be refused. +create table pg_temp.calls (n int primary key, name text not null, sql text not null); +insert into pg_temp.calls values + (1, 'create_official_sheet', $$ select public.create_official_sheet('m18-new', pg_temp.doc(null)) $$), + (2, 'create_sheet_draft', $$ select public.create_sheet_draft(pg_temp.id('SP'), null, 'x') $$), + (3, 'save_sheet_draft', $$ select public.save_sheet_draft(pg_temp.id('SP.v3'), 0, pg_temp.doc(null), 'x') $$), + (4, 'submit_sheet_review', $$ select public.submit_sheet_review(pg_temp.id('SP.v3'), 0, 'x') $$), + (5, 'withdraw_sheet_review', $$ select public.withdraw_sheet_review(pg_temp.id('SP.r'), 'x') $$), + (6, 'comment_sheet_review', $$ select public.comment_sheet_review(pg_temp.id('SP.r'), 'x', null) $$), + (7, 'acknowledge_sheet_review_group', $$ select public.acknowledge_sheet_review_group(pg_temp.id('SP.r'), 'general', repeat('1', 64)) $$), + (8, 'decide_sheet_review', $$ select public.decide_sheet_review(pg_temp.id('SP.r'), true, 'x') $$), + (9, 'publish_sheet_version', $$ select public.publish_sheet_version(pg_temp.id('SP.r')) $$), + (10, 'deprecate_sheet_version', $$ select public.deprecate_sheet_version(pg_temp.id('SP.v2'), 'x') $$), + (11, 'archive_anatomical_sheet', $$ select public.archive_anatomical_sheet(pg_temp.id('SP')) $$), + (12, 'restore_anatomical_sheet', $$ select public.restore_anatomical_sheet(pg_temp.id('SA')) $$), + (13, 'delete_anatomical_sheet', $$ select public.delete_anatomical_sheet(pg_temp.id('SD')) $$), + (14, 'delete_sheet_version', $$ select public.delete_sheet_version(pg_temp.id('SD.v1')) $$), + (15, 'create_sheet_working_copy', $$ select public.create_sheet_working_copy(pg_temp.id('h.v'), 'm18-wc') $$), + (16, 'create_species', $$ select public.create_species('m18new', 'N', 'N', 1) $$), + (17, 'update_inactive_species', $$ select public.update_inactive_species('m18inactive', 'N', 'N', 1) $$), + (18, 'list_catalog_species', $$ select case when public.list_catalog_species() is not null then 'ok' end $$), + (19, 'register_sheet_asset', $$ select public.register_sheet_asset(pg_temp.id('SP'), repeat('c9', 32), 100, 'x.svg') $$), + (20, 'confirm_sheet_asset_upload', $$ select public.confirm_sheet_asset_upload(pg_temp.id('a3')) $$), + (21, 'delete_sheet_asset', $$ select public.delete_sheet_asset(pg_temp.id('a3')) $$); +-- Every call, by one actor, with one expected outcome (the owner lists species). +create function pg_temp.matrix(p text, p_aal text, p_expect text) returns setof text language plpgsql as $$ +declare c record; +begin + for c in select * from pg_temp.calls order by n loop + perform pg_temp.as_user(p, p_aal); + return next is(pg_temp.val(c.sql), + case when p = 'O' and p_aal = 'aal2' and c.name = 'list_catalog_species' then 'ok' else p_expect end, + p || ' at ' || p_aal || ': ' || c.name); + end loop; +end $$; +-- Named calls by an actor that holds another capability: each refused. +create function pg_temp.crossed(p text, p_names text[]) returns setof text language plpgsql as $$ +declare c record; +begin + for c in select * from pg_temp.calls where name = any (p_names) order by n loop + perform pg_temp.as_user(p, 'aal2'); + return next is(pg_temp.val(c.sql), '42501 rights.capability', p || ' holds another capability: ' || c.name); + end loop; +end $$; +-- The four reads of one actor: fixtures through the policies, the catalogue +-- list, an archived sheet's published version by id, a draft by id. +create function pg_temp.reads(p text, p_aal text, p_visible text, p_catalogue text, p_archived text, p_draft text) +returns setof text language plpgsql as $f$ +begin + perform pg_temp.as_user(p, p_aal); + return next is(pg_temp.visible(), p_visible, p || ' at ' || p_aal || ': rows through the policies'); + return next is(pg_temp.catalogue(), p_catalogue, p || ' at ' || p_aal || ': catalogue list'); + return next is(pg_temp.val($$ select public.get_sheet_version(pg_temp.id('SA.v1')) ->> 'status' $$), p_archived, + p || ' at ' || p_aal || ': published version of an archived sheet by id'); + return next is(pg_temp.val($$ select public.get_sheet_version(pg_temp.id('SP.v3')) ->> 'status' $$), p_draft, + p || ' at ' || p_aal || ': draft by id'); +end $f$; +grant all on pg_temp.who, pg_temp.k, pg_temp.calls to authenticated; +grant execute on all functions in schema pg_temp to authenticated; + +-- ============ §5.3 catalogue access and the read policies, per actor ============ +create table pg_temp.views (label text primary key, visible text not null); +insert into pg_temp.views values + ('none', 'sheets=;versions=;assets=;objects=;reviews=0;comments=0;acks=0'), + ('reader', 'sheets=SA,SP;versions=SA.v1,SP.v1,SP.v2;assets=a1,a4;objects=a1,a4;reviews=0;comments=0;acks=0'), + ('staff', 'sheets=SA,SD,SP;versions=SA.v1,SD.v1,SP.v1,SP.v2,SP.v3;assets=a1,a2,a3,a4;objects=a1,a2,a4;reviews=1;comments=1;acks=1'); +grant select on pg_temp.views to authenticated; +select pg_temp.reads(a.p, a.aal, (select visible from pg_temp.views where label = 'none'), + '42501 rights.catalog', '42501 not_found', '42501 not_found') +from (values ('O', 'aal2'), ('A', 'aal2'), ('M', 'aal2'), ('S', 'aal2'), ('N', 'aal2'), + ('RX', 'aal1'), ('RR', 'aal1'), ('RD', 'aal1'), ('RU', 'aal1')) a(p, aal); +select pg_temp.reads(a.p, a.aal, (select visible from pg_temp.views where label = 'reader'), + 'SP', 'published', '42501 not_found') +from (values ('R', 'aal1'), ('E', 'aal1'), ('V', 'aal1'), ('P', 'aal1')) a(p, aal); +select pg_temp.reads(a.p, 'aal2', (select visible from pg_temp.views where label = 'staff'), + 'SP', 'published', 'draft') +from (values ('E'), ('V'), ('P')) a(p); + +-- Anonymous: no table privilege, no catalogue RPC. +reset role; +set local role anon; +select set_config('request.jwt.claims', '{"role":"anon"}', true); +select throws_ok($$ select id from public.anatomical_sheets $$, '42501', null, 'anon cannot read sheets'); +select throws_ok($$ select id from public.anatomical_sheet_versions $$, '42501', null, 'anon cannot read versions'); +select throws_ok($$ select public.get_sheet_version('18300000-0000-0000-0000-000000000031') $$, '42501', null, 'anon cannot call the read RPCs'); +reset role; +select is( + (select count(*) from pg_proc p join pg_namespace n on n.oid = p.pronamespace + where n.nspname = 'public' and p.proname ~ '(sheet|species|catalog|platform_role)' + and has_function_privilege('anon', p.oid, 'execute')), + 0::bigint, 'anon executes no catalogue or role RPC'); +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 = 'public' and p.proname ~ '(sheet|species|catalog|platform_role)' + and has_function_privilege('service_role', p.oid, 'execute')), + 'confirm_sheet_asset_upload,get_sheet_asset_state', + 'service_role executes only the upload confirmation and the operator read (§5.4)'); + +-- ============ F14 and §5.6: every catalogue RPC refused without the right ============ +select pg_temp.matrix('O', 'aal2', '42501 rights.capability'); +select pg_temp.matrix('A', 'aal2', '42501 rights.capability'); +select pg_temp.matrix('M', 'aal2', '42501 rights.capability'); +select pg_temp.matrix('S', 'aal2', '42501 rights.capability'); +select pg_temp.matrix('N', 'aal2', '42501 rights.capability'); +select pg_temp.matrix('R', 'aal1', '42501 rights.mfa'); +select pg_temp.matrix('E', 'aal1', '42501 rights.mfa'); +select pg_temp.matrix('V', 'aal1', '42501 rights.mfa'); +select pg_temp.matrix('P', 'aal1', '42501 rights.mfa'); +select pg_temp.matrix('RD', 'aal2', '42501 rights.account'); +select pg_temp.matrix('RU', 'aal2', '42501 rights.account'); + +-- ============ §5.4: one capability never stands for another ============ +select pg_temp.crossed('E', array['acknowledge_sheet_review_group', 'decide_sheet_review', 'publish_sheet_version', + 'deprecate_sheet_version', 'archive_anatomical_sheet', 'restore_anatomical_sheet']); +select pg_temp.crossed('V', array['create_official_sheet', 'create_sheet_draft', 'save_sheet_draft', 'submit_sheet_review', + 'withdraw_sheet_review', 'publish_sheet_version', 'deprecate_sheet_version', 'archive_anatomical_sheet', + 'delete_anatomical_sheet', 'delete_sheet_version', 'create_sheet_working_copy', 'create_species', + 'register_sheet_asset', 'confirm_sheet_asset_upload', 'delete_sheet_asset']); +select pg_temp.crossed('P', array['create_official_sheet', 'save_sheet_draft', 'submit_sheet_review', 'withdraw_sheet_review', + 'acknowledge_sheet_review_group', 'decide_sheet_review', 'register_sheet_asset', 'create_species']); + +-- ============ Species activation and renaming: the owner at aal2 only (§7.2) ============ +select pg_temp.as_user('A', 'aal2'); +select is(pg_temp.val($$ select public.activate_species('m18inactive') $$), '42501 rights.owner', 'an admin cannot activate a species'); +select pg_temp.as_user('O', 'aal1'); +select is(pg_temp.val($$ select public.activate_species('m18inactive') $$), '42501 rights.mfa', 'the owner at aal1 cannot activate a species'); +select pg_temp.as_user('O', 'aal2'); +select is(pg_temp.val($$ select public.activate_species('m18inactive') $$), 'm18inactive', 'the owner at aal2 activates a species'); +select pg_temp.as_user('A', 'aal2'); +select is(pg_temp.val($$ select public.rename_species('m18inactive', 'X', 'X') $$), '42501 rights.owner', 'an admin cannot rename a species'); + +-- ============ The grants table: own rows, the owner, staff (§5.2) ============ +create function pg_temp.grants_seen() returns bigint language sql as $$ + select count(*) from public.anatomical_catalog_grants g join pg_temp.who w on w.id = g.user_id; +$$; +grant execute on function pg_temp.grants_seen() to authenticated; +select pg_temp.as_user('R', 'aal1'); +select is(pg_temp.grants_seen(), 1::bigint, 'a reader sees only its own grant'); +select pg_temp.as_user('A', 'aal2'); +select is(pg_temp.grants_seen(), 0::bigint, 'an admin without a grant sees none'); +select pg_temp.as_user('E', 'aal2'); +select is(pg_temp.grants_seen(), 3::bigint, 'a capability holder at aal2 sees the capability grants, not the reader grants'); +select pg_temp.as_user('O', 'aal2'); +select is(pg_temp.grants_seen(), 8::bigint, 'the owner at aal2 sees every grant'); + +select * from finish(); +rollback; diff --git a/supabase/tests/019_sheet_immutability.sql b/supabase/tests/019_sheet_immutability.sql new file mode 100644 index 00000000..79033d95 --- /dev/null +++ b/supabase/tests/019_sheet_immutability.sql @@ -0,0 +1,185 @@ +-- V1-2.1 M4/M5: what no role changes, the table owner included (contract §6.8, +-- §6.9, §9.1, §12.1 F13 F16, §14.2), and the Storage rules the rewrite of 005, +-- 006 and 007 had stopped testing (§9.3, §9.4, §9.5), after the independent +-- audit (M3). Most statements run as the table owner on purpose: the guards are +-- triggers and constraints, not privileges. Fixtures are scoped to this file. +begin; +select plan(38); + +insert into auth.users (id, email, email_confirmed_at) values + ('19000000-0000-0000-0000-000000000001', 'own@i19.local', now()), + ('19000000-0000-0000-0000-00000000000e', 'ed@i19.local', now()), + ('19000000-0000-0000-0000-0000000000cc', 'reader@i19.local', now()); +insert into auth.mfa_factors (id, user_id, factor_type, status, created_at, updated_at) +select gen_random_uuid(), id, 'totp', 'verified', now(), now() from auth.users where email like '%@i19.local'; +insert into auth.sessions (id, user_id, aal) +select ('19100000' || substr(id::text, 9))::uuid, id, 'aal2' from auth.users where email like '%@i19.local'; +select set_config('request.jwt.claims', '', true); +select private.assign_platform_role(null, '19000000-0000-0000-0000-000000000001', 'owner'); +select private.assign_platform_role(null, '19000000-0000-0000-0000-00000000000e', 'admin'); +insert into public.anatomical_catalog_grants (user_id, grant_kind, reason, verification_note, granted_by) values + ('19000000-0000-0000-0000-00000000000e', 'sheet_editor', 'a', 'c', '19000000-0000-0000-0000-000000000001'), + ('19000000-0000-0000-0000-0000000000cc', 'catalog_reader', 'a', null, '19000000-0000-0000-0000-000000000001'); + +create function pg_temp.act(p uuid) returns void language sql as $$ + select set_config('request.jwt.claims', jsonb_build_object('sub', p, 'role', 'authenticated', 'aal', 'aal2', + 'session_id', ('19100000' || substr(p::text, 9))::uuid)::text, true); +$$; +create function pg_temp.doc(p_asset uuid) returns jsonb language sql as $$ + select jsonb_build_object('schema_version', 2, 'species_id', 'equine', 'name', jsonb_build_object('fr', 'I', 'en', 'I'), + 'description', jsonb_build_object('fr', 'd', 'en', 'd'), 'scope_disclaimer', jsonb_build_object('fr', 'x', 'en', 'x'), + 'attribution', jsonb_build_object('authors', '[]'::jsonb, 'license', null, 'notes', null), + 'vertebral_config', jsonb_build_object('regions', '[]'::jsonb), 'references', '[]'::jsonb, 'categories', '[]'::jsonb, + 'views', jsonb_build_array(jsonb_build_object('id', 'main', 'kind', 'main', 'name', jsonb_build_object('fr', 'V', 'en', 'V'), + 'svg_asset_id', p_asset, 'view_box', null)), + 'annotations', '[]'::jsonb, 'finding_zones', '[]'::jsonb); +$$; +grant execute on all functions in schema pg_temp to authenticated, service_role; + +-- SP: published v1 (drawing d1), draft v2; pending drawings d2 (no transition +-- yet), d3 (object present), d4 (no object). SX: a deleted sheet that had a +-- published version. +select set_config('request.jwt.claims', '{"sub":"19000000-0000-0000-0000-00000000000e"}', true); +insert into public.anatomical_sheets (id, species_id, name, slug, is_official, visibility, status) values + ('19200000-0000-0000-0000-000000000001', 'equine', 'SP', 'i19-sp', true, 'private', 'active'), + ('19200000-0000-0000-0000-000000000002', 'equine', 'SX', 'i19-sx', true, 'private', 'active'); +insert into public.anatomical_sheet_assets (id, sheet_id, sha256, byte_size, file_name, uploaded_at, created_by) values + ('19400000-0000-0000-0000-000000000001', '19200000-0000-0000-0000-000000000001', repeat('d1', 32), 100, 'd1.svg', now(), null), + ('19400000-0000-0000-0000-000000000002', '19200000-0000-0000-0000-000000000001', repeat('d2', 32), 100, 'd2.svg', null, null), + ('19400000-0000-0000-0000-000000000003', '19200000-0000-0000-0000-000000000001', repeat('d3', 32), 100, 'd3.svg', null, null), + ('19400000-0000-0000-0000-000000000004', '19200000-0000-0000-0000-000000000001', repeat('d4', 32), 100, 'd4.svg', null, null); +insert into storage.objects (bucket_id, name, metadata) +select 'anatomical-sheet-assets', repeat(c, 32) || '.svg', '{"size":100}' from unnest(array['d1', 'd3']) c on conflict do nothing; +insert into public.anatomical_sheet_versions (id, sheet_id, version_number, status, document_schema_version, content, + published_at, document_fingerprint) values + ('19300000-0000-0000-0000-000000000001', '19200000-0000-0000-0000-000000000001', 1, 'published', 2, + pg_temp.doc('19400000-0000-0000-0000-000000000001'), now(), repeat('0', 64)), + ('19300000-0000-0000-0000-000000000002', '19200000-0000-0000-0000-000000000001', 2, 'draft', 2, + pg_temp.doc('19400000-0000-0000-0000-000000000001'), null, null), + ('19300000-0000-0000-0000-000000000003', '19200000-0000-0000-0000-000000000002', 1, 'published', 2, + pg_temp.doc(null), now(), repeat('0', 64)); +update public.anatomical_sheets set current_version_id = '19300000-0000-0000-0000-000000000001', last_version_number = 2 + where id = '19200000-0000-0000-0000-000000000001'; +update public.anatomical_sheets set current_version_id = '19300000-0000-0000-0000-000000000003', last_version_number = 1, + status = 'deleted', deleted_at = now() where id = '19200000-0000-0000-0000-000000000002'; + +-- ============ A published version, for the table owner (§6.8) ============ +select throws_ok($$ update public.anatomical_sheet_versions set content = content || '{"name":{"fr":"X","en":"X"}}' + where id = '19300000-0000-0000-0000-000000000001' $$, '42501', null, 'the table owner cannot change published content'); +select throws_ok($$ update public.anatomical_sheet_versions set status = 'draft' + where id = '19300000-0000-0000-0000-000000000001' $$, '42501', null, 'a published version never goes back to draft'); +select throws_ok($$ update public.anatomical_sheet_versions set version_number = 9 + where id = '19300000-0000-0000-0000-000000000001' $$, '42501', null, 'version_number is immutable'); +select throws_ok($$ update public.anatomical_sheet_versions set document_fingerprint = repeat('1', 64) + where id = '19300000-0000-0000-0000-000000000001' $$, '42501', null, 'the published fingerprint is immutable'); +select throws_ok($$ update public.anatomical_sheet_versions set authors = '{}' + where id = '19300000-0000-0000-0000-000000000001' $$, '42501', null, 'the published author set is immutable'); +select throws_ok($$ update public.anatomical_sheet_versions set published_review_id = gen_random_uuid() + where id = '19300000-0000-0000-0000-000000000001' $$, '42501', null, 'the published review link is immutable'); +select throws_ok($$ delete from public.anatomical_sheet_versions where id = '19300000-0000-0000-0000-000000000001' $$, + '55000', null, 'the table owner cannot delete a published version'); +-- The deprecation transition changes no V1-2 column (§6.8). +select throws_ok($$ update public.anatomical_sheet_versions set status = 'deprecated', deprecated_at = now(), + document_fingerprint = repeat('1', 64) where id = '19300000-0000-0000-0000-000000000001' $$, + '42501', null, 'a deprecation that also changes the fingerprint is refused'); +select throws_ok($$ update public.anatomical_sheet_versions set status = 'deprecated', deprecated_at = now(), + source_version_id = '19300000-0000-0000-0000-000000000002' where id = '19300000-0000-0000-0000-000000000001' $$, + '42501', null, 'a deprecation that also changes the base is refused'); +select lives_ok($$ update public.anatomical_sheet_versions set status = 'deprecated', deprecated_at = now() + where id = '19300000-0000-0000-0000-000000000001' $$, 'the bare deprecation transition is allowed'); +-- ============ A deprecated version is frozen and kept (F13) ============ +select throws_ok($$ update public.anatomical_sheet_versions set change_note = 'late' + where id = '19300000-0000-0000-0000-000000000001' $$, '42501', null, 'a deprecated version is frozen for the table owner'); +select throws_ok($$ update public.anatomical_sheet_versions set status = 'published' + where id = '19300000-0000-0000-0000-000000000001' $$, '42501', null, 'a deprecated version is never published again'); +select throws_ok($$ delete from public.anatomical_sheet_versions where id = '19300000-0000-0000-0000-000000000001' $$, + '55000', null, 'the table owner cannot delete a deprecated version (F13)'); +-- ============ Drafts: one per sheet, species of the sheet, no direct deprecation ============ +select throws_ok($$ update public.anatomical_sheet_versions set status = 'deprecated', deprecated_at = now() + where id = '19300000-0000-0000-0000-000000000002' $$, '55000', null, 'a draft is never deprecated directly'); +select throws_ok($$ insert into public.anatomical_sheet_versions (sheet_id, version_number, document_schema_version, content) + values ('19200000-0000-0000-0000-000000000001', 7, 2, pg_temp.doc(null)) $$, '23505', null, 'one draft per sheet, for every role'); +select throws_ok($$ update public.anatomical_sheet_versions set content = jsonb_set(content, '{species_id}', '"canine"') + where id = '19300000-0000-0000-0000-000000000002' $$, '23514', null, 'a document of another species is refused for every role'); +-- No API role publishes by a direct UPDATE: neither has the privilege (F12). +set local role service_role; +select throws_ok($$ update public.anatomical_sheet_versions set status = 'published' + where id = '19300000-0000-0000-0000-000000000002' $$, '42501', null, 'service_role cannot update a version (F12)'); +set local role authenticated; +select pg_temp.act('19000000-0000-0000-0000-00000000000e'); +select throws_ok($$ update public.anatomical_sheet_versions set status = 'published' + where id = '19300000-0000-0000-0000-000000000002' $$, '42501', null, 'an editor cannot update a version directly (F9)'); +reset role; + +-- ============ Drawing rows (§9.1, F16) ============ +select throws_ok($$ insert into public.anatomical_sheet_assets (sheet_id, sha256, byte_size, file_name) + values ('19200000-0000-0000-0000-000000000001', repeat('d5', 32), 2097153, 'big.svg') $$, + '23514', null, 'a drawing row over 2 MiB is refused'); +select throws_ok($$ update public.anatomical_sheet_assets set byte_size = 99 + where id = '19400000-0000-0000-0000-000000000001' $$, '42501', null, 'a drawing row''s size is immutable (F16)'); +select throws_ok($$ update public.anatomical_sheet_assets set uploaded_at = now() - interval '1 day' + where id = '19400000-0000-0000-0000-000000000001' $$, '42501', null, 'a confirmation time never moves once set'); +select lives_ok($$ update public.anatomical_sheet_assets set uploaded_at = now() + where id = '19400000-0000-0000-0000-000000000002' $$, 'a pending row is confirmed once'); +set local role authenticated; +select pg_temp.act('19000000-0000-0000-0000-00000000000e'); +select throws_ok($$ select public.register_sheet_asset('19200000-0000-0000-0000-000000000001', repeat('d5', 32), 2097153, 'big.svg') $$, + 'P0001', 'invalid_input', 'register refuses a drawing over 2 MiB'); +reset role; + +-- ============ The historical sheet, for the table owner (§14.2) ============ +select throws_ok($$ update public.anatomical_sheets set status = 'archived', archived_at = now() + where id = '503dc301-a8b1-50d4-9e44-0919b2fc2916' $$, '42501', 'sheet.historical_read_only', 'the historical sheet is never archived'); +select throws_ok($$ update public.anatomical_sheets set name = 'x' + where id = '503dc301-a8b1-50d4-9e44-0919b2fc2916' $$, '42501', 'sheet.historical_read_only', 'the historical sheet row is never edited'); +select throws_ok($$ delete from public.anatomical_sheets where id = '503dc301-a8b1-50d4-9e44-0919b2fc2916' $$, + '42501', 'sheet.historical_read_only', 'the historical sheet is never deleted'); +select throws_ok($$ delete from public.anatomical_sheet_assets where sheet_id = '503dc301-a8b1-50d4-9e44-0919b2fc2916' $$, + '42501', 'sheet.historical_read_only', 'the historical drawing row is never deleted'); +select set_config('request.jwt.claims', '', true); +select lives_ok($$ update public.anatomical_sheet_versions set content = jsonb_set(content, '{description,fr}', '"seed"') + where sheet_id = '503dc301-a8b1-50d4-9e44-0919b2fc2916' $$, + 'a content write without an actor stays allowed on the historical sheet only (the converging seed)'); + +-- ============ Storage (§9.1, §9.3, §9.4) ============ +select is((select allowed_mime_types from storage.buckets where id = 'anatomical-sheet-assets'), array['image/svg+xml'], + 'the bucket accepts SVG only'); +-- Objects under names that resemble a confirmed key: only the exact +-- `.svg` is ever readable. +insert into storage.objects (bucket_id, name, metadata) +select 'anatomical-sheet-assets', n, '{"size":100}' +from unnest(array[upper(repeat('d1', 32)) || '.svg', repeat('d1', 32), 'x/' || repeat('d1', 32) || '.svg', + repeat('d1', 32) || '.svg.bak', repeat('d1', 32) || '.SVG']) n +on conflict do nothing; +set local role authenticated; +select pg_temp.act('19000000-0000-0000-0000-00000000000e'); +select is((select string_agg(name, ',') from storage.objects where bucket_id = 'anatomical-sheet-assets' and name ilike '%' || repeat('d1', 32) || '%'), + repeat('d1', 32) || '.svg', 'an editor reads the exact key only, no variant'); +select pg_temp.act('19000000-0000-0000-0000-0000000000cc'); +select is((select string_agg(name, ',') from storage.objects where bucket_id = 'anatomical-sheet-assets' and name ilike '%' || repeat('d1', 32) || '%'), + repeat('d1', 32) || '.svg', 'a reader reads the exact key of a catalogue drawing only, no variant'); +-- A deleted sheet is read by nobody, its published version included. +select is((select count(*) from public.anatomical_sheets where id = '19200000-0000-0000-0000-000000000002'), 0::bigint, + 'a reader does not see a deleted sheet'); +select throws_ok($$ select public.get_sheet_version('19300000-0000-0000-0000-000000000003') $$, + '42501', 'not_found', 'nor a published version of a deleted sheet by id'); +select pg_temp.act('19000000-0000-0000-0000-00000000000e'); +select is((select count(*) from public.anatomical_sheet_versions where sheet_id = '19200000-0000-0000-0000-000000000002'), 0::bigint, + 'an editor does not see the versions of a deleted sheet'); +-- The operator tool confirms an upload with the service key (§9.3 step 3, §9.5). +reset role; +set local role service_role; +select set_config('request.jwt.claims', '{"role":"service_role"}', true); +select is(public.confirm_sheet_asset_upload('19400000-0000-0000-0000-000000000003'), '19400000-0000-0000-0000-000000000003'::uuid, + 'the service role confirms an upload whose object exists with the recorded size'); +select throws_ok($$ select public.confirm_sheet_asset_upload('19400000-0000-0000-0000-000000000004') $$, + 'P0001', 'upload_missing', 'the service role cannot confirm a row without its object (F7)'); +select throws_ok($$ select public.register_sheet_asset('19200000-0000-0000-0000-000000000001', repeat('d6', 32), 100, 'x.svg') $$, + '42501', null, 'the service role cannot register a drawing'); +reset role; +select is((select actor_user_id is null from audit.audit_logs where action = 'anatomical_sheet_asset.uploaded' + and resource_id = '19400000-0000-0000-0000-000000000003'), true, + 'the operator confirmation is audited with a null actor'); + +select * from finish(); +rollback;