diff --git a/packages/supabase/src/database.types.ts b/packages/supabase/src/database.types.ts index 4cd5a54c..a1aca73c 100644 --- a/packages/supabase/src/database.types.ts +++ b/packages/supabase/src/database.types.ts @@ -1083,6 +1083,17 @@ export type Database = { object_name: string }[] } + claim_sheet_verifications: { + Args: { max_jobs: number } + Returns: { + attempts: number + lease_token: string + review_id: string + revision: number + sheet_id: string + version_id: string + }[] + } client_archive_preview: { Args: { client_id: string }; Returns: Json } comment_sheet_review: { Args: { body: string; group_key?: string; review_id: string } @@ -1097,6 +1108,10 @@ export type Database = { } Returns: undefined } + complete_sheet_verification: { + Args: { lease_token: string; review_id: string; verdict: Json } + Returns: string + } confirm_asset_upload: { Args: { asset_id: string }; Returns: undefined } confirm_sheet_asset_upload: { Args: { asset_id: string } @@ -1193,7 +1208,15 @@ export type Database = { Args: { max_age_seconds: number } Returns: number } + fail_sheet_verification: { + Args: { code: string; lease_token: string; review_id: string } + Returns: string + } get_sheet_asset_state: { Args: { asset_id: string }; Returns: Json } + get_sheet_verification_input: { + Args: { lease_token: string; review_id: string } + Returns: Json + } get_sheet_version: { Args: { version_id: string }; Returns: Json } grant_catalog_right: { Args: { diff --git a/packages/supabase/tests/db/schema-types.test.ts b/packages/supabase/tests/db/schema-types.test.ts index 638a402e..9732444e 100644 --- a/packages/supabase/tests/db/schema-types.test.ts +++ b/packages/supabase/tests/db/schema-types.test.ts @@ -271,6 +271,10 @@ const expectedFunctionArgs = { submit_sheet_review: ['expected_revision', 'note', 'version_id'], update_inactive_species: ['id', 'name_en', 'name_fr', 'sort_order'], withdraw_sheet_review: ['note', 'review_id'], + claim_sheet_verifications: ['max_jobs'], + complete_sheet_verification: ['lease_token', 'review_id', 'verdict'], + fail_sheet_verification: ['code', 'lease_token', 'review_id'], + get_sheet_verification_input: ['lease_token', 'review_id'], create_animal: [ 'birth_date', 'birth_year', diff --git a/supabase/migrations/20261101100000_sheet_verification_jobs.sql b/supabase/migrations/20261101100000_sheet_verification_jobs.sql new file mode 100644 index 00000000..6b28f746 --- /dev/null +++ b/supabase/migrations/20261101100000_sheet_verification_jobs.sql @@ -0,0 +1,405 @@ +-- V1-2.3 M6 `sheet_verification_jobs`: the worker RPCs of the server verdict. +-- docs/development/V1-2_ANATOMICAL_SHEETS.md §6.4 (job, RPCs, processing), +-- §6.5 (failures), §12.3 (M6). Service role only: no page reaches them. +-- +-- The round row (M5 `anatomical_sheet_reviews`) is the job, with the avatar +-- lease pattern of 20261013100000_files_foundation.sql (lease token, +-- `locked_at`, a fixed lease, attempts below a limit), without backoff: +-- * claim_sheet_verifications: rounds `verifying` with no live lease; +-- * get_sheet_verification_input: the frozen document, the base, the rows of +-- the drawings the document references; +-- * complete_sheet_verification: the verdict, checked for its binding and +-- its structure; `stale` or `malformed` write nothing; +-- * fail_sheet_verification: a technical failure, from a closed list. +-- The verdict itself is the core's (`compute_verdict`, crates/core); SQL +-- checks only that it answers this round and covers this document. + +-- =========================================================================== +-- 1. Constants +-- =========================================================================== +-- Attempts before a round closes `verification_failed` / `unavailable` +-- (§6.5 « five, proposal, tuned in V1-2.3 »). +create or replace function private.sheet_verification_attempt_limit() +returns integer language sql immutable set search_path = '' as $$ select 5 $$; + +-- A lease older than this is dead: the worker crashed or lost the database. +-- The child's wall-clock deadline is far below it (crates/worker limits). +create or replace function private.sheet_verification_lease() +returns interval language sql immutable set search_path = '' as $$ select interval '10 minutes' $$; + +-- The largest verdict text accepted (the at-caps fixture measures far below). +create or replace function private.sheet_verification_max_verdict_bytes() +returns integer language sql immutable set search_path = '' as $$ select 4194304 $$; + +-- The core's failure codes (crates/core/src/domain/sheet/verdict.rs `codes`). +create or replace function private.sheet_verdict_codes() +returns text[] language sql immutable set search_path = '' as $$ + select array[ + 'verification.integrity.document', 'verification.integrity.base', + 'verification.validation.rules', 'verification.validation.no_geometry', + 'verification.validation.caps', 'verification.integrity.drawing_missing', + 'verification.integrity.size_mismatch', 'verification.integrity.object_conflict', + 'verification.integrity.svg_rejected', 'verification.integrity.svg_removal', + 'verification.integrity.svg_not_canonical', 'verification.validation.out_of_frame', + 'verification.validation.marker_too_small', 'verification.validation.marker_interior_too_small', + 'verification.integrity.fingerprint' + ] +$$; + +-- The worker's technical failure codes (§6.5 transient, timeout, resource, +-- interruption rows; crates/worker `verify_job`). +create or replace function private.sheet_worker_codes() +returns text[] language sql immutable set search_path = '' as $$ + select array[ + 'verification.worker.unavailable', 'verification.worker.timeout', + 'verification.worker.resource_limit', 'verification.worker.lease_expired', + 'verification.worker.verdict_refused' + ] +$$; + +-- The service role only (the worker's key); anything else is refused. +create or replace function private.require_service_role() +returns void language plpgsql stable set search_path = '' as $$ +begin + if auth.role() is distinct from 'service_role' then + raise exception 'rights.capability' using errcode = '42501'; + end if; +end; +$$; + +-- =========================================================================== +-- 2. Group keys a verdict must carry (§6.3, §6.4) +-- =========================================================================== +-- `general`, `view:` per view, `zone:` per finding zone: the core's +-- `keys::group_keys` (crates/core/src/domain/sheet/review.rs). +create or replace function private.sheet_document_group_keys(p_doc jsonb) +returns text[] language sql immutable set search_path = '' as $$ + select array['general'] + || coalesce((select array_agg(distinct 'view:' || (v ->> 'id')) + from jsonb_array_elements(case jsonb_typeof(p_doc -> 'views') when 'array' then p_doc -> 'views' else '[]'::jsonb end) v + where jsonb_typeof(v -> 'id') = 'string'), '{}') + || coalesce((select array_agg(distinct 'zone:' || (z ->> 'id')) + from jsonb_array_elements(case jsonb_typeof(p_doc -> 'finding_zones') when 'array' then p_doc -> 'finding_zones' else '[]'::jsonb end) z + where jsonb_typeof(z -> 'id') = 'string'), '{}') +$$; + +-- The base of a round's version: the published source it derives from (§6.2). +create or replace function private.sheet_review_base(p_version_id uuid) +returns jsonb language sql stable security definer set search_path = '' as $$ + select s.content + from public.anatomical_sheet_versions v + join public.anatomical_sheet_versions s on s.id = v.source_version_id + where v.id = p_version_id +$$; + +-- A passed verdict's structure (§6.4): its groups are exactly the document's +-- keys and the base's removed ones, each with a digest; its drawings exactly +-- the document's asset ids with the rows' sha256, each `ok`; a fingerprint. +create or replace function private.passed_verdict_fits(p_verdict jsonb, p_sheet_id uuid, p_doc jsonb, p_base jsonb) +returns boolean language plpgsql stable security definer set search_path = '' as $$ +declare + v_expected text[]; + v_keys text[]; + v_drawings jsonb; +begin + if p_verdict -> 'failure_code' is distinct from 'null'::jsonb + or p_verdict -> 'failures' is distinct from '[]'::jsonb + or coalesce(p_verdict ->> 'fingerprint', '') !~ '^[0-9a-f]{64}$' + or jsonb_typeof(p_verdict -> 'groups') is distinct from 'array' + or jsonb_typeof(p_verdict -> 'drawings') is distinct from 'array' then + return false; + end if; + if exists ( + select 1 from jsonb_array_elements(p_verdict -> 'groups') g + where jsonb_typeof(g) <> 'object' + or jsonb_typeof(g -> 'key') is distinct from 'string' + or coalesce(g ->> 'digest', '') !~ '^[0-9a-f]{64}$' + or jsonb_typeof(g -> 'coverable') is distinct from 'boolean' + ) then + return false; + end if; + select array_agg(distinct k order by k) into v_expected + from unnest(private.sheet_document_group_keys(p_doc) + || coalesce(private.sheet_document_group_keys(p_base), '{}')) k; + select array_agg(g ->> 'key' order by g ->> 'key') into v_keys + from jsonb_array_elements(p_verdict -> 'groups') g; + -- Same set, no duplicate key. + if v_keys is distinct from v_expected then + return false; + end if; + v_drawings := p_verdict -> 'drawings'; + if exists ( + select 1 from jsonb_array_elements(v_drawings) d + where jsonb_typeof(d) <> 'object' or d ->> 'result' is distinct from 'ok' + or jsonb_typeof(d -> 'asset_id') is distinct from 'string' + or jsonb_typeof(d -> 'sha256') is distinct from 'string' + ) then + return false; + end if; + return ( + select coalesce(array_agg(lower(d ->> 'asset_id') || '/' || (d ->> 'sha256') order by 1), '{}') + from jsonb_array_elements(v_drawings) d + ) = ( + select coalesce(array_agg(a.id::text || '/' || a.sha256 order by 1), '{}') + from public.anatomical_sheet_assets a + where a.sheet_id = p_sheet_id + and a.id::text = any (private.sheet_document_asset_ids(p_doc)) + ) and jsonb_array_length(v_drawings) = cardinality(private.sheet_document_asset_ids(p_doc)); +end; +$$; + +-- =========================================================================== +-- 3. Worker RPCs +-- =========================================================================== +-- Claim up to `max_jobs` rounds (1 to 10). A dead lease counts as an attempt +-- already spent (§6.5 interruption); at the limit the round closes +-- `verification_failed` / `unavailable` with `lease_expired`. +create or replace function public.claim_sheet_verifications(max_jobs integer) +returns table ( + review_id uuid, version_id uuid, sheet_id uuid, revision integer, + lease_token uuid, attempts integer +) +language plpgsql +volatile +security definer +set search_path = '' +as $$ +#variable_conflict use_variable +declare + v_limit integer := least(greatest(coalesce(max_jobs, 1), 1), 10); + v_closed record; +begin + perform private.require_service_role(); + for v_closed in + update public.anatomical_sheet_reviews r + set status = 'verification_failed', failure_outcome = 'unavailable', + failure_code = 'verification.worker.lease_expired', lease_token = null, locked_at = null + where r.status = 'verifying' + and r.locked_at is not null and r.locked_at < now() - private.sheet_verification_lease() + and r.attempts >= private.sheet_verification_attempt_limit() + returning r.id, r.attempts + loop + perform private.log_event(null, 'anatomical_sheet_review.verification_failed', 'anatomical_sheet_review', + v_closed.id, null, null, + jsonb_build_object('outcome', 'unavailable', 'code', 'verification.worker.lease_expired', 'attempts', v_closed.attempts)); + end loop; + + return query + with picked as ( + select r.id + from public.anatomical_sheet_reviews r + where r.status = 'verifying' + and (r.locked_at is null or r.locked_at < now() - private.sheet_verification_lease()) + and r.attempts < private.sheet_verification_attempt_limit() + order by r.submitted_at + limit v_limit + for update skip locked + ), leased as ( + update public.anatomical_sheet_reviews r + set lease_token = gen_random_uuid(), locked_at = now(), attempts = r.attempts + 1, + -- A dead lease left no code: record the interruption it was. + failure_code = case when r.locked_at is not null then 'verification.worker.lease_expired' else r.failure_code end + from picked + where r.id = picked.id + returning r.id, r.version_id, r.revision, r.lease_token, r.attempts + ) + select l.id, l.version_id, v.sheet_id, l.revision, l.lease_token, l.attempts + from leased l + join public.anatomical_sheet_versions v on v.id = l.version_id; +end; +$$; + +-- The input of a leased round: the document at the round's revision (frozen +-- while the round is `verifying`), the base, the drawing rows the document +-- references among those registered for the sheet. Null for a stale lease. +create or replace function public.get_sheet_verification_input(review_id uuid, lease_token uuid) +returns jsonb +language plpgsql +stable +security definer +set search_path = '' +as $$ +#variable_conflict use_variable +declare + v_review public.anatomical_sheet_reviews%rowtype; + v_version public.anatomical_sheet_versions%rowtype; +begin + perform private.require_service_role(); + select r.* into v_review from public.anatomical_sheet_reviews r where r.id = review_id; + if v_review.id is null or v_review.status <> 'verifying' or v_review.lease_token is distinct from lease_token then + return null; + end if; + select v.* into v_version from public.anatomical_sheet_versions v where v.id = v_review.version_id; + -- The draft is frozen while its round is open; a revision past the round's + -- is a stale round (never reached: the freeze trigger refuses the save). + if v_version.revision <> v_review.revision then + return null; + end if; + return jsonb_build_object( + 'review_id', v_review.id, + 'version_id', v_version.id, + 'sheet_id', v_version.sheet_id, + 'revision', v_review.revision, + 'document', v_version.content::text, + 'base_document', private.sheet_review_base(v_version.id)::text, + 'drawings', coalesce(( + select jsonb_agg(jsonb_build_object( + 'asset_id', a.id, 'sha256', a.sha256, 'byte_size', a.byte_size, + 'bucket', 'anatomical-sheet-assets', 'object_key', a.sha256 || '.svg', + 'uploaded', a.uploaded_at is not null) + order by a.id) + from public.anatomical_sheet_assets a + where a.sheet_id = v_version.sheet_id + and a.id::text = any (private.sheet_document_asset_ids(v_version.content)) + ), '[]'::jsonb) + ); +end; +$$; + +-- Record the verdict of a leased round. Answers `passed` or `failed` once +-- written; `stale` (not verifying, another token, another round) or +-- `malformed` (wrong shape, unknown code, groups or drawings that do not fit +-- the document) write nothing. +create or replace function public.complete_sheet_verification(review_id uuid, lease_token uuid, verdict jsonb) +returns text +language plpgsql +volatile +security definer +set search_path = '' +as $$ +#variable_conflict use_variable +declare + v_review public.anatomical_sheet_reviews%rowtype; + v_version public.anatomical_sheet_versions%rowtype; + v_outcome text; + v_code text; +begin + perform private.require_service_role(); + select r.* into v_review from public.anatomical_sheet_reviews r where r.id = review_id for update; + if v_review.id is null or v_review.status <> 'verifying' or v_review.lease_token is distinct from lease_token then + return 'stale'; + end if; + select v.* into v_version from public.anatomical_sheet_versions v where v.id = v_review.version_id; + if jsonb_typeof(verdict) is distinct from 'object' + or octet_length(verdict::text) > private.sheet_verification_max_verdict_bytes() + or verdict -> 'format' is distinct from '1'::jsonb + or jsonb_typeof(verdict -> 'review_id') is distinct from 'string' + or jsonb_typeof(verdict -> 'version_id') is distinct from 'string' + or jsonb_typeof(verdict -> 'sheet_id') is distinct from 'string' + or jsonb_typeof(verdict -> 'revision') is distinct from 'number' + or jsonb_typeof(verdict -> 'verified_with') is distinct from 'string' + or char_length(verdict ->> 'verified_with') > 100 then + return 'malformed'; + end if; + -- A verdict naming another round or revision answers a round that no longer + -- exists as such (§6.5 stale result). + if lower(verdict ->> 'review_id') <> v_review.id::text + or lower(verdict ->> 'version_id') <> v_version.id::text + or lower(verdict ->> 'sheet_id') <> v_version.sheet_id::text + or (verdict -> 'revision') <> to_jsonb(v_review.revision) then + return 'stale'; + end if; + v_outcome := verdict ->> 'outcome'; + if v_outcome = 'passed' then + if not private.passed_verdict_fits(verdict, v_version.sheet_id, v_version.content, + private.sheet_review_base(v_version.id)) then + return 'malformed'; + end if; + update public.anatomical_sheet_reviews r + set status = 'open', verdict = complete_sheet_verification.verdict, verified_at = now(), + verified_with = verdict ->> 'verified_with', failure_outcome = null, failure_code = null, + lease_token = null, locked_at = null + where r.id = v_review.id; + perform private.log_event(null, 'anatomical_sheet_review.verification_passed', 'anatomical_sheet_review', + v_review.id, null, null, + jsonb_build_object('sheet_id', v_version.sheet_id, 'version_id', v_version.id, 'revision', v_review.revision, + 'verified_with', verdict ->> 'verified_with')); + return 'passed'; + end if; + if v_outcome is distinct from 'failed' then + return 'malformed'; + end if; + -- A failed verdict may carry no group or drawing (an unreadable document): + -- its codes are the core's closed list, the first one recorded. + v_code := verdict ->> 'failure_code'; + if v_code is null or not (v_code = any (private.sheet_verdict_codes())) + or jsonb_typeof(verdict -> 'failures') is distinct from 'array' + or jsonb_array_length(verdict -> 'failures') = 0 + or exists (select 1 from jsonb_array_elements(verdict -> 'failures') f + where jsonb_typeof(f) <> 'string' or not ((f #>> '{}') = any (private.sheet_verdict_codes()))) + or verdict -> 'failures' -> 0 <> to_jsonb(v_code) then + return 'malformed'; + end if; + update public.anatomical_sheet_reviews r + set status = 'verification_failed', verdict = complete_sheet_verification.verdict, verified_at = now(), + verified_with = verdict ->> 'verified_with', failure_outcome = 'failed', failure_code = v_code, + lease_token = null, locked_at = null + where r.id = v_review.id; + perform private.log_event(null, 'anatomical_sheet_review.verification_failed', 'anatomical_sheet_review', + v_review.id, null, null, + jsonb_build_object('sheet_id', v_version.sheet_id, 'version_id', v_version.id, 'revision', v_review.revision, + 'outcome', 'failed', 'codes', verdict -> 'failures')); + return 'failed'; +end; +$$; + +-- A technical failure of a leased round (§6.5): the round stays `verifying` +-- and claimable, its code recorded, until the attempt limit closes it +-- `verification_failed` / `unavailable`. Answers `retry`, `unavailable` or +-- `stale` (nothing written). +create or replace function public.fail_sheet_verification(review_id uuid, lease_token uuid, code text) +returns text +language plpgsql +volatile +security definer +set search_path = '' +as $$ +#variable_conflict use_variable +declare + v_review public.anatomical_sheet_reviews%rowtype; + v_final boolean; +begin + perform private.require_service_role(); + if code is null or not (code = any (private.sheet_worker_codes())) then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + select r.* into v_review from public.anatomical_sheet_reviews r where r.id = review_id for update; + if v_review.id is null or v_review.status <> 'verifying' or v_review.lease_token is distinct from lease_token then + return 'stale'; + end if; + v_final := v_review.attempts >= private.sheet_verification_attempt_limit(); + update public.anatomical_sheet_reviews r + set failure_code = code, lease_token = null, locked_at = null, + status = case when v_final then 'verification_failed'::public.sheet_round_status else r.status end, + failure_outcome = case when v_final then 'unavailable'::public.sheet_verification_outcome else null end + where r.id = v_review.id; + perform private.log_event(null, + case when v_final then 'anatomical_sheet_review.verification_failed' else 'anatomical_sheet_review.verification_attempt_failed' end, + 'anatomical_sheet_review', v_review.id, null, null, + jsonb_build_object('code', code, 'attempts', v_review.attempts, + 'outcome', case when v_final then 'unavailable' end)); + return case when v_final then 'unavailable' else 'retry' end; +end; +$$; + +-- =========================================================================== +-- 4. Privileges: the service role only +-- =========================================================================== +revoke all on function private.sheet_verification_attempt_limit() from public; +revoke all on function private.sheet_verification_lease() from public; +revoke all on function private.sheet_verification_max_verdict_bytes() from public; +revoke all on function private.sheet_verdict_codes() from public; +revoke all on function private.sheet_worker_codes() from public; +revoke all on function private.require_service_role() from public; +revoke all on function private.sheet_document_group_keys(jsonb) from public; +revoke all on function private.sheet_review_base(uuid) from public; +revoke all on function private.passed_verdict_fits(jsonb, uuid, jsonb, jsonb) from public; + +revoke all on function public.claim_sheet_verifications(integer) from public, anon, authenticated; +revoke all on function public.get_sheet_verification_input(uuid, uuid) from public, anon, authenticated; +revoke all on function public.complete_sheet_verification(uuid, uuid, jsonb) from public, anon, authenticated; +revoke all on function public.fail_sheet_verification(uuid, uuid, text) from public, anon, authenticated; +grant execute on function public.claim_sheet_verifications(integer) to service_role; +grant execute on function public.get_sheet_verification_input(uuid, uuid) to service_role; +grant execute on function public.complete_sheet_verification(uuid, uuid, jsonb) to service_role; +grant execute on function public.fail_sheet_verification(uuid, uuid, text) to service_role; diff --git a/supabase/tests/018_sheet_access_matrix.sql b/supabase/tests/018_sheet_access_matrix.sql index ee05ae1a..3ff1e805 100644 --- a/supabase/tests/018_sheet_access_matrix.sql +++ b/supabase/tests/018_sheet_access_matrix.sql @@ -241,8 +241,8 @@ 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)'); + 'claim_sheet_verifications,complete_sheet_verification,confirm_sheet_asset_upload,fail_sheet_verification,get_sheet_asset_state,get_sheet_verification_input', + 'service_role executes only the upload confirmation, the operator read and the M6 worker RPCs (§5.4, §6.4)'); -- ============ F14 and §5.6: every catalogue RPC refused without the right ============ select pg_temp.matrix('O', 'aal2', '42501 rights.capability'); diff --git a/supabase/tests/021_sheet_verification_jobs.sql b/supabase/tests/021_sheet_verification_jobs.sql new file mode 100644 index 00000000..5e94472f --- /dev/null +++ b/supabase/tests/021_sheet_verification_jobs.sql @@ -0,0 +1,221 @@ +-- V1-2.3 M6: the worker RPCs of the server verdict (contract §6.4, §6.5). +-- Service role only; claim with a lease, input bound to the live token, +-- completion checked for its binding and structure (stale / malformed write +-- nothing), technical failures up to the attempt limit, dead leases. +begin; +select plan(51); + +insert into auth.users (id, email, email_confirmed_at) values + ('f0000000-0000-0000-0000-000000000001', 'own@vj.local', now()), + ('f0000000-0000-0000-0000-00000000000e', 'ed@vj.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 '%@vj.local'; +insert into auth.sessions (id, user_id, aal) values + ('f1000000-0000-0000-0000-000000000001', 'f0000000-0000-0000-0000-000000000001', 'aal2'), + ('f1000000-0000-0000-0000-00000000000e', 'f0000000-0000-0000-0000-00000000000e', 'aal2'); +select set_config('request.jwt.claims', '', true); +select private.assign_platform_role(null, 'f0000000-0000-0000-0000-000000000001', 'owner'); +select private.assign_platform_role(null, 'f0000000-0000-0000-0000-00000000000e', 'admin'); +insert into public.anatomical_catalog_grants (user_id, grant_kind, reason, verification_note, granted_by) values + ('f0000000-0000-0000-0000-00000000000e','sheet_editor','a','c','f0000000-0000-0000-0000-000000000001'); + +create table pg_temp.k(key text primary key, id uuid); +grant all on pg_temp.k to authenticated, service_role; +create function pg_temp.id(p text) returns uuid language sql security definer as $$ select id from pg_temp.k where key = p $$; +grant execute on function pg_temp.id(text) to authenticated, service_role; +create function pg_temp.act(p uuid, s uuid) returns void language sql as $$ + select set_config('request.jwt.claims', jsonb_build_object('sub',p,'role','authenticated','aal','aal2','session_id',s)::text, true); +$$; +grant execute on function pg_temp.act(uuid,uuid) to authenticated; +create function pg_temp.worker() returns void language sql as $$ + select set_config('request.jwt.claims', '{"role":"service_role"}', true); +$$; +grant execute on function pg_temp.worker() to service_role; +create function pg_temp.doc(p_asset uuid, p_name text) returns jsonb language sql as $$ + select jsonb_build_object('schema_version',2,'species_id','equine', + 'name',jsonb_build_object('fr',p_name,'en',p_name), + '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, + 'finding_zones',jsonb_build_array(jsonb_build_object('id','z1','name',jsonb_build_object('fr','Z','en','Z'),'categories','[]'::jsonb))); +$$; +grant execute on function pg_temp.doc(uuid,text) to authenticated; +-- Test helpers read the round as the test owner (security definer): the +-- service role has no grant on the table. +-- The core's verdict for a round: passed with the document's groups and +-- drawing, or failed with a code (no group, no drawing). +create function pg_temp.verdict(p_review uuid, p_outcome text, p_code text default null) returns jsonb language sql security definer as $$ + select jsonb_build_object('format',1,'outcome',p_outcome, + 'failure_code',p_code, + 'failures',case when p_code is null then '[]'::jsonb else jsonb_build_array(p_code) end, + 'sheet_id',v.sheet_id,'version_id',v.id,'revision',r.revision,'review_id',r.id, + 'verified_with','faunosteo-core test', + 'fingerprint',case when p_outcome = 'passed' then repeat('f',64) end, + 'drawings',case when p_outcome = 'passed' then jsonb_build_array(jsonb_build_object('asset_id',pg_temp.id('asset'),'sha256',repeat('8',64),'byte_size',900,'result','ok','detail',null)) else '[]'::jsonb end, + 'document_bytes',100,'issues','[]'::jsonb,'caps',null,'completeness',null, + 'groups',case when p_outcome = 'passed' then jsonb_build_array( + jsonb_build_object('key','general','digest',repeat('1',64),'coverable',true,'removed',false), + jsonb_build_object('key','view:main','digest',repeat('2',64),'coverable',true,'removed',false), + jsonb_build_object('key','zone:z1','digest',repeat('3',64),'coverable',true,'removed',false)) else '[]'::jsonb end, + 'changes',null) + from public.anatomical_sheet_reviews r join public.anatomical_sheet_versions v on v.id = r.version_id + where r.id = p_review; +$$; +grant execute on function pg_temp.verdict(uuid,text,text) to service_role; +create function pg_temp.status(p text) returns text language sql security definer as $$ + select status::text || '/' || coalesce(failure_outcome::text, '-') || '/' || coalesce(failure_code, '-') + from public.anatomical_sheet_reviews where id = pg_temp.id(p); +$$; +grant execute on function pg_temp.status(text) to service_role; +create function pg_temp.token(p text) returns uuid language sql security definer as $$ + select lease_token from public.anatomical_sheet_reviews where id = pg_temp.id(p); +$$; +grant execute on function pg_temp.token(text) to service_role; + +-- A sheet with one confirmed drawing; three drafts submitted (r1, r2, r3). +set local role authenticated; +select pg_temp.act('f0000000-0000-0000-0000-00000000000e','f1000000-0000-0000-0000-00000000000e'); +insert into pg_temp.k select 'sheet', public.create_official_sheet('vj-sheet', pg_temp.doc(null,'VJ')); +insert into pg_temp.k select 'v1', id from public.anatomical_sheet_versions where sheet_id = pg_temp.id('sheet'); +insert into pg_temp.k select 'asset', public.register_sheet_asset(pg_temp.id('sheet'), repeat('8',64), 900, 'd.svg'); +reset role; +insert into storage.objects (bucket_id,name,metadata) values ('anatomical-sheet-assets', repeat('8',64)||'.svg', '{"size":900}'); +set local role authenticated; +select pg_temp.act('f0000000-0000-0000-0000-00000000000e','f1000000-0000-0000-0000-00000000000e'); +select public.confirm_sheet_asset_upload(pg_temp.id('asset')); +select public.save_sheet_draft(pg_temp.id('v1'), 0, pg_temp.doc(pg_temp.id('asset'),'VJ'), 'wire'); +insert into pg_temp.k select 'r1', public.submit_sheet_review(pg_temp.id('v1'), 1, 'one'); + +-- 1. Privileges: the service role only. +reset role; +select ok(not has_function_privilege('anon', 'public.claim_sheet_verifications(integer)', 'execute'), 'anon cannot claim'); +select ok(not has_function_privilege('authenticated', 'public.claim_sheet_verifications(integer)', 'execute'), 'authenticated cannot claim'); +select ok(not has_function_privilege('authenticated', 'public.get_sheet_verification_input(uuid, uuid)', 'execute'), 'authenticated cannot read the input'); +select ok(not has_function_privilege('authenticated', 'public.complete_sheet_verification(uuid, uuid, jsonb)', 'execute'), 'authenticated cannot complete'); +select ok(not has_function_privilege('authenticated', 'public.fail_sheet_verification(uuid, uuid, text)', 'execute'), 'authenticated cannot fail'); +select ok(not has_function_privilege('anon', 'public.complete_sheet_verification(uuid, uuid, jsonb)', 'execute'), 'anon cannot complete'); +select ok(has_function_privilege('service_role', 'public.claim_sheet_verifications(integer)', 'execute') + and has_function_privilege('service_role', 'public.get_sheet_verification_input(uuid, uuid)', 'execute') + and has_function_privilege('service_role', 'public.complete_sheet_verification(uuid, uuid, jsonb)', 'execute') + and has_function_privilege('service_role', 'public.fail_sheet_verification(uuid, uuid, text)', 'execute'), + 'the service role executes the four RPCs'); +set local role authenticated; +select pg_temp.act('f0000000-0000-0000-0000-000000000001','f1000000-0000-0000-0000-000000000001'); +select throws_ok($$ select public.claim_sheet_verifications(1) $$, '42501', null, 'the owner (authenticated) cannot claim'); +-- The role check holds even when the grant is the service role's but the +-- claims are not (defence in depth). +reset role; +set local role service_role; +select set_config('request.jwt.claims', '{"role":"authenticated"}', true); +select throws_ok($$ select public.claim_sheet_verifications(1) $$, '42501', 'rights.capability', 'service role without its claims is refused'); +select pg_temp.worker(); + +-- 2. Claim: lease set, attempt counted, a live lease not claimed twice. +select is((select count(*)::int from public.claim_sheet_verifications(5)), 1, 'one round claimed'); +select ok(pg_temp.token('r1') is not null, 'the round carries a lease token'); +reset role; +select is((select attempts from public.anatomical_sheet_reviews where id = pg_temp.id('r1')), 1, 'attempts counted at the claim'); +set local role service_role; select pg_temp.worker(); +select is((select count(*)::int from public.claim_sheet_verifications(5)), 0, 'a live lease is not claimed again'); + +-- 3. Input bound to the live token. +select is(public.get_sheet_verification_input(pg_temp.id('r1'), gen_random_uuid()), null, 'another token reads nothing'); +select is(public.get_sheet_verification_input(pg_temp.id('r1'), pg_temp.token('r1')) ->> 'revision', '1', 'input names the round revision'); +select is((public.get_sheet_verification_input(pg_temp.id('r1'), pg_temp.token('r1')) ->> 'document')::jsonb -> 'name' ->> 'fr', 'VJ', 'input carries the frozen document as text'); +select is(public.get_sheet_verification_input(pg_temp.id('r1'), pg_temp.token('r1')) -> 'base_document', 'null'::jsonb, 'no base for a first version'); +select is(public.get_sheet_verification_input(pg_temp.id('r1'), pg_temp.token('r1')) -> 'drawings' -> 0 ->> 'object_key', repeat('8',64) || '.svg', 'the drawing row names its object'); +select is(jsonb_array_length(public.get_sheet_verification_input(pg_temp.id('r1'), pg_temp.token('r1')) -> 'drawings'), 1, 'one referenced drawing'); + +-- 4. Completion: stale and malformed write nothing. +select is(public.complete_sheet_verification(pg_temp.id('r1'), gen_random_uuid(), pg_temp.verdict(pg_temp.id('r1'),'passed')), 'stale', 'another token is stale'); +select is(public.complete_sheet_verification(pg_temp.id('r1'), pg_temp.token('r1'), + jsonb_set(pg_temp.verdict(pg_temp.id('r1'),'passed'), '{revision}', '7')), 'stale', 'a verdict of another revision is stale'); +select is(public.complete_sheet_verification(pg_temp.id('r1'), pg_temp.token('r1'), + jsonb_set(pg_temp.verdict(pg_temp.id('r1'),'passed'), '{review_id}', to_jsonb(gen_random_uuid()))), 'stale', 'a verdict of another round is stale'); +select is(public.complete_sheet_verification(pg_temp.id('r1'), pg_temp.token('r1'), + jsonb_set(pg_temp.verdict(pg_temp.id('r1'),'passed'), '{format}', '2')), 'malformed', 'another verdict format is malformed'); +select is(public.complete_sheet_verification(pg_temp.id('r1'), pg_temp.token('r1'), + jsonb_set(pg_temp.verdict(pg_temp.id('r1'),'passed'), '{groups}', (pg_temp.verdict(pg_temp.id('r1'),'passed') -> 'groups') - 2)), 'malformed', 'a passed verdict missing a group is malformed'); +select is(public.complete_sheet_verification(pg_temp.id('r1'), pg_temp.token('r1'), + jsonb_set(pg_temp.verdict(pg_temp.id('r1'),'passed'), '{groups}', (pg_temp.verdict(pg_temp.id('r1'),'passed') -> 'groups') || jsonb_build_array(jsonb_build_object('key','general','digest',repeat('1',64),'coverable',true)))), 'malformed', 'a duplicated group key is malformed'); +select is(public.complete_sheet_verification(pg_temp.id('r1'), pg_temp.token('r1'), + jsonb_set(pg_temp.verdict(pg_temp.id('r1'),'passed'), '{drawings,0,sha256}', to_jsonb(repeat('9',64)))), 'malformed', 'a drawing with another sha256 is malformed'); +select is(public.complete_sheet_verification(pg_temp.id('r1'), pg_temp.token('r1'), + jsonb_set(pg_temp.verdict(pg_temp.id('r1'),'passed'), '{drawings}', '[]')), 'malformed', 'a passed verdict without its drawing is malformed'); +select is(public.complete_sheet_verification(pg_temp.id('r1'), pg_temp.token('r1'), + jsonb_set(pg_temp.verdict(pg_temp.id('r1'),'passed'), '{fingerprint}', 'null')), 'malformed', 'a passed verdict without a fingerprint is malformed'); +select is(public.complete_sheet_verification(pg_temp.id('r1'), pg_temp.token('r1'), + pg_temp.verdict(pg_temp.id('r1'),'failed','verification.invented')), 'malformed', 'a failed verdict with an unknown code is malformed'); +select is(public.complete_sheet_verification(pg_temp.id('r1'), pg_temp.token('r1'), '[]'::jsonb), 'malformed', 'a non-object verdict is malformed'); +select is(pg_temp.status('r1'), 'verifying/-/-', 'nothing written by stale or malformed completions'); + +-- 5. A passed verdict opens the round, once. +select is(public.complete_sheet_verification(pg_temp.id('r1'), pg_temp.token('r1'), pg_temp.verdict(pg_temp.id('r1'),'passed')), 'passed', 'a fitting passed verdict is written'); +reset role; +select is((select status::text || '/' || (verdict ->> 'fingerprint') || '/' || (lease_token is null)::text + from public.anatomical_sheet_reviews where id = pg_temp.id('r1')), 'open/' || repeat('f',64) || '/true', 'round open with its verdict, lease cleared'); +select ok(exists (select 1 from audit.audit_logs where action = 'anatomical_sheet_review.verification_passed' and resource_id = pg_temp.id('r1')), 'passed verification audited'); +set local role service_role; select pg_temp.worker(); +select is(public.complete_sheet_verification(pg_temp.id('r1'), gen_random_uuid(), pg_temp.verdict(pg_temp.id('r1'),'passed')), 'stale', 'a second completion is stale'); + +-- 6. A failed verdict without groups or drawings closes the round failed. +reset role; +set local role authenticated; +select pg_temp.act('f0000000-0000-0000-0000-00000000000e','f1000000-0000-0000-0000-00000000000e'); +select public.withdraw_sheet_review(pg_temp.id('r1'), 'again'); +select public.save_sheet_draft(pg_temp.id('v1'), 1, pg_temp.doc(pg_temp.id('asset'),'VJ2'), 'two'); +insert into pg_temp.k select 'r2', public.submit_sheet_review(pg_temp.id('v1'), 2, 'two'); +reset role; +set local role service_role; select pg_temp.worker(); +select is((select count(*)::int from public.claim_sheet_verifications(1)), 1, 'second round claimed'); +select is(public.complete_sheet_verification(pg_temp.id('r2'), pg_temp.token('r2'), + pg_temp.verdict(pg_temp.id('r2'),'failed','verification.integrity.document')), 'failed', 'a failed verdict without groups is written'); +select is(pg_temp.status('r2'), 'verification_failed/failed/verification.integrity.document', 'round closed failed with its code'); + +-- 7. Technical failures: retry below the limit, unavailable at it. +reset role; +set local role authenticated; +select pg_temp.act('f0000000-0000-0000-0000-00000000000e','f1000000-0000-0000-0000-00000000000e'); +select public.save_sheet_draft(pg_temp.id('v1'), 2, pg_temp.doc(pg_temp.id('asset'),'VJ3'), 'three'); +insert into pg_temp.k select 'r3', public.submit_sheet_review(pg_temp.id('v1'), 3, 'three'); +reset role; +set local role service_role; select pg_temp.worker(); +select is((select count(*)::int from public.claim_sheet_verifications(1)), 1, 'third round claimed'); +select throws_ok(format('select public.fail_sheet_verification(%L, %L, %L)', pg_temp.id('r3'), pg_temp.token('r3'), 'verification.worker.oops'), + 'P0001', 'invalid_input', 'an unknown worker code is refused'); +select is(public.fail_sheet_verification(pg_temp.id('r3'), gen_random_uuid(), 'verification.worker.timeout'), 'stale', 'a failure with another token is stale'); +select is(public.fail_sheet_verification(pg_temp.id('r3'), pg_temp.token('r3'), 'verification.worker.timeout'), 'retry', 'a timeout below the limit is retried'); +select is(pg_temp.status('r3') || '/' || (pg_temp.token('r3') is null)::text, 'verifying/-/verification.worker.timeout/true', 'round stays verifying, code recorded, lease released'); +-- A dead lease is claimed again and recorded as an interruption. +select is((select attempts from public.claim_sheet_verifications(1)), 2, 'reclaimed: second attempt'); +reset role; +update public.anatomical_sheet_reviews set locked_at = now() - interval '11 minutes' where id = pg_temp.id('r3'); +set local role service_role; select pg_temp.worker(); +select is((select attempts from public.claim_sheet_verifications(1)), 3, 'a dead lease is claimed again'); +select is(pg_temp.status('r3'), 'verifying/-/verification.worker.lease_expired', 'the interruption is recorded'); +-- At the limit, a technical failure closes the round unavailable. +reset role; +update public.anatomical_sheet_reviews set attempts = 5 where id = pg_temp.id('r3'); +set local role service_role; select pg_temp.worker(); +select is(public.fail_sheet_verification(pg_temp.id('r3'), pg_temp.token('r3'), 'verification.worker.resource_limit'), 'unavailable', 'the last attempt closes the round'); +select is(pg_temp.status('r3'), 'verification_failed/unavailable/verification.worker.resource_limit', 'round closed unavailable with the last code'); +reset role; +select ok(exists (select 1 from audit.audit_logs where action = 'anatomical_sheet_review.verification_attempt_failed' and resource_id = pg_temp.id('r3')), 'attempt failure audited'); + +-- 8. A dead lease at the limit is closed by the next claim. +set local role authenticated; +select pg_temp.act('f0000000-0000-0000-0000-00000000000e','f1000000-0000-0000-0000-00000000000e'); +select public.save_sheet_draft(pg_temp.id('v1'), 3, pg_temp.doc(pg_temp.id('asset'),'VJ4'), 'four'); +insert into pg_temp.k select 'r4', public.submit_sheet_review(pg_temp.id('v1'), 4, 'four'); +reset role; +update public.anatomical_sheet_reviews set attempts = 5, lease_token = gen_random_uuid(), locked_at = now() - interval '11 minutes' where id = pg_temp.id('r4'); +set local role service_role; select pg_temp.worker(); +select is((select count(*)::int from public.claim_sheet_verifications(5)), 0, 'a round at the limit is not claimed'); +select is(pg_temp.status('r4'), 'verification_failed/unavailable/verification.worker.lease_expired', 'its dead lease closes it unavailable'); + +select * from finish(); +rollback;