diff --git a/.claude/memory/evals.md b/.claude/memory/evals.md index 86ae4ce7..929c474e 100644 --- a/.claude/memory/evals.md +++ b/.claude/memory/evals.md @@ -64,3 +64,10 @@ Result: first gate pass → verifier ECARTS(5), security BLOCK(1): private EXECU Anomalies: 6 test-side fixes on first pgTAP run (RLS hides rows → "no change" asserts; data-modifying CTE; collation of `order by`; trigger name order decides errcode; audit list; pg_temp grants). Executor (opus) deviated usefully: RegionCode pattern separate from StableId. Action: LRN-038/039/040, BLK-007. Keep the two-gate pass on every migration step. + +## EVAL-009 | 2026-10-09 | Step 4b equine import — importer tests, pgTAP both engines, Docker build, gates + +Method: packages/anatomy 30 vitest (counts in=out on both sides, special cases, determinism, golden artifacts, guards); pgTAP 001–007 on PGlite and real stack (`db reset`, `db test` 256/256, `gen types` diff clean); root check (61+30+20+278, lint 0, build); `docker build` of the app image; Storage API end-to-end (owner 400 before confirmation → 200 after, alice/anon 400); fresh verifier (C1–C12) + security-auditor (semgrep 130 rules, 0 findings). +Result: first pass verifier ECARTS(4) (self-referential in=out control, undeclared importer-authored labels, docs vs literal sql_paths, silent FR→EN fallback) + security PASS with MEDIUM hash-claim bypass (register_sheet_asset accepts any sha256 → editor reads foreign objects). All fixed: `uploaded_at` + `confirm_sheet_asset_upload` (service role) required by the read predicate, bob-claims-hash pgTAP, authored-label anomalies (27 anomalies now), seeds-listed test, Dockerfile missing workspace manifests (found by building, not by the gates). +Anomalies: real image `storage.protect_delete` aborts direct DELETE tests (LRN-041); pg_temp fixtures need service_role grants; docker build raced the lockfile refresh (rebuild clean). +Action: fresh verifier re-dispatched on the delta; BDR-034, LRN-041. diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index f617cf0d..a1bf3b1a 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -184,4 +184,4 @@ Step 3 Supabase foundation on feature/step-03-supabase-foundation (9 commits, pu ## 2026-10-09 Step 4 validated + finished into develop. User decisions on the 7 open points → BDR-033 (follow-gated use, verified publication, no auto-deprecation, platform-owned official, kind rename, server validation, erasure path). Step 4b on feature/step-04b-equine-import: packages/anatomy importer (opus executor, 25 tests) → seed equine v1 as DRAFT (27 ann / 26 linked / 792 nodes / 612 leaves / 41 vet, 0 integrity issues, 18 anomalies reported, ssb-dysfunctions flagged); Storage migration + policy through the sheet, shim storage tables, harness applies seed/**, pgTAP 006/007 (238/238 real stack), assets uploaded + REST/Storage checks (owner 200, alice/anon 400). BDR-034, LRN-041. Gates dispatched; stop for user validation before Step 5. - +- Gates 4b: verifier ECARTS(4) + security PASS/MEDIUM → fixed same session (confirm_sheet_asset_upload + uploaded_at in read predicate, 27 anomalies declared, seeds-listed test, Dockerfile manifests for domain/anatomy, docker build green). Real stack 256/256, Storage e2e verified. EVAL-009. Fresh verifier re-run on delta; stop for user validation. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 3687c1fe..6f2e6dc9 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -75,7 +75,7 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo - [x] 4b.2 migration 20261009100000 sheet asset storage: bucket anatomical-sheet-assets (private), object read policy through the sheet (published refs or editor), no API writes; shim storage tables; pgTAP - [x] 4b.3 seed: equine_v1.sql idempotent (platform-owned official sheet, private, draft v1, 2 asset rows, fixed ids) in config sql_paths + PGlite harness applies supabase/seed/**; pgTAP 006: draft present, not publishable by non-admin, sheet_document_issues empty, assets match; upload script for the SVG bytes (service key from env, user/operator runs) - [x] 4b.4 real stack: db reset + db test + types check + assets upload + REST read check; docs (SUPABASE.md, ANATOMICAL_SHEET_MODEL.md §6 import, CLAUDE.md, plan note, CHANGELOG) - - [ ] 4b.5 verify: pnpm check green (61+25+19+278), real stack reset/test 238/238, types in sync, assets uploaded + Storage API 200/400/400; verifier + security gates dispatched; BDR-034, LRN-041 + - [x] 4b.5 verify: pnpm check green (61+30+20+278), real stack 256/256, types in sync, docker build OK, Storage API 400→200 after confirmation (alice/anon 400); verifier ECARTS(4) + security MEDIUM (hash claim) → fixed (uploaded_at + confirm RPC, authored labels, seeds-listed test, Dockerfile manifests); EVAL-009 --- diff --git a/CLAUDE.md b/CLAUDE.md index 8db072e8..5f4c2245 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -329,7 +329,8 @@ Database (Supabase) from public and granted only to the roles that evaluate them. - A migration is never edited once applied. Each migration ships its pgTAP file with allowed AND denied cases, and a regenerated `database.types.ts`. -- The browser holds the anon key only. `service_role` never appears in env.js, .env.example or code. +- The browser holds the anon key only. The `service_role` key value never appears in env.js, .env.example or code; + operator scripts under `packages/*/scripts/` read it from the environment and are never bundled. - pgTAP files run on PGlite and on the real image: scope counts to fixture ids, pin `collate "C"` on text ordering. ### Anatomical sheet model (packages/domain + migration 20261008110000) diff --git a/Dockerfile b/Dockerfile index ec79d059..27e293d4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -11,6 +11,8 @@ RUN corepack enable && corepack prepare pnpm@10.13.1 --activate # Workspace manifests first for layer caching (install depends only on these) COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./ COPY apps/app/package.json apps/app/ +COPY packages/domain/package.json packages/domain/ +COPY packages/anatomy/package.json packages/anatomy/ COPY packages/supabase/package.json packages/supabase/ RUN pnpm install --frozen-lockfile diff --git a/docs/development/ANATOMICAL_SHEET_MODEL.md b/docs/development/ANATOMICAL_SHEET_MODEL.md index 614330fe..a81fd079 100644 --- a/docs/development/ANATOMICAL_SHEET_MODEL.md +++ b/docs/development/ANATOMICAL_SHEET_MODEL.md @@ -315,5 +315,9 @@ Rules of the import: Storage: bucket `anatomical-sheet-assets` (private, SVG only, 20 MiB cap), objects `.svg`, read policy `anatomical_sheet_assets_read` through -`private.can_read_sheet_asset_object` (published reference of a usable -sheet, or editor); no API writes (operator upload, `SUPABASE.md` §3.1). +`private.can_read_sheet_asset_object`: the asset row must be **confirmed** +(`uploaded_at`, set only by `confirm_sheet_asset_upload` with the service +role once the bytes are in the bucket) and either edited by the caller or +referenced by a non-draft version of a usable sheet. A hash a user registers +on their own sheet therefore opens nothing. No API writes (operator upload, +`SUPABASE.md` §3.1). diff --git a/docs/development/SUPABASE.md b/docs/development/SUPABASE.md index 5d1bfe90..2f0e4325 100644 --- a/docs/development/SUPABASE.md +++ b/docs/development/SUPABASE.md @@ -68,14 +68,17 @@ ever reaches the browser. Two kinds of seed (`config.toml [db.seed] sql_paths`): -| File | Scope | Content | -| --------------- | ----------------- | ---------------------------------------------------------------------------------- | -| `seed.sql` | local only | dev accounts + first owner | -| `seed/**/*.sql` | every environment | versioned reference data, idempotent (today: the official equine sheet as a draft) | +| File | Scope | Content | +| -------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------ | +| `seed.sql` | local only | dev accounts + first owner | +| `seed/…/*.sql` | every environment | versioned reference data, idempotent (today: the official equine sheet as a draft); each file listed explicitly in `sql_paths` | -The PGlite harness applies `seed/**` after the migrations, `seed.sql` never -(it needs the real auth schema). On another environment, apply a versioned +The PGlite harness applies every `.sql` under `seed/` after the migrations, +`seed.sql` never (it needs the real auth schema); a test fails when a seed +file is missing from `sql_paths`. On another environment, apply a versioned seed with `psql -f` from a privileged session, then upload its assets (§3.1). +Never run `supabase db push --include-seed` against a shared database: the +list also contains `seed.sql` and its known local password. ### 3.1 Sheet assets (Storage) @@ -86,12 +89,16 @@ any version for its editors. No API role uploads; the operator does, with the service key, from the generated seed folder: ```bash -SUPABASE_URL=http://127.0.0.1:54321 SUPABASE_SERVICE_ROLE_KEY= \ - pnpm assets:upload supabase/seed/anatomical-sheets/equine/v1 +export SUPABASE_URL=http://127.0.0.1:54321 +read -rs SUPABASE_SERVICE_ROLE_KEY && export SUPABASE_SERVICE_ROLE_KEY # typed, not in shell history +pnpm assets:upload supabase/seed/anatomical-sheets/equine/v1 ``` The script verifies each file against `assets.json` (sha256, size) before -uploading and skips objects already present. +uploading, keeps objects already present, and calls +`confirm_sheet_asset_upload` (service role only) for each asset row: the +read policy ignores a row whose upload was never confirmed, so a user who +registers a known hash on their own sheet opens nothing. Seed accounts (local only, password `LocalDev-only-password-1`): diff --git a/packages/anatomy/package.json b/packages/anatomy/package.json index c7701dcd..03f90905 100644 --- a/packages/anatomy/package.json +++ b/packages/anatomy/package.json @@ -19,11 +19,11 @@ "import:equine": "tsx src/cli/import-equine.ts" }, "dependencies": { - "@faunosteo/domain": "workspace:*", - "@xmldom/xmldom": "^0.9.8" + "@faunosteo/domain": "workspace:*" }, "devDependencies": { "@types/node": "^20.19.41", + "@xmldom/xmldom": "^0.9.8", "eslint": "^9.17.0", "globals": "^15.14.0", "prettier": "^3.4.2", diff --git a/packages/anatomy/src/legacy/annotations.ts b/packages/anatomy/src/legacy/annotations.ts index f8cf777d..3f3ed3cb 100644 --- a/packages/anatomy/src/legacy/annotations.ts +++ b/packages/anatomy/src/legacy/annotations.ts @@ -118,8 +118,27 @@ function mapTrigger( return { annotation, region: null } } -function observableName(a: LegacyAnnotation) { +/** Missing labels fall back to the other language, never silently. */ +function observableName(a: LegacyAnnotation, out: Anomaly[]) { const fr = a.nameFr ?? a.nameEn ?? a.id + if (a.nameFr === null) { + out.push( + anomaly( + 'annotation.name_fr.missing', + a.id, + `data-anno-name-fr absent : nom FR repris de « ${fr} ».`, + ), + ) + } + if (a.nameEn === null) { + out.push( + anomaly( + 'annotation.name_en.missing', + a.id, + `data-anno-name-en absent : nom EN copié du FR « ${fr} », à traduire.`, + ), + ) + } return { fr, en: a.nameEn ?? fr } } @@ -128,7 +147,7 @@ function mapObservable( ctx: AnnotationContext, out: Anomaly[], ) { - const name = observableName(a) + const name = observableName(a, out) const zoneId = ctx.zoneByNames.get(zoneNameKey(name.fr, name.en)) ?? null if (zoneId === null) { out.push( diff --git a/packages/anatomy/src/legacy/authored-labels.ts b/packages/anatomy/src/legacy/authored-labels.ts new file mode 100644 index 00000000..5b45d199 --- /dev/null +++ b/packages/anatomy/src/legacy/authored-labels.ts @@ -0,0 +1,41 @@ +import type { AnatomicalSheetDocumentInput } from '@faunosteo/domain' +import type { Anomaly } from './types' + +/** + * Lists every FR/EN text the importer writes itself (no source file holds + * it), derived from the document so the list can never drift from what is + * written. Annotation categories are reported by categories.ts. + */ + +export const AUTHORED_LABEL_CODE = 'label.authored' + +function authored(subject: string, text: { fr?: string; en?: string }) { + const parts = [ + text.fr === undefined ? null : `FR « ${text.fr} »`, + text.en === undefined ? null : `EN « ${text.en} »`, + ].filter((part): part is string => part !== null) + const anomaly: Anomaly = { + code: AUTHORED_LABEL_CODE, + level: 'a_valider', + subject, + message: `Libellé écrit par l'importateur : ${parts.join(', ')}.`, + } + return anomaly +} + +export function regionLabelSubject(code: string): string { + return `vertebral_config.${code}` +} + +export function authoredLabelAnomalies( + document: AnatomicalSheetDocumentInput, +): Anomaly[] { + return [ + authored('name', document.name), + authored('description', document.description), + ...document.views.map((v) => authored(`views.${v.id}`, v.name)), + ...document.vertebral_config.regions.map((r) => + authored(regionLabelSubject(r.code), r.name), + ), + ] +} diff --git a/packages/anatomy/src/legacy/catalog-checks.ts b/packages/anatomy/src/legacy/catalog-checks.ts index f3a80d67..7ba450f8 100644 --- a/packages/anatomy/src/legacy/catalog-checks.ts +++ b/packages/anatomy/src/legacy/catalog-checks.ts @@ -60,6 +60,12 @@ function collectIds(nodes: readonly LegacyNode[], into: Set): void { } } +/** Locale-independent order: artifacts must not vary with the process. */ +function byCodePoint(a: string, b: string): number { + if (a === b) return 0 + return a < b ? -1 : 1 +} + /** Node ids are unique among siblings only; a finding is (zone, path). */ function crossZoneDuplicates(catalog: LegacyCatalog): Anomaly[] { const zonesById = new Map() @@ -69,9 +75,7 @@ function crossZoneDuplicates(catalog: LegacyCatalog): Anomaly[] { for (const id of ids) zonesById.set(id, (zonesById.get(id) ?? 0) + 1) } const shared = [...zonesById.entries()].filter(([, n]) => n > 1) - const top = [...shared].sort( - (a, b) => b[1] - a[1] || a[0].localeCompare(b[0]), - ) + const top = [...shared].sort((a, b) => b[1] - a[1] || byCodePoint(a[0], b[0])) return [ { code: 'finding.id.shared_across_zones', diff --git a/packages/anatomy/src/legacy/catalog.ts b/packages/anatomy/src/legacy/catalog.ts index b3dff730..da3362ff 100644 --- a/packages/anatomy/src/legacy/catalog.ts +++ b/packages/anatomy/src/legacy/catalog.ts @@ -169,11 +169,7 @@ function mapCategory( /** Counts categories as nodes, as the audit does (792 = 78 + 714). */ export function countTree( nodes: ReadonlyArray, -): { - nodes: number - leaves: number - vetReferrals: number -} { +): TreeCounts { let total = { nodes: 0, leaves: 0, vetReferrals: 0 } for (const node of nodes) { const children = node.children ?? [] @@ -201,15 +197,23 @@ function zoneStatsOf(zone: LegacyZone): ZoneStats { } } -/** Throws when the output tree does not hold exactly the input nodes. */ -function assertNothingDropped(zone: LegacyZone, mapped: ZoneInput): void { - const before = countTree(zone.categories) - const after = countTree(mapped.categories) - if (before.nodes !== after.nodes || before.leaves !== after.leaves) { - throw new Error( - `zone ${zone.id}: ${before.nodes} nodes in, ${after.nodes} out`, - ) - } +export interface TreeCounts { + nodes: number + leaves: number + vetReferrals: number +} + +/** Throws when the output tree does not hold exactly the input tree. */ +export function assertNothingDropped( + zoneId: string, + before: TreeCounts, + after: TreeCounts, +): void { + const keys = ['nodes', 'leaves', 'vetReferrals'] as const + const diff = keys.filter((key) => before[key] !== after[key]) + if (diff.length === 0) return + const detail = diff.map((k) => `${k} ${before[k]} in, ${after[k]} out`) + throw new Error(`zone ${zoneId}: ${detail.join('; ')}`) } function mapZone(key: string, zone: LegacyZone, state: WalkState): ZoneInput { @@ -219,7 +223,11 @@ function mapZone(key: string, zone: LegacyZone, state: WalkState): ZoneInput { name: { fr: zone.name_fr, en: zone.name_en }, categories: zone.categories.map((c) => mapCategory(key, c, state)), } - assertNothingDropped(zone, mapped) + assertNothingDropped( + key, + countTree(zone.categories), + countTree(mapped.categories), + ) return mapped } diff --git a/packages/anatomy/src/legacy/importer.ts b/packages/anatomy/src/legacy/importer.ts index ee8875c2..5c8f2d57 100644 --- a/packages/anatomy/src/legacy/importer.ts +++ b/packages/anatomy/src/legacy/importer.ts @@ -17,6 +17,7 @@ import { type LegacyCatalog, type MappedCatalog, } from './catalog' +import { authoredLabelAnomalies } from './authored-labels' import { catalogAnomalies } from './catalog-checks' import { mapCategories, type MappedCategories } from './categories' import { assetIdFromSha256, sha256Hex, sheetIdFor } from './ids' @@ -181,6 +182,7 @@ function countBy( } function buildStats( + sources: ParsedSources, document: AnatomicalSheetDocumentInput, mapped: Mapped, ): ImportStats { @@ -189,7 +191,8 @@ function buildStats( const sum = (key: 'nodes' | 'leaves' | 'vetReferrals') => totals.reduce((acc, zone) => acc + zone[key], 0) return { - legacyAnnotations: mapped.annotations.length, + legacyAnnotations: + sources.main.annotations.length + sources.head.annotations.length, annotations: annotations.length, annotationsByView: { [MAIN_VIEW_ID]: countBy(annotations, (a) => a.view_id === MAIN_VIEW_ID), @@ -215,6 +218,14 @@ function buildStats( } } +/** Every data-anno-id read from the SVGs must be written once. */ +function assertAnnotationsKept(stats: ImportStats): void { + if (stats.legacyAnnotations === stats.annotations) return + throw new Error( + `${stats.legacyAnnotations} annotations read, ${stats.annotations} written`, + ) +} + function sourceAnomalies( sources: ParsedSources, stats: ImportStats, @@ -272,8 +283,10 @@ function collectAnomalies( sources: ParsedSources, mapped: Mapped, stats: ImportStats, + document: AnatomicalSheetDocumentInput, ): Anomaly[] { return [ + ...authoredLabelAnomalies(document), ...sources.main.anomalies, ...sources.head.anomalies, ...mapped.annotations.flatMap((m) => m.anomalies), @@ -290,7 +303,8 @@ export function importEquineLegacy(input: EquineLegacyInput): ImportResult { const mapped = mapSources(sources) const document = buildDocument(sources, mapped) const parsed = AnatomicalSheetDocumentSchema.parse(document) - const stats = buildStats(document, mapped) + const stats = buildStats(sources, document, mapped) + assertAnnotationsKept(stats) return { document, legacyIdMap: buildIdMap(sources, mapped), @@ -310,7 +324,7 @@ export function importEquineLegacy(input: EquineLegacyInput): ImportResult { ), zoneStats: mapped.catalog.zoneStats, stats, - anomalies: collectAnomalies(sources, mapped, stats), + anomalies: collectAnomalies(sources, mapped, stats, document), issues: validateSheetDocument(parsed), } } diff --git a/packages/anatomy/src/legacy/report.ts b/packages/anatomy/src/legacy/report.ts index ed794447..f2c1bdb5 100644 --- a/packages/anatomy/src/legacy/report.ts +++ b/packages/anatomy/src/legacy/report.ts @@ -1,3 +1,4 @@ +import { AUTHORED_LABEL_CODE, regionLabelSubject } from './authored-labels' import { countTree } from './catalog' import type { Anomaly, ImportResult } from './types' @@ -96,9 +97,22 @@ function volumesSection(result: ImportResult): string { '', table(['Mesure', 'Valeur'], rows), '', - `Contrôle entrée = sortie : ${s.legacyAnnotations} annotations lues, ` + - `${s.annotations} écrites ; ${s.nodes} nœuds lus, ${out.nodes} écrits. ` + - `L'importateur s'arrête si un nœud manque.`, + 'Contrôle entrée = sortie, compté des deux côtés (sources lues, ' + + "document écrit). L'importateur s'arrête au moindre écart :", + '', + table( + ['Contrôle', 'Lu (sources)', 'Écrit (document)'], + [ + [ + 'Annotations (data-anno-id distincts)', + s.legacyAnnotations, + s.annotations, + ], + ['Nœuds (catégories incluses)', s.nodes, out.nodes], + ['Feuilles', s.leaves, out.leaves], + ['Orientations vétérinaires', s.vetReferrals, out.vetReferrals], + ], + ), ].join('\n') } @@ -167,11 +181,19 @@ function categoriesSection(result: ImportResult): string { } function vertebralSection(result: ImportResult): string { + const authored = new Set( + result.anomalies + .filter((a) => a.code === AUTHORED_LABEL_CODE) + .map((a) => a.subject), + ) const regions = result.document.vertebral_config.regions.map((r) => [ code(r.code), r.name.fr, r.name.en, r.count, + authored.has(regionLabelSubject(r.code)) + ? 'importateur, à valider' + : 'source', ]) const inferences = result.regionInferences.map((i) => [ code(result.legacyIdMap.annotations[i.annotationId] ?? i.annotationId), @@ -182,7 +204,13 @@ function vertebralSection(result: ImportResult): string { return [ '## 5. Configuration vertébrale', '', - table(['Code', 'Nom FR', 'Nom EN', 'Vertèbres'], regions), + table( + ['Code', 'Nom FR', 'Nom EN', 'Vertèbres', 'Origine du libellé'], + regions, + ), + '', + 'Nombres de vertèbres : `vertebrae.ts`. Noms de région : écrits par ' + + "l'importateur (aucune source ne les porte).", '', 'Codes de région déduits des libellés (racines `cervic`, `thorac`/`dors`, ' + '`lombair`/`lumbar`, `sacral`/`sacre`, `caudal`/`coccyg`, FR puis ' + @@ -238,6 +266,22 @@ function anomaliesSection(result: ImportResult): string { ].join('\n') } +/** Source keys the document does not carry, and where they live now. */ +const NOT_CARRIED_OVER = [ + '`schema_version` du catalogue (`2.0`) : version du format historique, ' + + 'remplacée par `schema_version: 1` du document canonique ; la valeur ' + + "d'origine est citée dans `attribution.notes`.", + 'bloc `species` du catalogue (`equine`, Cheval / Horse) : porté par ' + + '`species_id` du document et par la table `public.species` ; le nom ' + + 'de la fiche est écrit séparément (voir anomalies `label.authored`).', + 'second élément graphique de chaque annotation (marqueur visuel) : ' + + "reste dans l'asset SVG copié à l'identique, le document ne garde que " + + 'la zone de clic.', + '`data-anno-category-name` : répète le slug technique (`articulations`, ' + + "`os`), ce n'est pas un libellé ; le libellé de catégorie vient de la " + + "table de l'importateur (section 4).", +] + function notImportedSection(result: ImportResult): string { const dropped = result.annotationRows.filter((r) => r.geometry === 'aucune') const lines = @@ -251,9 +295,9 @@ function notImportedSection(result: ImportResult): string { '', ...lines, '', - 'Non repris par construction : le second élément graphique de chaque ' + - "annotation (marqueur visuel), qui reste dans l'asset SVG copié à " + - "l'identique.", + 'Non repris par construction :', + '', + ...NOT_CARRIED_OVER.map((line) => `- ${line}`), ].join('\n') } diff --git a/packages/anatomy/tests/importer.counts.test.ts b/packages/anatomy/tests/importer.counts.test.ts index 8c665406..4dcc23fd 100644 --- a/packages/anatomy/tests/importer.counts.test.ts +++ b/packages/anatomy/tests/importer.counts.test.ts @@ -1,3 +1,4 @@ +import type { FindingNodeInput } from '@faunosteo/domain' import { EQUINE_SOURCE_PATHS, type ImportResult } from '../src' import { legacyAnnoIds, runImport } from './helpers' @@ -51,9 +52,27 @@ describe('equine import volumes', () => { expect(bilateral).toHaveLength(9) }) - it('keeps 26 zones, 792 nodes, 612 leaves, 41 vet referrals', () => { + it('writes 792 nodes, 612 leaves, 41 vet referrals in the document', () => { + const counts = { nodes: 0, leaves: 0, vet: 0 } + const walk = (nodes: readonly FindingNodeInput[]): void => { + for (const node of nodes) { + counts.nodes += 1 + if (!node.children?.length) counts.leaves += 1 + if (node.requires_vet_referral === true) counts.vet += 1 + walk(node.children ?? []) + } + } + for (const zone of result.document.finding_zones) { + counts.nodes += zone.categories.length + for (const category of zone.categories) walk(category.children) + } + expect(counts).toEqual({ nodes: 792, leaves: 612, vet: 41 }) + }) + + it('reports the input side from the sources: 27 ids, 26 zones, 792/612/41', () => { expect(result.document.finding_zones).toHaveLength(26) expect(result.stats).toMatchObject({ + legacyAnnotations: 27, findingZones: 26, nodes: 792, leaves: 612, diff --git a/packages/anatomy/tests/importer.guards.test.ts b/packages/anatomy/tests/importer.guards.test.ts new file mode 100644 index 00000000..82817fbb --- /dev/null +++ b/packages/anatomy/tests/importer.guards.test.ts @@ -0,0 +1,46 @@ +import { renderSeedSql, DOCUMENT_DOLLAR_TAG } from '../src' +import { mapAnnotation } from '../src/legacy/annotations' +import { assertNothingDropped } from '../src/legacy/catalog' +import { parseAnnotatedSvg } from '../src/legacy/svg' +import { runImport } from './helpers' + +/** Guards that never fire on today's data, proven on synthetic inputs. */ + +const SVG_WITHOUT_EN = ` + + +` + +describe('importer guards', () => { + it('throws when a zone loses a vet referral', () => { + const before = { nodes: 10, leaves: 7, vetReferrals: 2 } + const after = { nodes: 10, leaves: 7, vetReferrals: 1 } + expect(() => assertNothingDropped('hip', before, after)).toThrow( + 'zone hip: vetReferrals 2 in, 1 out', + ) + expect(() => assertNothingDropped('hip', before, before)).not.toThrow() + }) + + it('copies FR into EN when data-anno-name-en is absent, and says so', () => { + const [legacy] = parseAnnotatedSvg(SVG_WITHOUT_EN, 'x.svg').annotations + const mapped = mapAnnotation(legacy!, { + viewId: 'main', + fileName: 'x.svg', + zoneByNames: new Map(), + }) + expect(mapped.annotation.name).toEqual({ fr: 'Garrot', en: 'Garrot' }) + expect(mapped.anomalies.map((a) => [a.code, a.level])).toContainEqual([ + 'annotation.name_en.missing', + 'a_valider', + ]) + }) + + it('refuses a document that contains the dollar-quote tag', async () => { + const result = await runImport() + const documentJson = JSON.stringify({ note: DOCUMENT_DOLLAR_TAG }) + expect(() => renderSeedSql({ result, documentJson })).toThrow( + DOCUMENT_DOLLAR_TAG, + ) + }) +}) diff --git a/packages/anatomy/tests/importer.special-cases.test.ts b/packages/anatomy/tests/importer.special-cases.test.ts index 4248fa5d..cc359487 100644 --- a/packages/anatomy/tests/importer.special-cases.test.ts +++ b/packages/anatomy/tests/importer.special-cases.test.ts @@ -107,3 +107,22 @@ describe('equine import special cases', () => { expect(Object.keys(leaf).sort()).toEqual(['id', 'name']) }) }) + +describe('importer-authored labels', () => { + it('declares every label written without a source', () => { + const subjects = result.anomalies + .filter((a) => a.code === 'label.authored' && a.level === 'a_valider') + .map((a) => a.subject) + expect(subjects).toEqual([ + 'name', + 'description', + 'views.main', + 'views.head', + 'vertebral_config.C', + 'vertebral_config.T', + 'vertebral_config.L', + 'vertebral_config.S', + 'vertebral_config.Cd', + ]) + }) +}) diff --git a/packages/supabase/scripts/upload-sheet-assets.ts b/packages/supabase/scripts/upload-sheet-assets.ts index da81d751..10c9b01b 100644 --- a/packages/supabase/scripts/upload-sheet-assets.ts +++ b/packages/supabase/scripts/upload-sheet-assets.ts @@ -5,13 +5,15 @@ * Operator tool: needs the service key, which never ships to the browser. * Reads SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY from the environment * (local stack: `pnpm supabase status` prints them). Idempotent: an object - * whose sha256 already exists is skipped, a mismatching upload is refused. + * whose sha256 already exists is kept, a local file whose bytes differ from + * the manifest is refused, and each asset row is confirmed server-side + * (confirm_sheet_asset_upload) so the read policy can trust it. * * pnpm assets:upload supabase/seed/anatomical-sheets/equine/v1 */ import { createHash } from 'node:crypto' import { readFile } from 'node:fs/promises' -import { join, resolve } from 'node:path' +import { basename, join, resolve } from 'node:path' import { createClient } from '@supabase/supabase-js' const BUCKET = 'anatomical-sheet-assets' @@ -20,6 +22,21 @@ interface AssetEntry { file: string sha256: string byte_size: number + svg_asset_id: string +} + +const SHA256_PATTERN = /^[0-9a-f]{64}$/ +const UUID_PATTERN = /^[0-9a-f-]{36}$/ + +/** The manifest is committed data, still: no path separators, hex hash, uuid. */ +function assertEntry(entry: AssetEntry): void { + if (basename(entry.file) !== entry.file || entry.file.startsWith('.')) { + throw new Error(`${entry.file}: file must be a plain file name`) + } + if (!SHA256_PATTERN.test(entry.sha256)) + throw new Error(`${entry.file}: bad sha256`) + if (!UUID_PATTERN.test(entry.svg_asset_id)) + throw new Error(`${entry.file}: bad asset id`) } function requireEnv(name: string): string { @@ -30,7 +47,9 @@ function requireEnv(name: string): string { async function readManifest(dir: string): Promise { const raw = await readFile(join(dir, 'assets.json'), 'utf8') - return JSON.parse(raw) as AssetEntry[] + const entries = JSON.parse(raw) as AssetEntry[] + entries.forEach(assertEntry) + return entries } /** The bytes on disk must still match what the seed recorded. */ @@ -63,7 +82,14 @@ async function main(): Promise { if (error && !/already exists/i.test(error.message)) { throw new Error(`${key}: ${error.message}`) } - console.log(`${error ? 'kept' : 'uploaded'} ${key} (${entry.file})`) + // The asset row becomes readable only once the server records the upload. + const confirmed = await client.rpc('confirm_sheet_asset_upload', { + asset_id: entry.svg_asset_id, + }) + if (confirmed.error) throw new Error(`${key}: ${confirmed.error.message}`) + console.log( + `${error ? 'kept' : 'uploaded'} ${key} (${entry.file}), confirmed`, + ) } } diff --git a/packages/supabase/src/database.types.ts b/packages/supabase/src/database.types.ts index e6b1e77a..1290eb9b 100644 --- a/packages/supabase/src/database.types.ts +++ b/packages/supabase/src/database.types.ts @@ -19,6 +19,7 @@ export type Database = { id: string sha256: string sheet_id: string + uploaded_at: string | null } ComputedFields: never Insert: { @@ -30,6 +31,7 @@ export type Database = { id?: string sha256: string sheet_id: string + uploaded_at?: string | null } Update: { byte_size?: number @@ -40,6 +42,7 @@ export type Database = { id?: string sha256?: string sheet_id?: string + uploaded_at?: string | null } Relationships: [ { @@ -369,6 +372,10 @@ export type Database = { } Functions: { archive_anatomical_sheet: { Args: { sheet_id: string }; Returns: string } + confirm_sheet_asset_upload: { + Args: { asset_id: string } + Returns: string + } create_anatomical_sheet: { Args: { description?: string diff --git a/packages/supabase/tests/db/harness.ts b/packages/supabase/tests/db/harness.ts index 84d79119..228a6540 100644 --- a/packages/supabase/tests/db/harness.ts +++ b/packages/supabase/tests/db/harness.ts @@ -17,7 +17,7 @@ export const repoRoot = resolve(here, '../../../..') export const supabaseDir = join(repoRoot, 'supabase') export const migrationsDir = join(supabaseDir, 'migrations') export const pgTapTestsDir = join(supabaseDir, 'tests') -/** Versioned seeds (reference data such as the official sheets); seed.sql itself needs the real auth schema and stays out. */ +/** Versioned seeds (reference data such as the official sheets); seed.sql itself needs the real auth schema and stays out. The CLI reads literal paths from config.toml: the seeds test checks every file here is listed. */ export const seedDir = join(supabaseDir, 'seed') async function listSqlFiles(dir: string): Promise { diff --git a/packages/supabase/tests/db/schema-types.test.ts b/packages/supabase/tests/db/schema-types.test.ts index 815c1326..584b3a4c 100644 --- a/packages/supabase/tests/db/schema-types.test.ts +++ b/packages/supabase/tests/db/schema-types.test.ts @@ -29,6 +29,7 @@ const expectedColumns = { 'id', 'sha256', 'sheet_id', + 'uploaded_at', ], anatomical_sheet_versions: [ 'change_note', @@ -106,6 +107,7 @@ type FunctionArgs = { } const expectedFunctionArgs = { archive_anatomical_sheet: ['sheet_id'], + confirm_sheet_asset_upload: ['asset_id'], create_anatomical_sheet: [ 'description', 'document', diff --git a/packages/supabase/tests/db/seeds.test.ts b/packages/supabase/tests/db/seeds.test.ts new file mode 100644 index 00000000..141cd0f8 --- /dev/null +++ b/packages/supabase/tests/db/seeds.test.ts @@ -0,0 +1,20 @@ +import { readFile } from 'node:fs/promises' +import { join, relative } from 'node:path' +import { listSeeds, seedDir, supabaseDir } from './harness' + +/** + * The CLI applies only the literal files of config.toml sql_paths, while the + * harness applies every seed on disk: a seed forgotten in the list would pass + * here and never reach `supabase db reset`. + */ +describe('versioned seeds', () => { + it('are all listed in config.toml [db.seed] sql_paths', async () => { + const config = await readFile(join(supabaseDir, 'config.toml'), 'utf8') + const line = config.match(/^sql_paths\s*=\s*\[(.*)\]/m)?.[1] ?? '' + const listed = [...line.matchAll(/"([^"]+)"/g)].map((m) => m[1]) + for (const file of await listSeeds()) { + const path = './' + relative(supabaseDir, join(seedDir, file)) + expect(listed, `${path} missing from sql_paths`).toContain(path) + } + }) +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7e6fc4ee..2ede2c9b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -102,13 +102,13 @@ importers: '@faunosteo/domain': specifier: workspace:* version: link:../domain - '@xmldom/xmldom': - specifier: ^0.9.8 - version: 0.9.12 devDependencies: '@types/node': specifier: ^20.19.41 version: 20.19.41 + '@xmldom/xmldom': + specifier: ^0.9.8 + version: 0.9.12 eslint: specifier: ^9.17.0 version: 9.39.4(jiti@2.7.0) diff --git a/supabase/config.toml b/supabase/config.toml index f08264b2..8d18afc2 100644 --- a/supabase/config.toml +++ b/supabase/config.toml @@ -31,9 +31,11 @@ schema_paths = [] [db.seed] enabled = true -# seed.sql: local development accounts + first owner, never run in prod. -# seed/**: versioned reference data (official anatomical sheets as drafts), -# idempotent, applied in every environment (docs/development/SUPABASE.md §3). +# seed.sql: local development accounts + first owner, LOCAL ONLY (never +# `db push --include-seed` against a shared database: it would run this file). +# seed/...: versioned reference data (official anatomical sheets as drafts), +# idempotent. The CLI takes literal paths: list every new seed file here; the +# PGlite harness test fails when one is missing (docs/development/SUPABASE.md §3). sql_paths = ["./seed.sql", "./seed/anatomical-sheets/equine/v1/equine_v1.sql"] [realtime] diff --git a/supabase/migrations/20261009100000_sheet_asset_storage.sql b/supabase/migrations/20261009100000_sheet_asset_storage.sql index 754a7643..01d973ec 100644 --- a/supabase/migrations/20261009100000_sheet_asset_storage.sql +++ b/supabase/migrations/20261009100000_sheet_asset_storage.sql @@ -4,18 +4,63 @@ -- Bucket anatomical-sheet-assets, private. Objects are content-addressed: -- key = .svg, so two sheets with the same drawing share one object -- and a copy of a sheet never copies bytes. Reading an object is authorised --- THROUGH a sheet (an asset row the caller may use or edit), never through --- the hash alone; drafts stay visible to editors only, as the sheet rows do. --- No API role writes objects: uploads are an operator / server task +-- THROUGH a sheet: an asset row the caller may use or edit AND whose upload +-- was confirmed server-side (uploaded_at), never through a hash a user +-- merely registered; drafts stay visible to editors only, as the sheet rows +-- do. No API role writes objects: uploads are an operator / server task -- (import tool with the service key) until the editor step adds a signed -- upload path. insert into storage.buckets (id, name, public, file_size_limit, allowed_mime_types) values ('anatomical-sheet-assets', 'anatomical-sheet-assets', false, 20971520, array['image/svg+xml']) -on conflict (id) do nothing; +on conflict (id) do update + set public = false, file_size_limit = excluded.file_size_limit, + allowed_mime_types = excluded.allowed_mime_types; --- An object is readable when a usable sheet publishes it (a non-draft --- version references the asset) or when the caller edits the sheet. +-- --------------------------------------------------------------------------- +-- Upload confirmation. An editor may register any sha256 as metadata, so a +-- hash alone must never open an object: the read predicate requires +-- uploaded_at, which only the operator / server path (service role) sets +-- after the bytes have landed in the bucket for that sheet. +-- --------------------------------------------------------------------------- +alter table public.anatomical_sheet_assets + add column uploaded_at timestamptz; + +comment on column public.anatomical_sheet_assets.uploaded_at is + 'Set by confirm_sheet_asset_upload (service role) once the object .svg exists for this sheet. Null = metadata only, object not readable through this row.'; + +create index anatomical_sheet_assets_sha256_idx on public.anatomical_sheet_assets (sha256); + +create or replace function public.confirm_sheet_asset_upload(asset_id uuid) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +begin + update public.anatomical_sheet_assets + set uploaded_at = now() + where id = asset_id and uploaded_at is null; + if not found and not exists (select 1 from public.anatomical_sheet_assets where id = asset_id) then + raise exception 'unknown asset %', asset_id using errcode = 'P0002'; + end if; + perform private.log_event( + auth.uid(), 'anatomical_sheet_asset.uploaded', 'anatomical_sheet_asset', asset_id + ); + return asset_id; +end; +$$; + +comment on function public.confirm_sheet_asset_upload(uuid) is + 'Operator / server only (service role): marks the asset bytes as present in Storage. Idempotent.'; + +revoke all on function public.confirm_sheet_asset_upload(uuid) from public, anon, authenticated; +grant execute on function public.confirm_sheet_asset_upload(uuid) to service_role; + +-- --------------------------------------------------------------------------- +-- Read predicate: a confirmed asset row of a sheet the caller edits, or of a +-- usable sheet whose non-draft version references it. Sargable on sha256. +-- --------------------------------------------------------------------------- create or replace function private.can_read_sheet_asset_object(p_user_id uuid, p_object_name text) returns boolean language sql @@ -26,7 +71,9 @@ as $$ select exists ( select 1 from public.anatomical_sheet_assets a - where a.sha256 || '.svg' = p_object_name + where a.sha256 = left(p_object_name, 64) + and p_object_name = a.sha256 || '.svg' + and a.uploaded_at is not null and ( private.can_edit_sheet(p_user_id, a.sheet_id) or ( @@ -43,7 +90,7 @@ as $$ $$; comment on function private.can_read_sheet_asset_object(uuid, text) is - 'Storage read predicate for bucket anatomical-sheet-assets: object .svg referenced by a published version of a usable sheet, or by any version of a sheet the caller edits.'; + 'Storage read predicate for bucket anatomical-sheet-assets: object .svg whose upload is confirmed, referenced by a published version of a usable sheet, or by any version of a sheet the caller edits.'; revoke all on function private.can_read_sheet_asset_object(uuid, text) from public; grant execute on function private.can_read_sheet_asset_object(uuid, text) to authenticated; diff --git a/supabase/seed/anatomical-sheets/equine/v1/IMPORT-REPORT.md b/supabase/seed/anatomical-sheets/equine/v1/IMPORT-REPORT.md index a20dbbd1..edce7970 100644 --- a/supabase/seed/anatomical-sheets/equine/v1/IMPORT-REPORT.md +++ b/supabase/seed/anatomical-sheets/equine/v1/IMPORT-REPORT.md @@ -37,7 +37,14 @@ Les ids d'asset sont dérivés du sha256 du fichier (UUID déterministe), les de | Feuilles | 612 | | Orientations vétérinaires | 41 | -Contrôle entrée = sortie : 27 annotations lues, 27 écrites ; 792 nœuds lus, 792 écrits. L'importateur s'arrête si un nœud manque. +Contrôle entrée = sortie, compté des deux côtés (sources lues, document écrit). L'importateur s'arrête au moindre écart : + +| Contrôle | Lu (sources) | Écrit (document) | +| ------------------------------------ | ------------ | ---------------- | +| Annotations (data-anno-id distincts) | 27 | 27 | +| Nœuds (catégories incluses) | 792 | 792 | +| Feuilles | 612 | 612 | +| Orientations vétérinaires | 41 | 41 | ## 3. Annotations @@ -85,13 +92,15 @@ Couleur : `null` partout (les couleurs du SVG restent dans l'asset). Dans les SV ## 5. Configuration vertébrale -| Code | Nom FR | Nom EN | Vertèbres | -| ---- | ----------- | -------- | --------- | -| `C` | Cervicales | Cervical | 7 | -| `T` | Thoraciques | Thoracic | 18 | -| `L` | Lombaires | Lumbar | 6 | -| `S` | Sacrales | Sacral | 5 | -| `Cd` | Caudales | Caudal | 18 | +| Code | Nom FR | Nom EN | Vertèbres | Origine du libellé | +| ---- | ----------- | -------- | --------- | ---------------------- | +| `C` | Cervicales | Cervical | 7 | importateur, à valider | +| `T` | Thoraciques | Thoracic | 18 | importateur, à valider | +| `L` | Lombaires | Lumbar | 6 | importateur, à valider | +| `S` | Sacrales | Sacral | 5 | importateur, à valider | +| `Cd` | Caudales | Caudal | 18 | importateur, à valider | + +Nombres de vertèbres : `vertebrae.ts`. Noms de région : écrits par l'importateur (aucune source ne les porte). Codes de région déduits des libellés (racines `cervic`, `thorac`/`dors`, `lombair`/`lumbar`, `sacral`/`sacre`, `caudal`/`coccyg`, FR puis EN). Déduction faite une fois ici, le document porte le code : @@ -139,12 +148,21 @@ Copie fidèle du catalogue : ids, libellés, descriptions présentes, orientatio ## 7. Anomalies à valider -12 points demandent une décision, 6 sont informatifs. +21 points demandent une décision, 6 sont informatifs. ### À valider | Code | Objet | Détail | | --------------------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `label.authored` | name | Libellé écrit par l'importateur : FR « Cheval », EN « Horse ». | +| `label.authored` | description | Libellé écrit par l'importateur : FR « Fiche anatomique officielle Faunosteo », EN « Official Faunosteo anatomical sheet ». | +| `label.authored` | views.main | Libellé écrit par l'importateur : FR « Vue générale », EN « Overview ». | +| `label.authored` | views.head | Libellé écrit par l'importateur : FR « Tête », EN « Head ». | +| `label.authored` | vertebral_config.C | Libellé écrit par l'importateur : FR « Cervicales », EN « Cervical ». | +| `label.authored` | vertebral_config.T | Libellé écrit par l'importateur : FR « Thoraciques », EN « Thoracic ». | +| `label.authored` | vertebral_config.L | Libellé écrit par l'importateur : FR « Lombaires », EN « Lumbar ». | +| `label.authored` | vertebral_config.S | Libellé écrit par l'importateur : FR « Sacrales », EN « Sacral ». | +| `label.authored` | vertebral_config.Cd | Libellé écrit par l'importateur : FR « Caudales », EN « Caudal ». | | `category.label.authored` | articulations | Libellé écrit par l'importateur : FR « Articulations », EN « Joints ». | | `category.label.authored` | os | Libellé écrit par l'importateur : FR « Os », EN « Bones ». | | `category.slug.normalised` | charni-res-vert-brales | Slug technique dégradé (accents perdus) normalisé en « charnieres-vertebrales ». | @@ -173,7 +191,12 @@ Copie fidèle du catalogue : ids, libellés, descriptions présentes, orientatio Aucune donnée métier écartée. -Non repris par construction : le second élément graphique de chaque annotation (marqueur visuel), qui reste dans l'asset SVG copié à l'identique. +Non repris par construction : + +- `schema_version` du catalogue (`2.0`) : version du format historique, remplacée par `schema_version: 1` du document canonique ; la valeur d'origine est citée dans `attribution.notes`. +- bloc `species` du catalogue (`equine`, Cheval / Horse) : porté par `species_id` du document et par la table `public.species` ; le nom de la fiche est écrit séparément (voir anomalies `label.authored`). +- second élément graphique de chaque annotation (marqueur visuel) : reste dans l'asset SVG copié à l'identique, le document ne garde que la zone de clic. +- `data-anno-category-name` : répète le slug technique (`articulations`, `os`), ce n'est pas un libellé ; le libellé de catégorie vient de la table de l'importateur (section 4). ## 9. Résultat de validation diff --git a/supabase/tests/006_sheet_asset_storage.sql b/supabase/tests/006_sheet_asset_storage.sql index 88e569e5..4aea4e98 100644 --- a/supabase/tests/006_sheet_asset_storage.sql +++ b/supabase/tests/006_sheet_asset_storage.sql @@ -2,7 +2,7 @@ -- through a sheet (published reference for users, any version for editors), -- never through its hash alone. No API writes. begin; -select plan(14); +select plan(28); insert into auth.users (id, email) values ('30000000-0000-0000-0000-00000000000a', 'alice-assets@test.local'), @@ -11,8 +11,8 @@ insert into auth.users (id, email) values create table pg_temp.ids (key text primary key, id uuid not null); create function pg_temp.id(p_key text) returns uuid language sql stable as $$ select id from pg_temp.ids where key = p_key $$; -grant all on pg_temp.ids to anon, authenticated; -grant execute on function pg_temp.id(text) to anon, authenticated; +grant all on pg_temp.ids to anon, authenticated, service_role; +grant execute on function pg_temp.id(text) to anon, authenticated, service_role; -- Minimal publishable document with one main view on a given asset. create function pg_temp.doc(p_asset uuid) returns jsonb language sql as $$ @@ -27,7 +27,7 @@ create function pg_temp.doc(p_asset uuid) returns jsonb language sql as $$ 'name', jsonb_build_object('fr', 'V', 'en', 'V'), 'svg_asset_id', p_asset, 'view_box', null)), 'annotations', '[]'::jsonb, 'finding_zones', '[]'::jsonb); $$; -grant execute on function pg_temp.doc(uuid) to authenticated; +grant execute on function pg_temp.doc(uuid) to authenticated, service_role; -- 1. Bucket contract select is((select public from storage.buckets where id = 'anatomical-sheet-assets'), false, 'bucket is private'); @@ -59,26 +59,45 @@ select lives_ok($$ select public.publish_sheet_version(pg_temp.id('v1')) $$, 'v1 insert into pg_temp.ids select 'v2', public.create_sheet_draft(pg_temp.id('sheet')); update public.anatomical_sheet_versions set content = pg_temp.doc(pg_temp.id('b')) where id = pg_temp.id('v2'); --- Objects uploaded by the operator (owner session) +-- Objects uploaded by the operator (owner session), then confirmed through the +-- service-role RPC for A and B only; C stays metadata without bytes. reset role; insert into storage.objects (bucket_id, name) values ('anatomical-sheet-assets', repeat('a', 64) || '.svg'), ('anatomical-sheet-assets', repeat('b', 64) || '.svg'), ('anatomical-sheet-assets', repeat('c', 64) || '.svg'), ('anatomical-sheet-assets', repeat('d', 64) || '.svg'); +set local role authenticated; +select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); +select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'nothing is readable before the upload is confirmed'); +select throws_ok( + $$ select public.confirm_sheet_asset_upload(pg_temp.id('a')) $$, + '42501', null, 'an editor cannot confirm an upload (service role only)' +); +set local role service_role; +select lives_ok($$ select public.confirm_sheet_asset_upload(pg_temp.id('a')) $$, 'service role confirms asset A'); +select lives_ok($$ select public.confirm_sheet_asset_upload(pg_temp.id('b')) $$, 'service role confirms asset B'); +select is(public.confirm_sheet_asset_upload(pg_temp.id('a')), pg_temp.id('a'), 'confirming twice is idempotent'); +reset role; -- 3. Editor reads every object of her sheet (published, draft, unreferenced), not foreign ones set local role authenticated; select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); select results_eq( $$ select name from storage.objects where bucket_id = 'anatomical-sheet-assets' order by name $$, - $$ values (repeat('a', 64) || '.svg'), (repeat('b', 64) || '.svg'), (repeat('c', 64) || '.svg') $$, - 'editor reads the objects of her sheet; the object no sheet registered stays hidden' + $$ values (repeat('a', 64) || '.svg'), (repeat('b', 64) || '.svg') $$, + 'editor reads the confirmed objects of her sheet; unconfirmed and foreign objects stay hidden' ); --- 4. Bob: private sheet → nothing; public sheet → published reference only +-- 4. Bob: private sheet → nothing; claiming the hash on his own sheet opens nothing select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000b","role":"authenticated"}', true); select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'other user reads nothing from a private sheet'); +insert into pg_temp.ids select 'bob-sheet', public.create_anatomical_sheet('equine', 'Claim', 'claim-test', pg_temp.doc(null)); +select lives_ok( + $$ select public.register_sheet_asset(pg_temp.id('bob-sheet'), repeat('a', 64), 100, 'A.svg') $$, + 'bob registers the known hash on his own sheet' +); +select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'a self-registered hash without a confirmed upload opens no object'); select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); select lives_ok($$ select public.set_sheet_visibility(pg_temp.id('sheet'), 'public') $$, 'alice makes the sheet public'); select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000b","role":"authenticated"}', true); @@ -100,11 +119,34 @@ select is( 0::bigint, 'no API role has an insert/update/delete policy on the bucket objects' ); +-- Name variants never match the strict key +select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); +select ok( + not private.can_read_sheet_asset_object('30000000-0000-0000-0000-00000000000a', repeat('a', 64)) + and not private.can_read_sheet_asset_object('30000000-0000-0000-0000-00000000000a', upper(repeat('a', 64)) || '.svg') + and not private.can_read_sheet_asset_object('30000000-0000-0000-0000-00000000000a', 'x/' || repeat('a', 64) || '.svg') + and not private.can_read_sheet_asset_object('30000000-0000-0000-0000-00000000000a', repeat('a', 64) || '.svg/'), + 'object name must be exactly .svg' +); +-- A deprecated version still publishes its asset +select lives_ok($$ select public.publish_sheet_version(pg_temp.id('v2')) $$, 'v2 (asset B) published'); +select lives_ok($$ select public.deprecate_sheet_version(pg_temp.id('v1'), 'old') $$, 'v1 (asset A) deprecated'); +select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000b","role":"authenticated"}', true); +select results_eq( + $$ select name from storage.objects where bucket_id = 'anatomical-sheet-assets' order by name $$, + $$ values (repeat('a', 64) || '.svg'), (repeat('b', 64) || '.svg') $$, + 'published and deprecated references both open the object for users of a public sheet' +); + -- 5. Archived sheet hides objects from others; anon sees nothing select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); select lives_ok($$ select public.archive_anatomical_sheet(pg_temp.id('sheet')) $$, 'alice archives'); select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000b","role":"authenticated"}', true); select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'archived sheet: others read nothing'); +select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); +select lives_ok($$ select public.restore_anatomical_sheet(pg_temp.id('sheet')) $$, 'alice restores'); +select lives_ok($$ select public.delete_anatomical_sheet(pg_temp.id('sheet')) $$, 'alice soft-deletes the sheet'); +select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'deleted sheet: even the creator reads nothing'); set local role anon; select set_config('request.jwt.claims', '', true); select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'anon reads nothing'); diff --git a/supabase/tests/007_equine_seed.sql b/supabase/tests/007_equine_seed.sql index d204943b..24d70229 100644 --- a/supabase/tests/007_equine_seed.sql +++ b/supabase/tests/007_equine_seed.sql @@ -2,7 +2,7 @@ -- present as a platform-owned DRAFT, never published by the seed, publishable -- by platform admins only, content accepted by the SQL referential gate. begin; -select plan(14); +select plan(18); insert into auth.users (id, email) values ('40000000-0000-0000-0000-000000000001', 'root-seed@test.local'), @@ -12,8 +12,8 @@ select private.assign_platform_role(null, '40000000-0000-0000-0000-000000000001' create table pg_temp.ids (key text primary key, id uuid not null); create function pg_temp.id(p_key text) returns uuid language sql stable as $$ select id from pg_temp.ids where key = p_key $$; -grant all on pg_temp.ids to anon, authenticated; -grant execute on function pg_temp.id(text) to anon, authenticated; +grant all on pg_temp.ids to anon, authenticated, service_role; +grant execute on function pg_temp.id(text) to anon, authenticated, service_role; insert into pg_temp.ids select 'sheet', id from public.anatomical_sheets where slug = 'faunosteo-cheval' and is_official; insert into pg_temp.ids select 'draft', id from public.anatomical_sheet_versions where sheet_id = pg_temp.id('sheet'); @@ -74,5 +74,25 @@ select set_config('request.jwt.claims', '{"sub":"40000000-0000-0000-0000-0000000 select is((select count(*) from public.anatomical_sheet_versions where id = pg_temp.id('draft')), 1::bigint, 'a platform admin sees the official draft'); select lives_ok($$ select public.publish_sheet_version(pg_temp.id('draft')) $$, 'a platform admin could publish it (rolled back here)'); +-- 3. Storage: the seed registers metadata only; after the operator upload + confirmation, +-- a platform admin reads both objects and a plain user none. +reset role; +insert into storage.objects (bucket_id, name) + select 'anatomical-sheet-assets', a.sha256 || '.svg' from public.anatomical_sheet_assets a where a.sheet_id = pg_temp.id('sheet'); +set local role authenticated; +select set_config('request.jwt.claims', '{"sub":"40000000-0000-0000-0000-000000000001","role":"authenticated"}', true); +select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'seed objects are not readable before confirmation'); +set local role service_role; +select is( + (select count(*) from public.anatomical_sheet_assets a where a.sheet_id = pg_temp.id('sheet') + and public.confirm_sheet_asset_upload(a.id) = a.id), + 2::bigint, 'operator confirms the two uploads' +); +set local role authenticated; +select set_config('request.jwt.claims', '{"sub":"40000000-0000-0000-0000-000000000001","role":"authenticated"}', true); +select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 2::bigint, 'a platform admin reads both official SVGs'); +select set_config('request.jwt.claims', '{"sub":"40000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); +select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'a plain user reads no official draft SVG'); + select * from finish(); rollback;