From 867ec5e39476ad4c57cadae0868f20104040d3fa Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 23 Nov 2026 00:10:00 +0100 Subject: [PATCH] test(supabase): cat-access census, SQL uniqueness and N-1 readers --- apps/app/tests/unit/n-1.reader.test.ts | 126 ++++++++++++++++++ crates/core/Cargo.toml | 4 + crates/core/tests/access_category_census.rs | 100 ++++++++++++++ .../tests/n-1.access-category.test.ts | 36 +++++ supabase/tests/024_sheet_access_category.sql | 74 ++++++++++ 5 files changed, 340 insertions(+) create mode 100644 crates/core/tests/access_category_census.rs create mode 100644 packages/core-wasm/tests/n-1.access-category.test.ts create mode 100644 supabase/tests/024_sheet_access_category.sql diff --git a/apps/app/tests/unit/n-1.reader.test.ts b/apps/app/tests/unit/n-1.reader.test.ts index 8a351c4d..07c11162 100644 --- a/apps/app/tests/unit/n-1.reader.test.ts +++ b/apps/app/tests/unit/n-1.reader.test.ts @@ -19,6 +19,7 @@ import { import { readFileSync } from 'node:fs' import { resolve } from 'node:path' import { + assertSnapshot, readArchiveDocument, readAttachmentBytes, readReportDocument, @@ -26,6 +27,10 @@ import { ReportSchema, } from '@faunosteo/core-wasm/n-1' import { exportReportToPdf } from '@/pdf/export' +import { CataloguePreview } from '@/catalogue/preview' +import { coreRuntime } from '@/core/runtime' +import { applyEdits } from '@/editor/core/editOps' +import type { BundledSheetData } from '@/sheets/provider' import { importAttachment } from '../helpers/pdfImport' import { useReportStore } from '@/state/reportStore' import { ARCHIVE_KEY, DRAFT_KEY } from '@/state/persistence' @@ -34,8 +39,11 @@ import { FIXTURES_DIR, ONE_PX_PNG } from '../helpers/goldens' import { archiveEnvelope, bundledMigrationMap, + bundledSheet, + emptyObservation, loadTestSheet, minimalReport, + sheetFromBundle, } from '../helpers/sheet' vi.mock('@/pdf/browserRasterizer', () => ({ @@ -195,3 +203,121 @@ describe('archives exported from core-built reports', () => { 30_000, ) }) + +/** The bundled reference document with a detail view on the main view and its access. */ +function documentWithAccess(document: unknown): string { + const edited = applyEdits(JSON.stringify(document), [ + { + op: 'insert', + element: { + kind: 'view', + value: { + id: 'view-forelimbaa', + kind: 'detail', + name: { fr: 'Membre antérieur', en: 'Forelimb' }, + parent_view_id: 'main', + svg_asset_id: null, + view_box: { min_x: 625, min_y: 969, width: 220, height: 660 }, + }, + }, + }, + { + op: 'insert', + element: { + kind: 'annotation', + value: { + id: 'anno-forelimbaa', + kind: 'detail_trigger', + view_id: 'main', + category_id: 'cat-access', + laterality: 'left', + geometry: { + type: 'polygon', + points: [ + [625, 969], + [845, 969], + [845, 1629], + [625, 1629], + ], + }, + review_status: 'to_confirm', + color: null, + name: null, + opens_view_id: 'view-forelimbaa', + }, + }, + }, + ]) + if (!edited.ok) throw new Error(edited.kind) + return edited.value +} + +/** The edited draft's fingerprint, from a preview load (the route the app takes). */ +function previewFingerprint(text: string, bundle: BundledSheetData): string { + const drawings = Object.entries(bundle.assets).map(([assetId, svg]) => ({ + assetId, + sha256: bundle.assetHashes[assetId]!, + bytes: new TextEncoder().encode(svg), + })) + const preview = new CataloguePreview( + coreRuntime(), + { status: 'draft', document: text }, + drawings, + ) + const state = preview.state() + preview.free() + if (!state.ok || !state.value.fingerprint) throw new Error('preview refused') + return state.value.fingerprint +} + +/** The edited document as a new bundle: its own fingerprint, no historical alias. */ +async function accessSheet(): Promise { + const bundle = await bundledSheet() + const text = documentWithAccess(bundle.document) + const fingerprint = previewFingerprint(text, bundle) + return sheetFromBundle({ + ...bundle, + ref: { + ...bundle.ref, + document_sha256: fingerprint, + fingerprint: { + convention: 'sha256-rfc8785-validated-v1', + aliases: [], + }, + }, + document: JSON.parse(text), + } as BundledSheetData) +} + +describe('a sheet carrying cat-access (detail view and its access)', () => { + it('its archive and PDF attachment read back through the N-1 readers', async () => { + const edited = await accessSheet() + const report = minimalReport(edited, { + observations: [ + { + ...emptyObservation(), + zones: [{ annotationId: 'c7-t1', viewId: 'main' }], + }, + ], + }) + const { pdf } = await exportReportToPdf(report, edited, { locale: 'fr' }) + const bytes = new Uint8Array(await pdf.arrayBuffer()) + const data: unknown = JSON.parse( + new TextDecoder().decode(await readAttachmentBytes(bytes)), + ) + expect(ReportArchiveEnvelopeSchema.safeParse(data).success).toBe(true) + const outcome = readArchiveDocument(data, await bundledMigrationMap()) + expect(outcome.origin).toBe('envelope_v1') + expect(outcome.archive).not.toBeNull() + expect(outcome.snapshotRejected).toBeUndefined() + const snapshot = (data as { sheetSnapshot: unknown }).sheetSnapshot + expect(() => assertSnapshot(snapshot)).not.toThrow() + // Observed fact: the lean snapshot carries the category, the view and the + // access, even though the report's zone touches none of them; the N-1 + // readers above accept them. + const kept = JSON.stringify(snapshot) + expect(kept).toContain('cat-access') + expect(kept).toContain('view-forelimbaa') + expect(kept).toContain('anno-forelimbaa') + }, 30_000) +}) diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 7c15f76b..7cfc7d8a 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -160,3 +160,7 @@ required-features = ["pdf-read"] [[test]] name = "r5_6_switch" required-features = ["pdf-read", "pdf-write"] + +[[test]] +name = "access_category_census" +required-features = ["pdf-read"] diff --git a/crates/core/tests/access_category_census.rs b/crates/core/tests/access_category_census.rs new file mode 100644 index 00000000..83362fd2 --- /dev/null +++ b/crates/core/tests/access_category_census.rs @@ -0,0 +1,100 @@ +//! No collision with the reserved `cat-access` category: no data file shipped +//! with the app (seeds, fixtures, oracles, goldens, PDF attachments) already +//! uses that id, except the N-1 fixture written to carry it. +#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)] + +mod common; + +use common::r4::repo_root; +use faunosteo_core::pdf::read::probe::{ProbeLimits, read_attached_document}; +use std::path::{Path, PathBuf}; + +const RESERVED: &str = "cat-access"; +const TREES: [&str; 5] = [ + "supabase/seed", + "crates/core/tests/fixtures", + "crates/core/tests/oracles", + "apps/app/tests/fixtures", + "packages/core-wasm/tests", +]; +const EXEMPT: &str = "crates/core/tests/fixtures/n1/access-category.json"; +const DATA_EXTENSIONS: [&str; 4] = ["json", "sql", "svg", "md"]; + +fn files_under(dir: &Path, out: &mut Vec) { + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + files_under(&path, out); + } else { + out.push(path); + } + } +} + +fn all_files() -> Vec { + let mut files = Vec::new(); + for tree in TREES { + let root = repo_root().join(tree); + assert!(root.is_dir(), "{root:?} is not a directory"); + files_under(&root, &mut files); + } + files +} + +fn extension(path: &Path) -> &str { + path.extension().and_then(|e| e.to_str()).unwrap_or("") +} + +fn contains_reserved(bytes: &[u8]) -> bool { + bytes + .windows(RESERVED.len()) + .any(|w| w == RESERVED.as_bytes()) +} + +/// The attachment text under the production limits; a refused read or a +/// missing attachment (the hostile files) is "no attachment". +fn attachment_has_reserved(bytes: &[u8]) -> bool { + match read_attached_document(bytes, ProbeLimits::PRODUCTION) { + Ok(located) => contains_reserved(located.text.as_bytes()), + Err(_) => false, + } +} + +#[test] +fn no_data_file_uses_the_reserved_category_id() { + let exempt = repo_root().join(EXEMPT); + let mut checked = 0; + for path in all_files() { + if !DATA_EXTENSIONS.contains(&extension(&path)) || path == exempt { + continue; + } + checked += 1; + let bytes = std::fs::read(&path).unwrap(); + assert!(!contains_reserved(&bytes), "{path:?} contains {RESERVED}"); + } + assert!(checked > 100, "census walked only {checked} data files"); +} + +#[test] +fn no_pdf_attachment_uses_the_reserved_category_id() { + let pdf_root = repo_root().join("apps/app/tests/fixtures"); + let mut checked = 0; + for path in all_files() { + if extension(&path) != "pdf" || !path.starts_with(&pdf_root) { + continue; + } + checked += 1; + let bytes = std::fs::read(&path).unwrap(); + assert!( + !attachment_has_reserved(&bytes), + "{path:?} carries {RESERVED}" + ); + } + assert!(checked > 0, "census found no PDF fixture"); +} + +#[test] +fn the_exempt_fixture_does_carry_it() { + let bytes = std::fs::read(repo_root().join(EXEMPT)).unwrap(); + assert!(contains_reserved(&bytes)); +} diff --git a/packages/core-wasm/tests/n-1.access-category.test.ts b/packages/core-wasm/tests/n-1.access-category.test.ts new file mode 100644 index 00000000..ddb04213 --- /dev/null +++ b/packages/core-wasm/tests/n-1.access-category.test.ts @@ -0,0 +1,36 @@ +/** + * The reserved `cat-access` category through the frozen N-1 readers (detail views plan, R3 + * « lecture par l'application N-1 »): the fixture `crates/core/tests/fixtures/n1/access-category.json` + * (the horse slice, the category, a detail view and its access) is read by the Zod schema of the + * build before R2, and its validation twin reports the same issue codes as for the slice alone. + * The native side is `crates/core/tests/n1_access_category.rs`. + */ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' + +import { AnatomicalSheetDocumentSchema } from './n-1' +import { validateSheetDocument } from './n-1/domain/anatomical-sheet/validate' + +const ROOT = fileURLToPath(new URL('../../../', import.meta.url)) +const json = (path: string): unknown => JSON.parse(readFileSync(join(ROOT, path), 'utf8')) + +const fixture = json('crates/core/tests/fixtures/n1/access-category.json') +const sliceInput = (json('crates/core/tests/fixtures/horse-slice.json') as { input: unknown }).input + +const codes = (document: unknown): string[] => + validateSheetDocument(AnatomicalSheetDocumentSchema.parse(document)) + .map((issue) => issue.code) + .sort() + +describe('a sheet carrying cat-access, read by the frozen N-1 build', () => { + it('parses with the N-1 document schema', () => { + const parsed = AnatomicalSheetDocumentSchema.parse(fixture) + expect(parsed.categories.map((category) => category.id)).toContain('cat-access') + expect(parsed.annotations.some((annotation) => annotation.id === 'anno-forelimbaa')).toBe(true) + }) + + it('validates with the same issue codes as the horse slice', () => { + expect(codes(fixture)).toEqual(codes(sliceInput)) + }) +}) diff --git a/supabase/tests/024_sheet_access_category.sql b/supabase/tests/024_sheet_access_category.sql new file mode 100644 index 00000000..66d35961 --- /dev/null +++ b/supabase/tests/024_sheet_access_category.sql @@ -0,0 +1,74 @@ +-- V1-2.6 U2: the reserved `cat-access` category (detail views plan, R3). +-- What SQL really does: since 20261028110000 (lines 139-144) the business +-- mirror is dropped, and `save_sheet_draft` checks the structure and the size +-- only (`private.check_document_structure`, lines 411-441). No SQL rule exists +-- for this feature and none is added. Uniqueness is the core's: +-- `DuplicateKey` on insert, and `category.id.duplicate` in the verdict +-- (`crates/core/tests/sheet_access_category.rs`). So a draft carrying +-- `cat-access` and an access in it saves, and so does one carrying the id +-- twice: the verdict refuses that one later, not the save. +begin; +select plan(3); + +insert into auth.users (id, email, email_confirmed_at) values + ('24000000-0000-0000-0000-000000000001', 'own@m24.local', now()), + ('24000000-0000-0000-0000-00000000000e', 'ed@m24.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 in ('own@m24.local', 'ed@m24.local'); +insert into auth.sessions (id, user_id, aal) values + ('24100000-0000-0000-0000-00000000000e', '24000000-0000-0000-0000-00000000000e', 'aal2'); + +select set_config('request.jwt.claims', '', true); +select private.assign_platform_role(null, '24000000-0000-0000-0000-000000000001', 'owner'); +select private.assign_platform_role(null, '24000000-0000-0000-0000-00000000000e', 'admin'); +insert into public.anatomical_catalog_grants (user_id, grant_kind, reason, verification_note, granted_by) values + ('24000000-0000-0000-0000-00000000000e', 'sheet_editor', 'a', 'c', '24000000-0000-0000-0000-000000000001'); + +create table pg_temp.k (key text primary key, id uuid); +grant all on pg_temp.k to authenticated; +create function pg_temp.act() returns void language sql as $$ + select set_config('request.jwt.claims', jsonb_build_object('sub', '24000000-0000-0000-0000-00000000000e', + 'role', 'authenticated', 'aal', 'aal2', 'session_id', '24100000-0000-0000-0000-00000000000e')::text, true); +$$; +grant execute on function pg_temp.act() to authenticated; +-- A main view and its detail view; `p_access` adds `cat-access` and the access, +-- `p_twice` repeats the category. +create function pg_temp.doc(p_access boolean, p_twice boolean) returns jsonb language sql as $$ + select jsonb_build_object('schema_version', 2, 'species_id', 'equine', + 'name', jsonb_build_object('fr', 'Cheval', 'en', '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', case when p_access then + jsonb_build_array(jsonb_build_object('id', 'cat-access', 'name', jsonb_build_object('fr', 'Accès', 'en', 'Access'), 'color', null)) + || case when p_twice then jsonb_build_array(jsonb_build_object('id', 'cat-access', 'name', jsonb_build_object('fr', 'Bis', 'en', 'Dup'), 'color', null)) else '[]'::jsonb end + else '[]'::jsonb end, + 'views', jsonb_build_array( + jsonb_build_object('id', 'main', 'kind', 'main', 'name', jsonb_build_object('fr', 'V', 'en', 'V'), 'svg_asset_id', null, 'view_box', null), + jsonb_build_object('id', 'detail', 'kind', 'detail', 'name', jsonb_build_object('fr', 'D', 'en', 'D'), 'parent_view_id', 'main', + 'svg_asset_id', null, 'view_box', jsonb_build_object('min_x', 625, 'min_y', 969, 'width', 220, 'height', 660))), + 'annotations', case when p_access then jsonb_build_array(jsonb_build_object('id', 'access', 'kind', 'detail_trigger', + 'view_id', 'main', 'category_id', 'cat-access', 'laterality', 'left', 'review_status', 'to_confirm', 'color', null, 'name', null, + 'opens_view_id', 'detail', 'geometry', jsonb_build_object('type', 'polygon', + 'points', jsonb_build_array(jsonb_build_array(625, 969), jsonb_build_array(845, 969), jsonb_build_array(845, 1629))))) else '[]'::jsonb end, + 'finding_zones', '[]'::jsonb); +$$; +grant execute on function pg_temp.doc(boolean, boolean) to authenticated; + +set local role authenticated; +select pg_temp.act(); +insert into pg_temp.k select 'sheet', public.create_official_sheet('m24-sheet', pg_temp.doc(false, false)); +insert into pg_temp.k select 'v1', id from public.anatomical_sheet_versions + where sheet_id = (select id from pg_temp.k where key = 'sheet'); + +select lives_ok($$ select public.save_sheet_draft((select id from pg_temp.k where key = 'v1'), 0, pg_temp.doc(true, false), 'access') $$, + 'a draft carrying cat-access and an access saves: SQL adds no rule'); +select lives_ok($$ select public.save_sheet_draft((select id from pg_temp.k where key = 'v1'), 1, pg_temp.doc(true, true), 'dup') $$, + 'the category id twice saves too: uniqueness is the core''s, not SQL''s'); +select is((select content #>> '{categories,1,name,en}' from public.anatomical_sheet_versions + where id = (select id from pg_temp.k where key = 'v1')), 'Dup', 'the saved content is the last draft'); + +select * from finish(); +rollback;