From 3914eaa866e499668dd80d46ebba3d914159095f Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 28 Oct 2026 16:20:51 +0100 Subject: [PATCH] fix(supabase): V1-2.1 harden M5 after the security and verifier gates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fresh security audit PASS; verifier ECARTS(10) addressed: - publish re-checks the approver's sheet_reviewer grant (publish.approval.invalid) - scope disclaimer enforced at approve and publish (publish.disclaimer.missing, O6) - to_confirm split from inherited (publish.to_confirm.open distinct from publish.inherited.present) - save_sheet_draft requires an active sheet; working copy adds the 2 MiB octet_length check - delete_sheet_asset EXECUTE revoked from service_role (§5.4 surface) - species table comment updated (§7.2); lease columns dropped from the reviews grant - lock order sheet->version->round in decide/publish; conflict_retry kind (40001/40P01) in sheets.ts Tests: pgTAP 016 (omitted status, separation, revoked-reviewer + renewal, ack carry, inactive-species publish refusal, deprecated-delete, schema_version 1, content-write without actor, working-copy positive), 001 census (no other writer of profile_roles). 871 real-stack pgTAP / 122 PGlite / 4 sandbox green; typecheck, lint, types drift clean. --- .claude/memory/journal.md | 1 + packages/supabase/src/sheets.ts | 6 + .../20261028110000_sheet_review_workflow.sql | 109 ++++++++++-- supabase/tests/001_schema.sql | 15 +- supabase/tests/016_sheet_review_workflow.sql | 163 +++++++++++++++++- 5 files changed, 280 insertions(+), 14 deletions(-) diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index ffa5ac99..c7c4a6b8 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -475,3 +475,4 @@ R5.4: `draft/{labels,changelog,review_report,drawing,overlay,app_review,svg_comp ## 2026-10-28 - V1-2.1 M4/M5 built+tested on sandbox (DEV untouched): M4 20261028100000 sheet_access_hardening (rights table + RPCs, has_mfa/has_aal2_session, catalogue reader predicate, can_edit_sheet on capability, AR-1 B role RPCs + F17/F18/F19, F1-F16), M5 20261028110000 sheet_review_workflow (version/sheet cols, freeze/revision/author triggers, rounds/comments/acks, lifecycle+review+publish RPCs, species, working copy, uploads+INSERT policy, mirror removed + status check). Defects F1-F19 reproduced on old schema; pgTAP 001/003/004/005/006/007/010/015/016 green (850 real-stack, 122 PGlite); sandbox real-GoTrue AR-1 B + F18 race green; fresh install + M3->M5 upgrade green; sheets.ts closed kinds, client gate deleted, types regen no drift; rust:check + typecheck + lint + build green. 011 + SQL-mirror generator deleted, ledger retargeted. BDR + LRN-095. check:all Docker image/worker stages not re-run (no app/worker/Dockerfile change). STOP at checkpoint. +- V1-2.1 fresh security+verifier gates run on commit 77e5fa4: security PASS (no blocker; lease-token whole-row grant narrowed to omit attempts/lease_token/locked_at). Verifier ECARTS(10) → fixed the real gaps: publish re-checks the approver's reviewer grant (publish.approval.invalid), scope disclaimer enforced at approve+publish (publish.disclaimer.missing, O6), to_confirm split from inherited (publish.to_confirm.open), save requires an active sheet, delete_sheet_asset revoked from service_role, species table comment updated, working-copy 2 MiB check, lock order sheet→version→round in decide/publish, conflict_retry kind (40001/40P01) in sheets.ts. Tests added (pgTAP 016 now 50, 001 census no-other-writer): omitted review_status, separation author-reviewer, revoked-reviewer approval + renewal, ack carry, inactive-species publish refusal, deprecated-delete, schema_version 1 refused, content-write-without-actor, working-copy positive. 871 real-stack pgTAP / 122 PGlite / 4 sandbox green; typecheck+lint+types drift clean. Deferred (noted): at-caps timing (V1-2.2 doc), fuller MFA factor mgmt (V1-2.5), low residuals (existence oracle, write-budget on some admin RPCs). diff --git a/packages/supabase/src/sheets.ts b/packages/supabase/src/sheets.ts index 81506141..e62b5cb1 100644 --- a/packages/supabase/src/sheets.ts +++ b/packages/supabase/src/sheets.ts @@ -75,7 +75,10 @@ export const SHEET_FAILURE_KINDS = [ 'verdict.stale', 'verdict.fingerprint', 'publish.review.missing', + 'publish.approval.invalid', + 'publish.to_confirm.open', 'publish.inherited.present', + 'publish.disclaimer.missing', 'publish.species.inactive', 'publish.species.other', 'publish.drawing.missing', @@ -89,6 +92,7 @@ export const SHEET_FAILURE_KINDS = [ // shared 'invalid_input', 'rate_limited', + 'conflict_retry', 'session_expired', 'network', 'unavailable', @@ -122,6 +126,8 @@ export function classifySheetError(error: unknown, status?: number): SheetFailur if (error instanceof TypeError) return 'network' const e = (error ?? {}) as PostgrestLikeError if (e.message && KIND_SET.has(e.message)) return e.message as SheetFailureKind + // Deadlock (40P01) and serialization (40001) are retryable (contract §6.1). + if (e.code === '40P01' || e.code === '40001') return 'conflict_retry' if (status === 401 || e.code?.startsWith('PGRST30')) return 'session_expired' if (status === 0) return 'network' return 'unavailable' diff --git a/supabase/migrations/20261028110000_sheet_review_workflow.sql b/supabase/migrations/20261028110000_sheet_review_workflow.sql index 867532db..e8443b0f 100644 --- a/supabase/migrations/20261028110000_sheet_review_workflow.sql +++ b/supabase/migrations/20261028110000_sheet_review_workflow.sql @@ -168,6 +168,43 @@ $$; comment on function private.sheet_all_reviewed(jsonb) is 'Declared defensive status check (contract §12.2): true when every annotation, finding category and finding node is reviewed (an absent review_status counts as inherited, so it is refused).'; +-- True when any element is explicitly `to_confirm` (contract §6.7 keeps +-- `publish.to_confirm.open` apart from `publish.inherited.present`, which +-- covers an inherited or omitted status). +create or replace function private.sheet_has_to_confirm(p_doc jsonb) +returns boolean +language sql +immutable +set search_path = '' +as $$ + select exists ( + select 1 from jsonb_array_elements(coalesce(p_doc -> 'annotations', '[]'::jsonb)) a + where a ->> 'review_status' = 'to_confirm' + ) or exists ( + select 1 + from jsonb_array_elements(coalesce(p_doc -> 'finding_zones', '[]'::jsonb)) z, + jsonb_array_elements(coalesce(z -> 'categories', '[]'::jsonb)) c + where c ->> 'review_status' = 'to_confirm' + ) or exists ( + select 1 + from jsonb_array_elements(coalesce(p_doc -> 'finding_zones', '[]'::jsonb)) z, + jsonb_array_elements(coalesce(z -> 'categories', '[]'::jsonb)) c, + jsonb_path_query(c, '$.children[*].**{0 to 64}') n + where jsonb_typeof(n) = 'object' and n ? 'id' and n ->> 'review_status' = 'to_confirm' + ); +$$; + +-- True when the scope disclaimer is present and non-blank in FR and EN (O6). +create or replace function private.sheet_disclaimer_ok(p_doc jsonb) +returns boolean +language sql +immutable +set search_path = '' +as $$ + select length(btrim(coalesce(p_doc -> 'scope_disclaimer' ->> 'fr', ''))) > 0 + and length(btrim(coalesce(p_doc -> 'scope_disclaimer' ->> 'en', ''))) > 0; +$$; + -- =========================================================================== -- 3. Triggers: revision, author set, freeze, extended publication guard -- =========================================================================== @@ -426,6 +463,10 @@ begin if v_row.status <> 'draft' then raise exception 'draft.not_a_draft' using errcode = '55000'; end if; + -- A draft of an active official sheet only (§6.2): an archived sheet is frozen. + if not exists (select 1 from public.anatomical_sheets s where s.id = v_row.sheet_id and s.status = 'active') then + raise exception 'sheet.inactive' using errcode = '55000'; + end if; if exists (select 1 from public.anatomical_sheet_reviews r where r.version_id = v_row.id and r.status in ('verifying', 'open', 'approved')) then raise exception 'draft.frozen' using errcode = '55000'; @@ -755,17 +796,20 @@ begin if char_length(note) not between 1 and 4000 then raise exception 'invalid_input' using errcode = 'P0001'; end if; - select r.* into v_review from public.anatomical_sheet_reviews r where r.id = decide_sheet_review.review_id for update; - if v_review.id is null then + -- 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; + if v_version.id is null then raise exception 'not_found' using errcode = '42501'; end if; + 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 raise exception 'round.not_open' using errcode = '55000'; end if; if v_review.authors @> array[v_actor] then raise exception 'review.separation' using errcode = '42501'; end if; - select v.* into v_version from public.anatomical_sheet_versions v where v.id = v_review.version_id for update; perform private.consume_catalog_write_budget(v_actor); if approve then @@ -774,9 +818,15 @@ begin if v_review.verdict is null or 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 + raise exception 'publish.to_confirm.open' using errcode = 'P0001'; + end if; if not private.sheet_all_reviewed(v_version.content) then raise exception 'publish.inherited.present' using errcode = 'P0001'; end if; + if not private.sheet_disclaimer_ok(v_version.content) then + raise exception 'publish.disclaimer.missing' using errcode = 'P0001'; + end if; v_uncovered := private.uncovered_review_groups(v_review.id); if coalesce(array_length(v_uncovered, 1), 0) > 0 then raise exception 'review.groups.uncovered' using errcode = 'P0001'; @@ -821,15 +871,18 @@ declare v_name text; v_description text; begin - select r.* into v_review from public.anatomical_sheet_reviews r where r.id = publish_sheet_version.review_id for update; - if v_review.id is null then + -- 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 + join public.anatomical_sheet_reviews r on r.version_id = v.id + where r.id = publish_sheet_version.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 - join public.anatomical_sheet_versions v on v.sheet_id = s.id - where v.id = v_review.version_id for update; + select s.* into v_sheet from public.anatomical_sheets s where s.id = v_sheet.id for update; v_actor := private.require_sheet_publisher(v_sheet.id); - select v.* into v_version from public.anatomical_sheet_versions v where v.id = v_review.version_id for update; + 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 = publish_sheet_version.review_id for update; if v_sheet.status <> 'active' then raise exception 'sheet.inactive' using errcode = '55000'; @@ -846,6 +899,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 + raise exception 'publish.approval.invalid' using errcode = 'P0001'; + end if; -- Species active and not `other` (§6.7). if not exists (select 1 from public.species s where s.id = v_sheet.species_id and s.active) then raise exception 'publish.species.inactive' using errcode = 'P0001'; @@ -853,10 +911,16 @@ begin if v_sheet.species_id = 'other' then raise exception 'publish.species.other' using errcode = 'P0001'; end if; - -- Status check kept in SQL (§12.2): no to_confirm / inherited element. + -- Status check kept in SQL (§12.2): no to_confirm, no inherited (or omitted). + if private.sheet_has_to_confirm(v_version.content) then + raise exception 'publish.to_confirm.open' using errcode = 'P0001'; + end if; if not private.sheet_all_reviewed(v_version.content) then raise exception 'publish.inherited.present' using errcode = 'P0001'; end if; + if not private.sheet_disclaimer_ok(v_version.content) then + raise exception 'publish.disclaimer.missing' using errcode = 'P0001'; + end if; -- Groups still covered at publication. if coalesce(array_length(private.uncovered_review_groups(v_review.id), 1), 0) > 0 then raise exception 'review.groups.uncovered' using errcode = 'P0001'; @@ -1141,6 +1205,10 @@ begin v_map := v_map || jsonb_build_object(r.id::text, v_new::text); 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; 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 || ')' @@ -1531,7 +1599,14 @@ create trigger anatomical_sheet_versions_guard_update revoke all on public.anatomical_sheet_reviews from public, anon, authenticated, service_role; revoke all on public.anatomical_sheet_review_comments from public, anon, authenticated, service_role; revoke all on public.anatomical_sheet_review_acknowledgments from public, anon, authenticated, service_role; -grant select on public.anatomical_sheet_reviews to authenticated; +-- The lease columns (attempts, lease_token, locked_at) are the worker's, read +-- only by the M6 service-role RPCs; the admin screens never see them, as the +-- avatar lease pattern hides its own (20261013100000_files_foundation.sql). +grant select (id, version_id, round, revision, authors, submitted_by, submitted_at, + submission_note, status, verdict, verified_at, verified_with, + failure_outcome, failure_code, decided_by, decided_at, decision_note, + withdrawn_by, withdrawn_at, withdrawal_note, created_at) + on public.anatomical_sheet_reviews to authenticated; grant select on public.anatomical_sheet_review_comments to authenticated; grant select on public.anatomical_sheet_review_acknowledgments to authenticated; -- The editor needs the draft revision for the save-conflict check (§6.2); the @@ -1609,6 +1684,8 @@ $$; -- Private helpers: EXECUTE for nobody except the predicates the review -- policies evaluate (caller_can_see_official_sheet, granted in M4). revoke all on function private.sheet_all_reviewed(jsonb) from public, anon, authenticated, service_role; +revoke all on function private.sheet_has_to_confirm(jsonb) from public, anon, authenticated, service_role; +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_sheet_author(uuid) from public, anon, authenticated, service_role; @@ -1622,3 +1699,13 @@ revoke all on function private.set_sheet_status(uuid, uuid, public.sheet_status, -- longer called). Drop them so no stale path survives. drop function if exists private.require_sheet_editor(uuid, uuid); drop function if exists private.require_version_editor(uuid, uuid); + +-- delete_sheet_asset survives from the base migration (editor, aal2, via +-- can_edit_sheet); the service role never needs it (§5.4 limits its surface to +-- the worker RPCs, the upload confirmation and the operator read). +revoke all on function public.delete_sheet_asset(uuid) from service_role; + +-- §7.2: the species table is no longer write-only through migrations; editors +-- create inactive species and the owner activates them, by audited RPC. +comment on table public.species is + 'Species of animals and of anatomical sheets. Written only by the audited RPCs create_species (editor, inactive), activate_species / rename_species (owner), update_inactive_species (editor); no direct API write path.'; diff --git a/supabase/tests/001_schema.sql b/supabase/tests/001_schema.sql index 002dd9b8..96a45af6 100644 --- a/supabase/tests/001_schema.sql +++ b/supabase/tests/001_schema.sql @@ -1,6 +1,6 @@ -- Schema contract: objects exist, RLS is on, API roles start from zero. begin; -select plan(26); +select plan(27); -- Schemas select has_schema('private', 'schema private exists'); @@ -66,5 +66,18 @@ select is( 'authenticated executes only the policy predicates in private' ); +-- No write path to profile_roles other than the two private writers (§16.2, +-- §5.7 inventory). prosrc of every function is scanned for an insert/update/ +-- delete on public.profile_roles; reads (has_platform_role, the owner count) +-- are excluded. +select is( + (select string_agg(p.proname::text, ',' order by p.proname::text collate "C") + from pg_proc p join pg_namespace n on n.oid = p.pronamespace + where n.nspname in ('public', 'private') + and p.prosrc ~ '(insert into|update|delete from)\s+public\.profile_roles'), + 'assign_platform_role,withdraw_platform_role', + 'only assign_platform_role / withdraw_platform_role write profile_roles' +); + select * from finish(); rollback; diff --git a/supabase/tests/016_sheet_review_workflow.sql b/supabase/tests/016_sheet_review_workflow.sql index 06122d6d..d4bbabd1 100644 --- a/supabase/tests/016_sheet_review_workflow.sql +++ b/supabase/tests/016_sheet_review_workflow.sql @@ -4,7 +4,7 @@ -- worker of M6, as the contract allows until V1-2.3. Real GoTrue MFA and the -- concurrency cases run in tests/sandbox. begin; -select plan(30); +select plan(50); -- Accounts: owner, editor+publisher, reviewer, and a reviewer who also edits -- (so becomes a round author -> separation of duties). @@ -105,7 +105,7 @@ set local role authenticated; -- Approval is refused while an element is to_confirm (D2: counts as not reviewed). select pg_temp.act('e0000000-0000-0000-0000-0000000000f1','e1000000-0000-0000-0000-0000000000f1'); select throws_ok($$ select public.decide_sheet_review((select id from pg_temp.k where key='r1'), true, 'ok') $$, - 'P0001', 'publish.inherited.present', 'approval refused while an element is to_confirm'); + 'P0001', 'publish.to_confirm.open', 'approval refused while an element is to_confirm (distinct code)'); -- Reviewer requests changes; editor marks reviewed and resubmits. select public.decide_sheet_review((select id from pg_temp.k where key='r1'), false, 'please mark reviewed'); @@ -205,5 +205,164 @@ select throws_ok($$ update public.anatomical_sheet_versions set status='publishe where id=(select id from pg_temp.k where key='v2') $$, '42501', 'publish.review.missing', 'no direct UPDATE publishes a draft, even for the table owner'); +-- ============ Declared status check: omitted status + disclaimer (§12.2, O6) ============ +-- Checked directly on the predicates (as the table owner): an omitted +-- review_status counts as inherited (§12.2 mandates an omitted-status case). +select ok(not private.sheet_all_reviewed(pg_temp.doc(null,'reviewed') #- '{annotations,0,review_status}'), + 'an omitted review_status counts as not reviewed (§12.2)'); +select ok(not private.sheet_has_to_confirm(pg_temp.doc(null,'reviewed') #- '{annotations,0,review_status}'), + 'an omitted status is inherited, never to_confirm'); +select ok(private.sheet_all_reviewed(pg_temp.doc(null,'reviewed')), 'a fully reviewed document passes the status check'); +select ok(private.sheet_has_to_confirm(pg_temp.doc(null,'to_confirm')), 'a to_confirm element is detected'); +select ok(not private.sheet_disclaimer_ok(jsonb_set(pg_temp.doc(null,'reviewed'), '{scope_disclaimer}', '{"fr":" ","en":"x"}')), + 'a blank FR scope disclaimer fails O6'); +select ok(private.sheet_disclaimer_ok(pg_temp.doc(null,'reviewed')), 'a present FR and EN disclaimer passes O6'); + +-- A content write with no authenticated actor is refused on a non-historical +-- sheet (§5.5). The claim is cleared so auth.uid() is null; the content trigger +-- raises before the one-draft unique index is reached. +select set_config('request.jwt.claims', '', true); +select throws_ok($$ insert into public.anatomical_sheet_versions (sheet_id, version_number, document_schema_version, content) + values ((select id from pg_temp.k where key='sheet'), 99, 2, pg_temp.doc(null,'reviewed')) $$, + '42501', null, 'a content write with no actor is refused on a non-historical sheet (§5.5)'); + +-- ============ schema_version: only 2 is stored (former 008 cases) ============ +set local role authenticated; +select pg_temp.act('e0000000-0000-0000-0000-00000000000e','e1000000-0000-0000-0000-00000000000e'); +select throws_ok($$ select public.create_official_sheet('sv1', jsonb_set(pg_temp.doc(null,'reviewed'),'{schema_version}','1')) $$, + '23514', null, 'a schema_version 1 document is refused at creation'); + +-- ============ Separation of duties + revoked-reviewer approval (§5.5, §6.7) ============ +insert into pg_temp.k select 'sheet3', public.create_official_sheet('wf-sep', pg_temp.doc(null,'reviewed')); +insert into pg_temp.k select 'v3', id from public.anatomical_sheet_versions where sheet_id=(select id from pg_temp.k where key='sheet3'); +insert into pg_temp.k select 'asset3', public.register_sheet_asset((select id from pg_temp.k where key='sheet3'), repeat('8',64), 500, 's.svg'); +reset role; +insert into storage.objects (bucket_id,name,metadata) values ('anatomical-sheet-assets', repeat('8',64)||'.svg','{"size":500}'); +set local role authenticated; select pg_temp.act('e0000000-0000-0000-0000-00000000000e','e1000000-0000-0000-0000-00000000000e'); +select public.confirm_sheet_asset_upload((select id from pg_temp.k where key='asset3')); +select public.save_sheet_draft((select id from pg_temp.k where key='v3'), 0, pg_temp.doc((select id from pg_temp.k where key='asset3'),'reviewed'), 'wire'); +-- rev2 (reviewer + editor) edits the draft and so becomes an author of the round. +select pg_temp.act('e0000000-0000-0000-0000-0000000000f2','e1000000-0000-0000-0000-0000000000f2'); +select public.save_sheet_draft((select id from pg_temp.k where key='v3'), 1, + jsonb_set(pg_temp.doc((select id from pg_temp.k where key='asset3'),'reviewed'),'{description,fr}','"rev2 edit"'), 'rev2'); +select pg_temp.act('e0000000-0000-0000-0000-00000000000e','e1000000-0000-0000-0000-00000000000e'); +insert into pg_temp.k select 'r3', public.submit_sheet_review((select id from pg_temp.k where key='v3'), 2, 'sep round'); +reset role; select pg_temp.open_round((select id from pg_temp.k where key='r3'), (select id from pg_temp.k where key='asset3'), repeat('8',64)); +set local role authenticated; +-- rev2 is an author of r3: it may neither acknowledge nor approve (review.separation, not rights.capability). +select pg_temp.act('e0000000-0000-0000-0000-0000000000f2','e1000000-0000-0000-0000-0000000000f2'); +select throws_ok($$ select public.acknowledge_sheet_review_group((select id from pg_temp.k where key='r3'),'general',repeat('1',64)) $$, + '42501','review.separation','an author who holds the reviewer capability cannot acknowledge its own round'); +select throws_ok($$ select public.decide_sheet_review((select id from pg_temp.k where key='r3'), true, 'self') $$, + '42501','review.separation','an author who holds the reviewer capability cannot approve its own round'); +-- rev1 (not an author) comments, acknowledges and approves. +select pg_temp.act('e0000000-0000-0000-0000-0000000000f1','e1000000-0000-0000-0000-0000000000f1'); +select is(public.comment_sheet_review((select id from pg_temp.k where key='r3'),'general group looks fine','general') is not null, true, + 'a reviewer comments on the round'); +select public.acknowledge_sheet_review_group((select id from pg_temp.k where key='r3'),'general',repeat('1',64)); +select public.acknowledge_sheet_review_group((select id from pg_temp.k where key='r3'),'view:main',repeat('2',64)); +select public.acknowledge_sheet_review_group((select id from pg_temp.k where key='r3'),'zone:z1',repeat('3',64)); +select public.decide_sheet_review((select id from pg_temp.k where key='r3'), true, 'approved by rev1'); +-- Revoke rev1's reviewer grant: the approval no longer carries a publication. +reset role; +update public.anatomical_catalog_grants set revoked_at=now(), revoked_by='e0000000-0000-0000-0000-000000000001', revocation_reason='rotation' + where user_id='e0000000-0000-0000-0000-0000000000f1' and grant_kind='sheet_reviewer' and revoked_at is null; +set local role authenticated; select pg_temp.act('e0000000-0000-0000-0000-00000000000e','e1000000-0000-0000-0000-00000000000e'); +select throws_ok($$ select public.publish_sheet_version((select id from pg_temp.k where key='r3')) $$, + 'P0001','publish.approval.invalid','a revoked reviewer''s approval does not carry a publication'); +-- Renew the grant: the approval counts again and publication succeeds. +reset role; +insert into public.anatomical_catalog_grants (user_id,grant_kind,reason,verification_note,granted_by) + values ('e0000000-0000-0000-0000-0000000000f1','sheet_reviewer','renewed','checked','e0000000-0000-0000-0000-000000000001'); +set local role authenticated; select pg_temp.act('e0000000-0000-0000-0000-00000000000e','e1000000-0000-0000-0000-00000000000e'); +select is(public.publish_sheet_version((select id from pg_temp.k where key='r3')), (select id from pg_temp.k where key='v3'), + 'after the reviewer grant is renewed the approval counts again and publication succeeds'); + +-- ============ Acknowledgment carry across rounds (§6.3) ============ +-- A new draft of sheet3 from the published v3; change only the general group; the +-- view and zone acknowledgments carry because their digests are unchanged. +insert into pg_temp.k select 'v3b', public.create_sheet_draft((select id from pg_temp.k where key='sheet3'), (select id from pg_temp.k where key='v3'), 'edition 2'); +select public.save_sheet_draft((select id from pg_temp.k where key='v3b'), 0, + jsonb_set(pg_temp.doc((select id from pg_temp.k where key='asset3'),'reviewed'),'{description,en}','"v3b"'), 'general only'); +insert into pg_temp.k select 'r3b', public.submit_sheet_review((select id from pg_temp.k where key='v3b'), 1, 'round b'); +reset role; +-- Same view:main and zone:z1 digests as r3 (2,3); a new general digest (changed group). +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',(select id from pg_temp.k where key='asset3'),'sha256',repeat('8',64))), + 'groups', jsonb_build_array( + jsonb_build_object('key','general','digest',repeat('5',64),'coverable',true), + jsonb_build_object('key','view:main','digest',repeat('2',64),'coverable',true), + jsonb_build_object('key','zone:z1','digest',repeat('3',64),'coverable',true))) + where id=(select id from pg_temp.k where key='r3b'); +set local role authenticated; +select pg_temp.act('e0000000-0000-0000-0000-0000000000f1','e1000000-0000-0000-0000-0000000000f1'); +-- Only the changed general group is uncovered; view:main and zone:z1 carry from r3. +select public.acknowledge_sheet_review_group((select id from pg_temp.k where key='r3b'),'general',repeat('5',64)); +select is(public.decide_sheet_review((select id from pg_temp.k where key='r3b'), true, 'approved; two groups carried') is not null, true, + 'the unchanged groups carry their acknowledgments from the previous round (§6.3)'); + +-- ============ Inactive species refused at publication (§6.7) ============ +-- Build an official sheet for the inactive 'tapir' created earlier... it was +-- activated above, so create a fresh inactive species and a sheet on it. +select pg_temp.act('e0000000-0000-0000-0000-00000000000e','e1000000-0000-0000-0000-00000000000e'); +select public.create_species('okapi','Okapi','Okapi',70); +insert into pg_temp.k select 'sheet4', public.create_official_sheet('wf-okapi', + jsonb_set(pg_temp.doc((select id from pg_temp.k where key='asset3'),'reviewed'),'{species_id}','"okapi"')); +insert into pg_temp.k select 'v4', id from public.anatomical_sheet_versions where sheet_id=(select id from pg_temp.k where key='sheet4'); +-- register the shared drawing for sheet4 and confirm it +insert into pg_temp.k select 'asset4', public.register_sheet_asset((select id from pg_temp.k where key='sheet4'), repeat('8',64), 500, 's.svg'); +reset role; set local role authenticated; select pg_temp.act('e0000000-0000-0000-0000-00000000000e','e1000000-0000-0000-0000-00000000000e'); +select public.confirm_sheet_asset_upload((select id from pg_temp.k where key='asset4')); +select public.save_sheet_draft((select id from pg_temp.k where key='v4'), 0, + jsonb_set(pg_temp.doc((select id from pg_temp.k where key='asset4'),'reviewed'),'{species_id}','"okapi"'), 'wire'); +insert into pg_temp.k select 'r4', public.submit_sheet_review((select id from pg_temp.k where key='v4'), 1, 'okapi round'); +reset role; select pg_temp.open_round((select id from pg_temp.k where key='r4'), (select id from pg_temp.k where key='asset4'), repeat('8',64)); +set local role authenticated; +select pg_temp.act('e0000000-0000-0000-0000-0000000000f1','e1000000-0000-0000-0000-0000000000f1'); +select public.acknowledge_sheet_review_group((select id from pg_temp.k where key='r4'),'general',repeat('1',64)); +select public.acknowledge_sheet_review_group((select id from pg_temp.k where key='r4'),'view:main',repeat('2',64)); +select public.acknowledge_sheet_review_group((select id from pg_temp.k where key='r4'),'zone:z1',repeat('3',64)); +select public.decide_sheet_review((select id from pg_temp.k where key='r4'), true, 'approved'); +select pg_temp.act('e0000000-0000-0000-0000-00000000000e','e1000000-0000-0000-0000-00000000000e'); +select throws_ok($$ select public.publish_sheet_version((select id from pg_temp.k where key='r4')) $$, + 'P0001','publish.species.inactive','publication is refused while the species is inactive (§6.7)'); + +-- ============ Deprecated version deletion refused (F13) ============ +-- v3 is published; deprecate it, then a physical delete is refused for every role. +select public.deprecate_sheet_version((select id from pg_temp.k where key='v3'), 'superseded'); +select throws_ok($$ select public.delete_sheet_version((select id from pg_temp.k where key='v3')) $$, + '55000', null, 'a deprecated (once published) version cannot be deleted (F13)'); + +-- ============ Working copy of the historical sheet, positive path (§14.3) ============ +-- Confirm the seeded historical drawing object, then create the working copy. +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; +set local role authenticated; select pg_temp.act('e0000000-0000-0000-0000-00000000000e','e1000000-0000-0000-0000-00000000000e'); +insert into pg_temp.k select 'wc', public.create_sheet_working_copy( + (select id from public.anatomical_sheet_versions where sheet_id='503dc301-a8b1-50d4-9e44-0919b2fc2916'), 'cheval-travail'); +reset role; +select results_eq( + $$ select is_official, working_copy_source_version_id is not null, status::text + from public.anatomical_sheets where id = (select id from pg_temp.k where key='wc') $$, + $$ values (true, true, 'active') $$, + 'the working copy is an official active sheet with its provenance set'); +select is( + (select coalesce(array_length(authors,1),0) from public.anatomical_sheet_versions where sheet_id = (select id from pg_temp.k where key='wc')), + 1, 'the working-copy draft has one author (the caller), no base'); +select is( + (select source_version_id from public.anatomical_sheet_versions where sheet_id = (select id from pg_temp.k where key='wc')), + null, 'the working-copy draft has no base'); +-- a second active working copy of the historical sheet is refused +set local role authenticated; select pg_temp.act('e0000000-0000-0000-0000-00000000000e','e1000000-0000-0000-0000-00000000000e'); +select throws_ok($$ select public.create_sheet_working_copy( + (select id from public.anatomical_sheet_versions where sheet_id='503dc301-a8b1-50d4-9e44-0919b2fc2916'), 'cheval-2') $$, + 'P0001','working_copy.exists','only one active working copy of the historical sheet at a time'); + select * from finish(); rollback;