diff --git a/.claude/memory/blockers.md b/.claude/memory/blockers.md index c21193b2..0632591f 100644 --- a/.claude/memory/blockers.md +++ b/.claude/memory/blockers.md @@ -58,3 +58,12 @@ Friction: `supabase start` → "permission denied … /var/run/docker.sock"; dae Root: host group membership; needs `sudo usermod -aG docker $USER` + re-login (user runs, not Claude). Workaround: PGlite harness (BDR-028) executes migrations + 81 pgTAP checks; CLI config parses (`supabase start` fails only at Docker inspect). Status: resolved 2026-10-08 (same day) — user added docker group; `supabase start` pulled postgres 17.11.0.004, applied 3 migrations + seed; `supabase test db` 81/81 after scoping counts to fixture ids (seed rows broke 6 absolute counts, PGlite had no seed); `gen types` adopted (CLI output unformatted → piped through prettier); REST script §8 matched expectations; `db reset` from zero OK. + +--- + +## BLK-007 | 2026-10-08 | Per-schema ALTER DEFAULT PRIVILEGES REVOKE is a no-op → private helpers kept PUBLIC EXECUTE + +Friction: Step 4 verifier + security gate both found every `private.*` function executable by `authenticated` (incl. definer helpers taking a caller-supplied actor: assign_platform_role, insert_sheet_draft). +Root: foundation ran `alter default privileges in schema private revoke execute on functions from public`; PostgreSQL adds per-schema defaults on top of the built-in PUBLIC EXECUTE, a per-schema REVOKE cannot remove it. Nothing reachable via API (PostgREST exposes public only, anon no USAGE on private) but the rule "EXECUTE revoked from public" was false. +Fix: explicit `revoke all on function private.f(args) from public` for every function (new migration 20261008110100 for the Step 3 helpers, inline for Step 4); pgTAP 001 census: anon executes nothing in private/audit, authenticated only the 7 policy predicates. +Status: resolved (commit on feature/step-04-anatomical-sheet-model). diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index f17ff41b..58a0cc70 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -255,3 +255,27 @@ Status: closed. CLI gen needs running stack. File written in generator format (Row/Insert/Update/Relationships/Functions/Enums/Constants). `schema-types.test.ts`: compile-time exhaustiveness (every Row column listed, every Args key listed) + runtime diff vs information_schema / pg_enum / pg_proc in PGlite; also pins RLS-on + no `using(true)` for every future public table. CI `db:types:check` diffs against real generator once Docker available; first real run may reformat (PostgrestVersion string) → regenerate + commit. Status: closed; column scalar types (uuid→string…) reviewed by hand, not executed. + +--- + +## BDR-030 | 2026-10-08 | Step 4 split: model + persistence now, importer → official equine DRAFT next + +User brief: no full equine import yet; first official horse sheet = draft, business content verified before publication. Plan Step 4 bundled model + importer. Split: Step 4 = packages/domain document + validation + migration + pgTAP + docs; Step 4b = legacy importer → draft + IMPORT-REPORT, publish on user go. packages/anatomy created at 4b. +Alt rejected: importer in same step → publishes seed v1 immutable before expert review (contradicts brief). +Status: closed (plan note added under Step 4). + +--- + +## BDR-031 | 2026-10-08 | Canonical sheet document shape (schema_version 1) + +Labels `{ fr, en }` objects (one LocalizedText, new locale = optional key) instead of name_fr/name_en pairs. Strict Zod objects (unknown key rejected). Structural records explicit `null`; finding tree nodes lean on input, `.default()` fills description/sources/children/requires_vet_referral (612 leaves). Views = tree (`parent_view_id`), detail `svg_asset_id` nullable = crop parent via `view_box` (C9). Annotation discriminated union point|zone|detail_trigger; `laterality` 4 values explicit (unpaired/bilateral/left/right); spine = `vertebral_region_code` → ordered `vertebral_config.regions` with free codes (C1/Q3); findings link = inline `finding_zone_id` (no separate map, no label matching); finding categories carry `kind` dysfunction|observation|anamnesis|custom; node ids unique among siblings so `(zone, path[])` addressing survives Step 5. Two tiers: shape (Zod, every save) vs integrity (`validateSheetDocument`, 17 coded rules, publish gate). +Alt rejected: name_fr/name_en flat (BDR-009 catalog style) → no locale extension; annotation_finding_map array → extra structure for a 1:N field; UUIDs as in-document ids → unreadable, legacy paths re-keyed. +Status: closed; category kind `observation` vs report Observation collision (C7) flagged to user. + +--- + +## BDR-032 | 2026-10-08 | Sheet persistence: trigger-enforced immutability, SQL publish re-check, content-addressed assets + +Tables species / anatomical_sheets / _versions / _assets. Published immutable via BEFORE UPDATE trigger (every role incl. owner; only published→deprecated with stamps); deprecated frozen; BEFORE DELETE trigger = preconditions (never published, never current, never base of active fork; reports join later) → no session flags, RPC just deletes. One draft per sheet (partial unique index, C8). Document↔row: CHECK `content->'schema_version' = to_jsonb(document_schema_version)`, trigger species match. `private.sheet_document_issues(jsonb)` re-checks the non-recursive error rules at publish + unknown asset ids → defense in depth, same codes as TS (BACKEND_ARCH "SQL doesn't re-implement Zod" kept for shape). Assets content-addressed (sha256, unique per sheet), Storage path `.svg` by convention, fork = metadata copy + `remap_document_assets`. Draft autosave = column-level UPDATE (content, change_note) policy on own draft (unaudited by design); identity (name/slug/description) column policy; visibility via audited `set_sheet_visibility` RPC and draft deletion via `delete_sheet_version` after gate review (sharing + deletion = sensitive state); `last_version_number` counter (no number reuse); content ≤ 2 MiB, byte_size ≤ 20 MiB, reason ≤ 500; `require_actor` refuses deactivated profiles; authz before lookup (unknown id = same 42501); fork copies only referenced assets. can_use_sheet = active ∧ (public ∨ editor) until grants/follows. Official sheet = creator null + is_official, platform admins edit. +Alt rejected: session-flag delete bypass (hacky); Zod-equivalent validation only in TS (browser not a boundary); per-sheet asset storage copy on fork (needs worker job). +Status: closed; names (`anatomical_sheet_assets`, storage layout, official ownership) listed for user confirmation. diff --git a/.claude/memory/evals.md b/.claude/memory/evals.md index 02aa2d67..86ae4ce7 100644 --- a/.claude/memory/evals.md +++ b/.claude/memory/evals.md @@ -56,3 +56,11 @@ Method: `supabase start` (postgres 17.11.0.004), `supabase test db`, `gen types Result: migrations + seed apply from zero; pgTAP 81/81 after fix; REST: alice 1 row, anon 42501, self-deactivate 42501 (column grant), self-grant 42501 (RPC message), cross-row PATCH 0 rows, owner grant → uuid, alice sees her role, owner reads 3 profiles; audit shows system bootstrap + owner grant. Anomalies: (1) 6 pgTAP counts assumed empty DB — seed rows on real stack (PGlite runs no seed) → scoped to fixture ids + neutralise foreign owners before last-owner test. (2) CLI gen output unformatted + `ComputedFields: never`, no `__InternalSupabase` → hand-written file replaced by generated+prettier; scripts pipe prettier. PGlite harness had hidden both: environment parity gap, not logic gap. Action: LRN-037 (tests must be seed-agnostic; generated files via deterministic formatter). BLK-006 resolved. + +## EVAL-008 | 2026-10-08 | Step 4 sheet model — domain tests, pgTAP both engines, fresh verifier + security gates + +Method: packages/domain 61 vitest (schema 29 + integrity 32, one per rule code); pgTAP 005 (127 checks) + 001 census on PGlite and real stack (`db reset`, `db test` 210/210, `gen types` diff clean); root check (typecheck, 356 tests, lint 0, build); fresh verifier (contract C1–C13) + security-auditor (semgrep 725 rules 0 findings + checklist). +Result: first gate pass → verifier ECARTS(5), security BLOCK(1): private EXECUTE not revoked (BLK-007), visibility change unaudited, 7 RPCs without non-editor denial test, doc/code mismatches, 75-line SQL function, `any` suppression in a test. All fixed same session: +32 pgTAP checks, hardening migration, visibility RPC, caps, authz-first, SQL check split in 4 functions, `set()/unset()` typed mutations. Second pass: fresh verifier (pending at write time). +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. + diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 04f152b9..2bbaf8cf 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -178,3 +178,5 @@ SaaS migration kickoff. Step 0: 8 docs in docs/development/ (27-step plan, domai Step 3 Supabase foundation on feature/step-03-supabase-foundation (9 commits, pushed). Docker socket denied (BLK-006) → PGlite+pgtap harness (BDR-028). 3 migrations: foundation (private/audit, set_updated_at, append-only audit_logs, log_event), profiles (auth trigger, own-row RLS, column grants), platform_roles (4-value enum BDR-026, RPC-only writes audited BDR-027, helpers hierarchy). 81 pgTAP checks allowed+denied; packages/supabase (client PKCE, types in gen format BDR-029, schema↔types test); app env.supabase null-safe, lib/supabase.ts, entrypoint/env.example; CI supabase job; SUPABASE.md. 278+13 tests, typecheck/lint/build green. Not run: real stack, gen types, seed. LRN-035/036, EVAL-006. Next: user validation; Step 4 (sheet model) parallelizable; Docker access for real-stack proof. - Same day, Docker access granted by user: real stack up, pgTAP 81/81 after seed-agnostic fix, gen types adopted (prettier pipe), REST script verified, db reset OK. BLK-006 resolved, EVAL-007, LRN-037. Branch still awaiting user validation before finish. - Step 3 validated by user (session 4). chore/supabase-cli-gitignore finished into develop. Step 4 (sheet model) started on feature/step-04-anatomical-sheet-model. +- Step 4 (session 4): spec docs/development/ANATOMICAL_SHEET_MODEL.md; packages/domain (Zod doc strict, 17 integrity rules, 60 tests, opus executor); migration 20261008110000 (species, sheets, immutable versions, assets, 11 RPCs, RLS) + pgTAP 005 (95 checks); types regenerated on real stack (Docker now OK), pgTAP 176/176 real + PGlite; publishSheetVersion gate; docs synced. 5 commits on feature/step-04-anatomical-sheet-model. BDR-030/031/032, LRN-038/039. Verifier + security gates dispatched. Next: user validation, Step 4b importer → equine draft. +- Gates: verifier ECARTS(5) + security BLOCK(1) on first pass (private EXECUTE never revoked = BLK-007, foundation flaw). Fixed: hardening migration 20261008110100, explicit revokes + pgTAP census, set_sheet_visibility RPC, no direct draft DELETE, caps, authz-first, counter, asset copy scoped, SQL check split, url http(s) only. Real stack 210/210, root check green. Fresh verifier re-dispatched on the delta. diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md index 8a3e34b9..fa8a9756 100644 --- a/.claude/memory/learnings.md +++ b/.claude/memory/learnings.md @@ -288,3 +288,24 @@ Apply: every migration; pin with pgTAP privilege checks. Real stack applies `seed.sql` before `supabase test db`; PGlite harness applies migrations only → absolute `count(*)` and "last owner" assertions passed on PGlite, failed on real stack (6/81). Fix: filter every count by fixture ids; neutralise foreign rows inside the rolled-back tx before invariants like "last owner". `supabase gen types` (CLI 2.120) emits unformatted TS and suggests oxfmt → pipe through project prettier in both `db:types` and `db:types:check`, else CI diff flaps. Apply: any dual-runner test setup (shim vs real); any CI diff on generated code. + +--- + +## LRN-038 | 2026-10-08 | RLS filters, never raises: test "no change", and trigger guards under the owner role + +API-role UPDATE/DELETE on a row hidden by policy touches 0 rows silently → `throws_ok` wrong; assert the row unchanged afterwards (`is((select content ...), expected)`). Trigger-level immutability must be proven with `reset role` (table owner bypasses RLS). pgTAP `is()` cannot wrap a data-modifying CTE (`with u as (update …)` must be top level) → plain statement then a read. Triggers fire alphabetically by name: when two BEFORE triggers reject, the first name's errcode surfaces (species check 23514 before guard 42501) → pick test inputs that isolate the guard. +Apply: every RLS + trigger pgTAP file. + +--- + +## LRN-039 | 2026-10-08 | Dual-runner parity: pin collation, grant pg_temp fixtures to API roles + +Real Supabase image sorts text with a locale collation (`anatomical_sheet_asset…` before `anatomical_sheet.archived`), PGlite with C → `results_eq` on `order by text` flaps; pin `order by col collate "C"`. pg_temp tables/functions created as postgres are invisible to `set local role authenticated` → `grant all on pg_temp.t to anon, authenticated; grant execute on function pg_temp.f(...)`. jsonb equality check beats `(x->>'k')::int = n` in a CHECK (no cast error on garbage). +Apply: any pgTAP file with fixtures read while impersonating; any ordered results_eq (extends LRN-037). + +--- + +## LRN-040 | 2026-10-08 | Function privileges: revoke per function, pin with a pg_proc census + +`alter default privileges in schema X revoke execute on functions from public` does nothing (BLK-007). Pattern: every migration ends with `revoke all on function private.f(args) from public` per function + explicit grants; a pgTAP census (`has_function_privilege('anon'|'authenticated', p.oid, 'execute')` over pg_proc of private/audit, compared to an allowlist via `string_agg(... order by proname::text collate "C")`) fails the next omission. `results_eq` over `name`-typed columns vs text literals raises "could not determine which collation" on PGlite → compare one aggregated string. Trigger functions that call other private functions must be `security definer` once EXECUTE is revoked (the invoking API role no longer holds it). +Apply: every Supabase migration; the census is the backstop. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index de7853a6..24a2d08f 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -63,12 +63,12 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo - [x] 3.10 verify: typecheck, test:run 278 app + 13 supabase (81 pgTAP), lint 0, build OK; BDR-026..029, LRN-035/036, BLK-006, EVAL-006 - [ ] Step 4 — canonical anatomical sheet model (2026-10-08, branch feature/step-04-anatomical-sheet-model). Scope re-split: model + validation + persistence + tests here; legacy importer → official equine DRAFT + import report = next step (user: no full import yet, draft verified before publication). Spec: docs/development/ANATOMICAL_SHEET_MODEL.md - [x] 4.0 context + spec: business §2.6–2.9/§7/§16/§17.3/§23, OPEN_QUESTIONS C1/C2/C8/C9/Q3/Q5/Q9, audit 07; ANATOMICAL_SHEET_MODEL.md written - - [ ] 4.1 packages/domain: AnatomicalSheetDocumentSchema (strict, localized {fr,en}, views tree, annotations union, finding tree with category kind), validateSheetDocument (integrity issues), assertPublishable, createEmptySheetDocument; fixture horse-slice; tests per rule + id-stability - - [ ] 4.2 migration 20261008110000_anatomical_sheets: species (seed equine), enums, sheets/versions/assets, triggers (one draft, published immutable, delete preconditions, species match), helpers can_edit/can_use_sheet, sheet_document_issues, lifecycle RPCs (create/draft/publish/deprecate/delete/fork/archive/restore/delete sheet/register asset), privileges + RLS - - [ ] 4.3 pgTAP 005_anatomical_sheets.sql: schema/privileges, lifecycle allowed path, immutability, fork provenance, deletion preconditions, denied paths (other user, anon, direct writes, official), invalid document refused at publish - - [ ] 4.4 packages/supabase: database.types.ts regenerated (real stack), schema-types test extended (tables, enums list, functions); index.ts row aliases; publishSheetVersion service (domain validation before RPC) + test - - [ ] 4.5 docs: SUPABASE.md layout/tests, CLAUDE.md folder map + conventions + scopes, packages/README, IMPLEMENTATION_PLAN Step 4 adjustment note, CHANGELOG - - [ ] 4.6 verify: pnpm check (typecheck, test:run, lint, build), db:reset + db:test on real stack, fresh verifier + security gate; capitalize BDR/LRN/EVAL + - [x] 4.1 packages/domain: AnatomicalSheetDocumentSchema (strict, localized {fr,en}, views tree, annotations union, finding tree with category kind), validateSheetDocument (integrity issues), assertPublishable, createEmptySheetDocument; fixture horse-slice; tests per rule + id-stability + - [x] 4.2 migration 20261008110000_anatomical_sheets: species (seed equine), enums, sheets/versions/assets, triggers (one draft, published immutable, delete preconditions, species match), helpers can_edit/can_use_sheet, sheet_document_issues, lifecycle RPCs (create/draft/publish/deprecate/delete/fork/archive/restore/delete sheet/register asset), privileges + RLS + - [x] 4.3 pgTAP 005_anatomical_sheets.sql: schema/privileges, lifecycle allowed path, immutability, fork provenance, deletion preconditions, denied paths (other user, anon, direct writes, official), invalid document refused at publish + - [x] 4.4 packages/supabase: database.types.ts regenerated (real stack), schema-types test extended (tables, enums list, functions); index.ts row aliases; publishSheetVersion service (domain validation before RPC) + test + - [x] 4.5 docs: SUPABASE.md layout/tests, CLAUDE.md folder map + conventions + scopes, packages/README, IMPLEMENTATION_PLAN Step 4 adjustment note, CHANGELOG + - [x] 4.6 verify: pnpm check green (61+17+278), db:reset + db:test 210/210 real stack, types in sync; verifier ECARTS(5) + security BLOCK(1) → all fixed (BLK-007 hardening migration, visibility RPC, +32 pgTAP, doc sync); BDR-030..032, LRN-038..040, EVAL-008 - [ ] Step 4b — legacy importer → official equine sheet as DRAFT (document.json + legacy-id-map + IMPORT-REPORT.md for business verification), publication after user validation --- diff --git a/docs/development/ANATOMICAL_SHEET_MODEL.md b/docs/development/ANATOMICAL_SHEET_MODEL.md index 025a881b..53cdcfd7 100644 --- a/docs/development/ANATOMICAL_SHEET_MODEL.md +++ b/docs/development/ANATOMICAL_SHEET_MODEL.md @@ -13,10 +13,10 @@ Out of scope here: the legacy importer and the official equine draft ## 1. Two layers -| Layer | Where | Role | -|---|---|---| -| Canonical document | `packages/domain/src/anatomical-sheet/` (Zod) | The sheet content: views, annotations, finding tree, vertebral regions, translations. Self-describing (`schema_version`). | -| Relational identity | `supabase/migrations/20261008110000_anatomical_sheets.sql` | Who owns the sheet, visibility, versions and their status, provenance of copies, assets, audit. | +| Layer | Where | Role | +| ------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | +| Canonical document | `packages/domain/src/anatomical-sheet/` (Zod) | The sheet content: views, annotations, finding tree, vertebral regions, translations. Self-describing (`schema_version`). | +| Relational identity | `supabase/migrations/20261008110000_anatomical_sheets.sql` | Who owns the sheet, visibility, versions and their status, provenance of copies, assets, audit. | The database stores the document as JSONB in `anatomical_sheet_versions.content`. Zod is the shape contract at the @@ -95,11 +95,11 @@ Why these shapes: ### 2.1 Validation tiers -| Tier | Function | When | -|---|---|---| -| Shape | `AnatomicalSheetDocumentSchema.parse()` | every save (draft included) | -| Integrity | `validateSheetDocument(doc): SheetIssue[]` | editor feedback; `publishable` = no issue with `severity: 'error'` | -| Relational | `publish_sheet_version()` in SQL | publication: species matches the sheet, assets exist, referential rules below | +| Tier | Function | When | +| ---------- | ------------------------------------------ | ----------------------------------------------------------------------------- | +| Shape | `AnatomicalSheetDocumentSchema.parse()` | every save (draft included) | +| Integrity | `validateSheetDocument(doc): SheetIssue[]` | editor feedback; `publishable` = no issue with `severity: 'error'` | +| Relational | `publish_sheet_version()` in SQL | publication: species matches the sheet, assets exist, referential rules below | `SheetIssue = { code, severity: 'error' | 'warning', path, message }`; the path names the offending field (`annotations[0].category_id`), the later @@ -108,23 +108,23 @@ entry for a duplicate, the item itself for `view.unreachable` and Integrity rules (error unless stated): -| Code | Rule | -|---|---| -| `view.main.count` | exactly one `main` view | -| `view.id.duplicate` | view ids unique | -| `view.parent.missing` / `view.parent.cycle` | detail parent exists; the parent chain reaches the main view | -| `view.unreachable` | every detail view is opened by ≥1 `detail_trigger` located in its parent view | -| `view.asset.missing` | the main view has an asset; a detail view without asset has a `view_box` | -| `annotation.id.duplicate` | annotation ids unique across the whole sheet (all views) | -| `annotation.view.missing` | `view_id` exists | -| `annotation.category.missing` | `category_id` exists | -| `annotation.opens_view.invalid` | trigger target exists, is `detail`, and its parent is the trigger's view | -| `annotation.finding_zone.missing` | `finding_zone_id` exists | -| `annotation.region.missing` | `vertebral_region_code` exists in `vertebral_config` | -| `annotation.no_findings` (warning) | point / zone without `finding_zone_id` | -| `region.code.duplicate`, `category.id.duplicate`, `finding_zone.id.duplicate` | uniqueness | -| `finding.id.duplicate` | node ids unique among siblings (per zone, per children array) | -| `finding_zone.unreferenced` (warning) | zone no annotation points to | +| Code | Rule | +| ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | +| `view.main.count` | exactly one `main` view | +| `view.id.duplicate` | view ids unique | +| `view.parent.missing` / `view.parent.cycle` | detail parent exists; the parent chain reaches the main view | +| `view.unreachable` | every detail view is opened by ≥1 `detail_trigger` located in its parent view | +| `view.asset.missing` | the main view has an asset; a detail view without asset has a `view_box` | +| `annotation.id.duplicate` | annotation ids unique across the whole sheet (all views) | +| `annotation.view.missing` | `view_id` exists | +| `annotation.category.missing` | `category_id` exists | +| `annotation.opens_view.invalid` | trigger target exists, is `detail`, and its parent is the trigger's view | +| `annotation.finding_zone.missing` | `finding_zone_id` exists | +| `annotation.region.missing` | `vertebral_region_code` exists in `vertebral_config` | +| `annotation.no_findings` (warning) | point / zone without `finding_zone_id` | +| `region.code.duplicate`, `category.id.duplicate`, `finding_zone.id.duplicate` | uniqueness | +| `finding.id.duplicate` | node ids unique among siblings (per zone, per children array) | +| `finding_zone.unreferenced` (warning) | zone no annotation points to | A draft may be saved with errors. Publishing a document with errors is refused in TypeScript (`assertPublishable`) and in SQL @@ -149,43 +149,46 @@ any authenticated user; no write path through the API (platform step later). ### `anatomical_sheets` -| Column | Notes | -|---|---| -| `id uuid` | | -| `species_id` | FK species | -| `name text`, `slug text`, `description text` | slug `^[a-z0-9][a-z0-9-]{1,79}$`, unique per owner scope among non-deleted sheets | -| `creator_user_id uuid null` | null = platform-owned (official sheets, seeds) | -| `is_official boolean` | only a platform admin can create one; editable by platform admins | -| `visibility` | enum `sheet_visibility`: `private` \| `public` | -| `status` | enum `sheet_status`: `active` \| `archived` \| `deleted` (soft) | -| `based_on_sheet_id`, `based_on_version_id` | provenance of a copy (fork); FK `on delete set null` so the copy survives the source | -| `current_version_id` | latest published version (nullable while draft-only) | -| `archived_at`, `deleted_at`, `created_at`, `updated_at` | | +| Column | Notes | +| ------------------------------------------------------- | ------------------------------------------------------------------------------------ | +| `id uuid` | | +| `species_id` | FK species | +| `name text`, `slug text`, `description text` | slug `^[a-z0-9][a-z0-9-]{1,79}$`, unique per owner scope among non-deleted sheets | +| `creator_user_id uuid null` | null = platform-owned (official sheets, seeds) | +| `is_official boolean` | only a platform admin can create one; editable by platform admins | +| `visibility` | enum `sheet_visibility`: `private` \| `public` | +| `status` | enum `sheet_status`: `active` \| `archived` \| `deleted` (soft) | +| `based_on_sheet_id`, `based_on_version_id` | provenance of a copy (fork); FK `on delete set null` so the copy survives the source | +| `current_version_id` | latest published version (nullable while draft-only) | +| `last_version_number` | monotonic counter: a deleted version's number is never reused | +| `archived_at`, `deleted_at`, `created_at`, `updated_at` | | ### `anatomical_sheet_versions` -| Column | Notes | -|---|---| -| `id uuid`, `sheet_id` | | -| `version_number int` | unique per sheet, assigned by the server (`max + 1`) | -| `status` | enum `sheet_version_status`: `draft` \| `published` \| `deprecated` | -| `document_schema_version int` | CHECK = `content->>'schema_version'`; only `1` today | -| `content jsonb` | the canonical document; CHECK `jsonb_typeof = 'object'` | -| `change_note text` | what changed in this version | -| `created_by`, `published_by`, `deprecated_by` | profile ids, `on delete set null` | -| `published_at`, `deprecated_at`, `created_at`, `updated_at` | | +| Column | Notes | +| ----------------------------------------------------------- | ------------------------------------------------------------------------ | +| `id uuid`, `sheet_id` | | +| `version_number int` | unique per sheet, assigned by the server (`max + 1`) | +| `status` | enum `sheet_version_status`: `draft` \| `published` \| `deprecated` | +| `document_schema_version int` | CHECK = `content->>'schema_version'`; only `1` today | +| `content jsonb` | the canonical document; CHECK `jsonb_typeof = 'object'` and size ≤ 2 MiB | +| `change_note text` | what changed in this version | +| `created_by`, `published_by`, `deprecated_by` | profile ids, `on delete set null` | +| `published_at`, `deprecated_at`, `created_at`, `updated_at` | | Rules enforced by triggers (every role, including the table owner): - **One draft per sheet** (partial unique index, C8). - **Published rows are immutable**: the only accepted UPDATE on a `published` row is the transition to `deprecated` (status, `deprecated_at`, - `deprecated_by`); any other column change raises `42501`. A `deprecated` - row is frozen. + `deprecated_by`); a change to any compared column (content, schema + version, number, sheet, note, authorship, timestamps) raises `42501` for + every role, table owner included. Through the API the row is simply + invisible to UPDATE (zero rows touched). A `deprecated` row is frozen. - **Deletion preconditions** (BEFORE DELETE): never a `published` row; never - the `current_version_id` of its sheet; never a version some sheet is - `based_on`; (reports: added when the table exists, §16). A `draft` has no - dependents and can be dropped by its editor. + the `current_version_id` of its sheet; never a version a non-deleted sheet + is `based_on`; (reports: added when the table exists, §16). A `draft` has + no dependents and is dropped by its editor through `delete_sheet_version`. - **Document ↔ row**: `content->>'species_id'` equals the sheet's species. ### `anatomical_sheet_assets` @@ -196,61 +199,72 @@ Rules enforced by triggers (every role, including the table owner): immutable and **content-addressed**: the bytes live in Storage under `anatomical-sheet-assets/.svg` (bucket and policies arrive with the importer step; until then the path is a convention, not a row). Two sheets -with the same SVG share one object; a copy of a sheet copies the metadata -rows only. Deleting an asset referenced by a version is refused (FK restrict -is not possible on a JSONB reference, so the delete RPC checks every -version's views). +with the same SVG share one object; a copy of a sheet copies only the +metadata rows its copied version references. Deleting an asset referenced by +a version is refused (FK restrict is not possible on a JSONB reference, so +`delete_sheet_asset` checks every version's views). Asset rows follow the +sheet's visibility, drafts included: the future Storage policy must +authorise through the sheet, never through a sha256 alone. ### 3.1 Lifecycle (RPCs, security definer, audited) -| RPC | Actor | Effect | -|---|---|---| -| `create_anatomical_sheet(species_id, name, slug, description, visibility, official, document)` | any active user; `official = true` needs platform admin | sheet + draft v1 | -| `create_sheet_draft(sheet_id, from_version_id, change_note)` | editor | new draft `max + 1`, content copied from `from_version_id` (default: current version); refused if a draft exists | -| `publish_sheet_version(version_id)` | editor | draft → published; relational checks; sheet `current_version_id` ← version. Previous published versions stay `published` (historical reports keep rendering) | -| `deprecate_sheet_version(version_id, reason)` | editor | published → deprecated (not offered for new reports; still readable) | -| `delete_sheet_version(version_id)` | editor | physical delete, trigger preconditions | -| `fork_anatomical_sheet(source_version_id, name, slug, visibility)` | any user who can use the source | new sheet (`based_on_*` set, `creator = actor`), asset rows copied, draft v1 = source content with `svg_asset_id`s remapped. The source rows are not touched | -| `archive_anatomical_sheet(sheet_id)` / `restore_anatomical_sheet` | editor | status archived ↔ active; archived sheets are hidden from "use" but readable by their editor | -| `delete_anatomical_sheet(sheet_id)` | editor | soft delete; refused while any version has dependents | -| `register_sheet_asset(sheet_id, sha256, byte_size, file_name)` | editor | asset row (idempotent on `(sheet, sha256)`) | +| RPC | Actor | Effect | +| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `create_anatomical_sheet(species_id, name, slug, document, description, visibility, official)` | any active account; `official = true` needs platform admin | sheet + draft v1 | +| `create_sheet_draft(sheet_id, from_version_id, change_note)` | editor | new draft `max + 1`, content copied from `from_version_id` (default: current version); refused if a draft exists | +| `publish_sheet_version(version_id)` | editor | draft → published; relational checks; sheet `current_version_id` ← version. Previous published versions stay `published` (historical reports keep rendering) | +| `deprecate_sheet_version(version_id, reason)` | editor | published → deprecated (not offered for new reports; still readable) | +| `delete_sheet_version(version_id)` | editor | physical delete, trigger preconditions | +| `fork_anatomical_sheet(source_version_id, name, slug, visibility)` | any user who can use the source | new sheet (`based_on_*` set, `creator = actor`), asset rows copied, draft v1 = source content with `svg_asset_id`s remapped. The source rows are not touched | +| `archive_anatomical_sheet(sheet_id)` / `restore_anatomical_sheet` | editor | status archived ↔ active; archived sheets are hidden from "use" but readable by their editor | +| `delete_anatomical_sheet(sheet_id)` | editor | soft delete; refused while a non-deleted copy derives from the sheet | +| `set_sheet_visibility(sheet_id, visibility)` | editor | private ↔ public, audited (sharing is sensitive state) | +| `register_sheet_asset(sheet_id, sha256, byte_size, file_name)` | editor | asset row (idempotent on `(sheet, sha256)`) | +| `delete_sheet_asset(asset_id)` | editor | refused while any version references the asset | Direct table access for `authenticated`: SELECT through the policies below; -UPDATE of `content` / `change_note` on **own draft** rows (the future editor -autosaves with a PATCH); DELETE of own draft rows. Everything else is RPC. +UPDATE of `name` / `slug` / `description` on own sheets and of `content` / +`change_note` on **own draft** rows (the future editor autosaves with a +PATCH; the autosave itself is not audited, the publication is). Everything +else is RPC. Every RPC takes its actor from `auth.uid()`, refuses a +deactivated profile, checks `can_edit_sheet` before reading anything else +(unknown and foreign ids get the same `42501`), and calls +`private.log_event`. ### 3.2 Access helpers (`private`, security definer) -| Helper | True when | -|---|---| -| `can_edit_sheet(uid, sheet_id)` | sheet not deleted and (creator = uid, or `is_official` and platform admin) | -| `can_use_sheet(uid, sheet_id)` | sheet `active` and (`public`, or `can_edit_sheet`) — grants and follows plug in here at the community step | +| Helper | True when | +| ------------------------------- | --------------------------------------------------------------------------------------------------------- | +| `can_edit_sheet(uid, sheet_id)` | sheet not deleted and (creator = uid, or `is_official` and platform admin) | +| `can_use_sheet(uid, sheet_id)` | sheet `active` and (`public`, or `can_edit_sheet`), grants and follows plug in here at the community step | Policies: -| Table | SELECT | INSERT / UPDATE / DELETE | -|---|---|---| -| `species` | authenticated, `active` rows | none | -| `anatomical_sheets` | `can_use_sheet` or `can_edit_sheet` | none (RPC) | -| `anatomical_sheet_versions` | published / deprecated of usable sheets; drafts for editors | UPDATE `content`, `change_note` and DELETE on own drafts; INSERT via RPC | -| `anatomical_sheet_assets` | same visibility as the sheet | none (RPC) | +| Table | SELECT | INSERT / UPDATE / DELETE | +| --------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------ | +| `species` | authenticated, `active` rows | none | +| `anatomical_sheets` | `can_use_sheet` or `can_edit_sheet` | UPDATE `name`, `slug`, `description` for editors; everything else RPC | +| `anatomical_sheet_versions` | published / deprecated of usable sheets; drafts for editors | UPDATE `content`, `change_note` on own drafts; INSERT and DELETE via RPC | +| `anatomical_sheet_assets` | same visibility as the sheet | none (RPC) | -`anon` gets nothing. Public discovery views for the public site come with -the community step (§17.4). +`anon` gets nothing. Every `private` function has EXECUTE revoked from +PUBLIC; only the two predicates above are granted to `authenticated` +(pgTAP 001 keeps a census). Public discovery views for the public site come +with the community step (§17.4). ## 4. What the model guarantees (acceptance criteria) -| Criterion | Where it is proven | -|---|---| +| Criterion | Where it is proven | +| ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | | A sheet with several views and annotations explicitly linked to findings | `packages/domain/tests/fixtures/horse-slice.ts` (2 views, trigger, spine region, bilateral joint, 3 finding kinds); schema + integrity tests | -| Ids stable under translation | test: renaming every label leaves ids, references and `validateSheetDocument` output unchanged | -| Published versions immutable | pgTAP: UPDATE of content / status / number on a published row → `42501`, for the editor, for a platform admin and for the owner role | -| New version leaves old ones intact | pgTAP: v2 draft then publish; v1 row byte-identical, `current_version_id` moves | -| Copies keep provenance, source untouched | pgTAP: fork → `based_on_*` set, source rows and assets unchanged; editing the copy leaves the source unchanged | -| Validation detects inconsistencies | domain tests, one per rule (missing references, duplicate ids, invalid relations) + SQL `sheet_document_issues` | -| Security rules tested | pgTAP allowed + denied paths: other user, anon, direct writes, official sheets, archived/deleted sheets | -| Migrations reproducible | PGlite replays from zero in `pnpm test:run`; `pnpm db:reset` on the real stack | -| Previous tests pass | root `pnpm check` | +| Ids stable under translation | test: renaming every label leaves ids, references and `validateSheetDocument` output unchanged | +| Published versions immutable | pgTAP: UPDATE of content / status / number on a published row → `42501` for the table owner; zero rows touched through the API role | +| New version leaves old ones intact | pgTAP: v2 draft then publish; v1 row byte-identical, `current_version_id` moves | +| Copies keep provenance, source untouched | pgTAP: fork → `based_on_*` set, source rows and assets unchanged; editing the copy leaves the source unchanged | +| Validation detects inconsistencies | domain tests, one per rule (missing references, duplicate ids, invalid relations) + SQL `sheet_document_issues` | +| Security rules tested | pgTAP allowed + denied paths: other user, anon, direct writes, official sheets, archived/deleted sheets | +| Migrations reproducible | PGlite replays from zero in `pnpm test:run`; `pnpm db:reset` on the real stack | +| Previous tests pass | root `pnpm check` | ## 5. Decisions left to the user @@ -268,3 +282,12 @@ the community step (§17.4). account? 6. **Finding category kind naming**: `observation` collides with the report "Observation" (OPEN_QUESTIONS C7). Alternative: `consultation_reason`. +7. **Server-side shape validation**: SQL re-checks references, sizes and the + species, not the full Zod shape (ids pattern, enums, unknown keys). A + client calling the RPC directly can publish a shape-invalid document to + its own sheet. Options: a plpgsql shape check, or publication through an + Edge Function running the Zod schema (community step at the latest). +8. **Account erasure**: `creator_user_id` is `on delete restrict` and the + immutability guard blocks `set null` on `published_by` of published rows, + so deleting an `auth.users` row that owns sheets fails by design until the + retention step (§16) defines reassignment or anonymisation. diff --git a/packages/domain/src/anatomical-sheet/schema.ts b/packages/domain/src/anatomical-sheet/schema.ts index 7bdaaf70..19c304ad 100644 --- a/packages/domain/src/anatomical-sheet/schema.ts +++ b/packages/domain/src/anatomical-sheet/schema.ts @@ -159,11 +159,17 @@ export const AnnotationSchema = z.discriminatedUnion('kind', [ DetailTriggerAnnotationSchema, ]) +/** Documents are shared across users: only web links, never javascript: URLs. */ +const HttpUrlSchema = z + .string() + .url() + .refine((url) => /^https?:\/\//i.test(url), 'http(s) URL expected') + export const SourceRefSchema = z .object({ type: z.enum(['manual', 'journal', 'database', 'web']), citation: z.string().min(1), - url: z.string().url().optional(), + url: HttpUrlSchema.optional(), }) .strict() diff --git a/packages/domain/tests/anatomical-sheet.schema.test.ts b/packages/domain/tests/anatomical-sheet.schema.test.ts index 3f7746ba..0e7cfd1a 100644 --- a/packages/domain/tests/anatomical-sheet.schema.test.ts +++ b/packages/domain/tests/anatomical-sheet.schema.test.ts @@ -6,14 +6,25 @@ import { } from '../src' import { horseSlice, horseSliceInput } from './fixtures/horse-slice' -// Mutations deliberately break the typed shape, so the draft is untyped. -// eslint-disable-next-line @typescript-eslint/no-explicit-any -type LooseDoc = any -type Mutation = (doc: LooseDoc) => void +type Tree = Record +type Mutation = (doc: Tree) => void + +/** Walks `path` inside a JSON tree; mutations break the typed shape on purpose. */ +function at(doc: Tree, path: (string | number)[]): Tree { + return path.reduce((node, key) => node[key] as Tree, doc) +} + +function set(doc: Tree, path: (string | number)[], value: unknown): void { + at(doc, path.slice(0, -1))[String(path.at(-1))] = value +} + +function unset(doc: Tree, path: (string | number)[]): void { + delete at(doc, path.slice(0, -1))[String(path.at(-1))] +} /** Applies a mutation to the lean fixture and reports whether it parses. */ function parsesAfter(mutate: Mutation): boolean { - const doc: LooseDoc = horseSliceInput() + const doc = horseSliceInput() as unknown as Tree mutate(doc) return AnatomicalSheetDocumentSchema.safeParse(doc).success } @@ -31,35 +42,70 @@ describe('AnatomicalSheetDocumentSchema', () => { }) const rejections: Array<[string, Mutation]> = [ - ['an unknown top-level key', (d) => (d.extra = true)], - ['an unknown nested key', (d) => (d.views[0].zoom = 2)], - ['a stable id with spaces', (d) => (d.annotations[0].id = 'Hip Joint')], - ['a stable id with an accent', (d) => (d.categories[0].id = 'É')], - ['an empty stable id', (d) => (d.finding_zones[0].id = '')], - ['schema_version 2', (d) => (d.schema_version = 2)], - ['a non-uuid svg_asset_id', (d) => (d.views[0].svg_asset_id = 'horse')], + ['an unknown top-level key', (d) => set(d, ['extra'], true)], + ['an unknown nested key', (d) => set(d, ['views', 0, 'zoom'], 2)], + [ + 'a stable id with spaces', + (d) => set(d, ['annotations', 0, 'id'], 'Hip Joint'), + ], + ['a stable id with an accent', (d) => set(d, ['categories', 0, 'id'], 'É')], + ['an empty stable id', (d) => set(d, ['finding_zones', 0, 'id'], '')], + ['schema_version 2', (d) => set(d, ['schema_version'], 2)], + [ + 'a non-uuid svg_asset_id', + (d) => set(d, ['views', 0, 'svg_asset_id'], 'horse'), + ], [ 'a polygon with 2 points', (d) => - (d.annotations[1].geometry.points = [ - [0, 0], - [1, 1], - ]), + set( + d, + ['annotations', 1, 'geometry', 'points'], + [ + [0, 0], + [1, 1], + ], + ), ], - ['a circle with r 0', (d) => (d.annotations[0].geometry.r = 0)], - ['a region count of 0', (d) => (d.vertebral_config.regions[0].count = 0)], - ['a missing en label', (d) => delete d.name.en], + [ + 'a circle with r 0', + (d) => set(d, ['annotations', 0, 'geometry', 'r'], 0), + ], + [ + 'a region count of 0', + (d) => set(d, ['vertebral_config', 'regions', 0, 'count'], 0), + ], + ['a missing en label', (d) => unset(d, ['name', 'en'])], [ 'a detail view without parent_view_id', - (d) => delete d.views[1].parent_view_id, + (d) => unset(d, ['views', 1, 'parent_view_id']), ], [ 'a detail_trigger with finding_zone_id', - (d) => (d.annotations[3].finding_zone_id = 'hip'), + (d) => set(d, ['annotations', 3, 'finding_zone_id'], 'hip'), + ], + [ + 'a javascript: source url', + (d) => + set( + d, + [ + 'finding_zones', + 0, + 'categories', + 2, + 'children', + 0, + 'sources', + 0, + 'url', + ], + 'javascript:alert(1)', + ), ], [ 'a finding category kind foo', - (d) => (d.finding_zones[0].categories[0].kind = 'foo'), + (d) => set(d, ['finding_zones', 0, 'categories', 0, 'kind'], 'foo'), ], ] diff --git a/packages/supabase/src/database.types.ts b/packages/supabase/src/database.types.ts index 23461cc7..e6b1e77a 100644 --- a/packages/supabase/src/database.types.ts +++ b/packages/supabase/src/database.types.ts @@ -151,6 +151,7 @@ export type Database = { description: string id: string is_official: boolean + last_version_number: number name: string slug: string species_id: string @@ -170,6 +171,7 @@ export type Database = { description?: string id?: string is_official?: boolean + last_version_number?: number name: string slug: string species_id: string @@ -188,6 +190,7 @@ export type Database = { description?: string id?: string is_official?: boolean + last_version_number?: number name?: string slug?: string species_id?: string @@ -428,6 +431,13 @@ export type Database = { } Returns: string } + set_sheet_visibility: { + Args: { + sheet_id: string + visibility: Database['public']['Enums']['sheet_visibility'] + } + Returns: string + } } Enums: { platform_role: 'owner' | 'admin' | 'moderator' | 'support' diff --git a/packages/supabase/tests/db/schema-types.test.ts b/packages/supabase/tests/db/schema-types.test.ts index aff66993..815c1326 100644 --- a/packages/supabase/tests/db/schema-types.test.ts +++ b/packages/supabase/tests/db/schema-types.test.ts @@ -57,6 +57,7 @@ const expectedColumns = { 'description', 'id', 'is_official', + 'last_version_number', 'name', 'slug', 'species_id', @@ -125,6 +126,7 @@ const expectedFunctionArgs = { register_sheet_asset: ['byte_size', 'file_name', 'sha256', 'sheet_id'], restore_anatomical_sheet: ['sheet_id'], revoke_platform_role: ['reason', 'role', 'target_user_id'], + set_sheet_visibility: ['sheet_id', 'visibility'], } as const satisfies FunctionArgs type MissingArgs = { diff --git a/supabase/migrations/20261008110000_anatomical_sheets.sql b/supabase/migrations/20261008110000_anatomical_sheets.sql index 88ca7948..f4dcdae5 100644 --- a/supabase/migrations/20261008110000_anatomical_sheets.sql +++ b/supabase/migrations/20261008110000_anatomical_sheets.sql @@ -59,6 +59,9 @@ create table public.anatomical_sheets ( based_on_sheet_id uuid references public.anatomical_sheets (id) on delete set null, based_on_version_id uuid, current_version_id uuid, + -- Monotonic counter: a deleted version's number is never reused. + last_version_number integer not null default 0 + constraint anatomical_sheets_last_version_nonneg check (last_version_number >= 0), archived_at timestamptz, deleted_at timestamptz, created_at timestamptz not null default now(), @@ -100,7 +103,9 @@ create table public.anatomical_sheet_versions ( document_schema_version integer not null constraint anatomical_sheet_versions_schema_known check (document_schema_version = 1), content jsonb not null - constraint anatomical_sheet_versions_content_object check (jsonb_typeof(content) = 'object'), + constraint anatomical_sheet_versions_content_object check (jsonb_typeof(content) = 'object') + -- Hostile or runaway documents stop here (2 MiB; the horse catalog is ~170 KiB). + constraint anatomical_sheet_versions_content_size check (pg_column_size(content) <= 2097152), change_note text not null default '' constraint anatomical_sheet_versions_change_note_length check (char_length(change_note) <= 1000), created_by uuid references public.profiles (id) on delete set null, @@ -149,7 +154,7 @@ create table public.anatomical_sheet_assets ( sha256 text not null constraint anatomical_sheet_assets_sha256_format check (sha256 ~ '^[0-9a-f]{64}$'), byte_size integer not null - constraint anatomical_sheet_assets_byte_size_positive check (byte_size > 0), + constraint anatomical_sheet_assets_byte_size_range check (byte_size between 1 and 20971520), content_type text not null default 'image/svg+xml' constraint anatomical_sheet_assets_content_type check (content_type in ('image/svg+xml')), file_name text not null @@ -172,6 +177,7 @@ create index anatomical_sheet_assets_sheet_idx on public.anatomical_sheet_assets create or replace function private.check_sheet_version_document() returns trigger language plpgsql +security definer set search_path = '' as $$ declare @@ -202,8 +208,8 @@ as $$ declare v_same_core boolean; begin - if new.sheet_id <> old.sheet_id or new.version_number <> old.version_number then - raise exception 'sheet_id and version_number are immutable' using errcode = '42501'; + if new.id <> old.id or new.sheet_id <> old.sheet_id or new.version_number <> old.version_number then + raise exception 'id, sheet_id and version_number are immutable' using errcode = '42501'; end if; if old.status = 'deprecated' then @@ -260,6 +266,7 @@ $$; create or replace function private.guard_sheet_version_delete() returns trigger language plpgsql +security definer set search_path = '' as $$ declare @@ -295,7 +302,44 @@ as $$ select case when p_issues @> array[p_code] then p_issues else p_issues || p_code end; $$; -create or replace function private.sheet_document_issues(p_doc jsonb) +-- Uniqueness of the id-bearing collections. +create or replace function private.sheet_document_duplicate_issues(p_doc jsonb) +returns text[] +language plpgsql +immutable +set search_path = '' +as $$ +declare + v_issues text[] := '{}'; + r record; +begin + for r in + select * from (values + ('views', 'id', 'view.id.duplicate'), + ('annotations', 'id', 'annotation.id.duplicate'), + ('categories', 'id', 'category.id.duplicate'), + ('finding_zones', 'id', 'finding_zone.id.duplicate') + ) as t(collection, key, code) + loop + if exists ( + select 1 from jsonb_array_elements(coalesce(p_doc -> r.collection, '[]'::jsonb)) e + group by e ->> r.key having count(*) > 1 + ) then + v_issues := private.append_issue(v_issues, r.code); + end if; + end loop; + if exists ( + select 1 from jsonb_array_elements(coalesce(p_doc -> 'vertebral_config' -> 'regions', '[]'::jsonb)) g + group by g ->> 'code' having count(*) > 1 + ) then + v_issues := private.append_issue(v_issues, 'region.code.duplicate'); + end if; + return v_issues; +end; +$$; + +-- View tree: one main view, parents exist, details reachable, something to draw. +create or replace function private.sheet_document_view_issues(p_doc jsonb) returns text[] language plpgsql immutable @@ -305,39 +349,14 @@ declare v_issues text[] := '{}'; v_views jsonb := coalesce(p_doc -> 'views', '[]'::jsonb); v_anns jsonb := coalesce(p_doc -> 'annotations', '[]'::jsonb); - v_cats jsonb := coalesce(p_doc -> 'categories', '[]'::jsonb); - v_zones jsonb := coalesce(p_doc -> 'finding_zones', '[]'::jsonb); - v_regs jsonb := coalesce(p_doc -> 'vertebral_config' -> 'regions', '[]'::jsonb); r record; begin - if jsonb_typeof(v_views) <> 'array' or jsonb_typeof(v_anns) <> 'array' - or jsonb_typeof(v_cats) <> 'array' or jsonb_typeof(v_zones) <> 'array' - or jsonb_typeof(v_regs) <> 'array' then - return array['document.shape']; - end if; - if (select count(*) from jsonb_array_elements(v_views) v where v ->> 'kind' = 'main') <> 1 then v_issues := private.append_issue(v_issues, 'view.main.count'); end if; - if exists (select 1 from jsonb_array_elements(v_views) v group by v ->> 'id' having count(*) > 1) then - v_issues := private.append_issue(v_issues, 'view.id.duplicate'); - end if; - if exists (select 1 from jsonb_array_elements(v_anns) a group by a ->> 'id' having count(*) > 1) then - v_issues := private.append_issue(v_issues, 'annotation.id.duplicate'); - end if; - if exists (select 1 from jsonb_array_elements(v_cats) c group by c ->> 'id' having count(*) > 1) then - v_issues := private.append_issue(v_issues, 'category.id.duplicate'); - end if; - if exists (select 1 from jsonb_array_elements(v_zones) z group by z ->> 'id' having count(*) > 1) then - v_issues := private.append_issue(v_issues, 'finding_zone.id.duplicate'); - end if; - if exists (select 1 from jsonb_array_elements(v_regs) g group by g ->> 'code' having count(*) > 1) then - v_issues := private.append_issue(v_issues, 'region.code.duplicate'); - end if; - for r in select v ->> 'id' as id, v ->> 'kind' as kind, v ->> 'parent_view_id' as parent, - v ->> 'svg_asset_id' as asset, v -> 'view_box' as view_box + v ->> 'svg_asset_id' as asset, jsonb_typeof(v -> 'view_box') as view_box_type from jsonb_array_elements(v_views) v loop if r.kind = 'detail' then @@ -350,19 +369,37 @@ begin ) then v_issues := private.append_issue(v_issues, 'view.unreachable'); end if; - if r.asset is null and (r.view_box is null or jsonb_typeof(r.view_box) = 'null') then + if r.asset is null and coalesce(r.view_box_type, 'null') = 'null' then v_issues := private.append_issue(v_issues, 'view.asset.missing'); end if; elsif r.asset is null then v_issues := private.append_issue(v_issues, 'view.asset.missing'); end if; end loop; + return v_issues; +end; +$$; +-- Annotation references: view, category, trigger target, finding zone, region. +create or replace function private.sheet_document_annotation_issues(p_doc jsonb) +returns text[] +language plpgsql +immutable +set search_path = '' +as $$ +declare + v_issues text[] := '{}'; + v_views jsonb := coalesce(p_doc -> 'views', '[]'::jsonb); + v_cats jsonb := coalesce(p_doc -> 'categories', '[]'::jsonb); + v_zones jsonb := coalesce(p_doc -> 'finding_zones', '[]'::jsonb); + v_regs jsonb := coalesce(p_doc -> 'vertebral_config' -> 'regions', '[]'::jsonb); + r record; +begin for r in select a ->> 'kind' as kind, a ->> 'view_id' as view_id, a ->> 'category_id' as category_id, a ->> 'opens_view_id' as opens, a ->> 'finding_zone_id' as zone, a ->> 'vertebral_region_code' as region - from jsonb_array_elements(v_anns) a + from jsonb_array_elements(coalesce(p_doc -> 'annotations', '[]'::jsonb)) a loop if not exists (select 1 from jsonb_array_elements(v_views) v where v ->> 'id' = r.view_id) then v_issues := private.append_issue(v_issues, 'annotation.view.missing'); @@ -387,14 +424,54 @@ begin v_issues := private.append_issue(v_issues, 'annotation.region.missing'); end if; end loop; - return v_issues; end; $$; +-- True when every id-bearing collection of the document is a JSON array. +create or replace function private.sheet_document_has_shape(p_doc jsonb) +returns boolean +language sql +immutable +set search_path = '' +as $$ + select jsonb_typeof(p_doc) = 'object' + and jsonb_typeof(coalesce(p_doc -> 'views', '[]'::jsonb)) = 'array' + and jsonb_typeof(coalesce(p_doc -> 'annotations', '[]'::jsonb)) = 'array' + and jsonb_typeof(coalesce(p_doc -> 'categories', '[]'::jsonb)) = 'array' + and jsonb_typeof(coalesce(p_doc -> 'finding_zones', '[]'::jsonb)) = 'array' + and jsonb_typeof(coalesce(p_doc -> 'vertebral_config' -> 'regions', '[]'::jsonb)) = 'array'; +$$; + +create or replace function private.sheet_document_issues(p_doc jsonb) +returns text[] +language sql +immutable +set search_path = '' +as $$ + select case + when not private.sheet_document_has_shape(p_doc) then array['document.shape'] + else private.sheet_document_view_issues(p_doc) + || private.sheet_document_duplicate_issues(p_doc) + || private.sheet_document_annotation_issues(p_doc) + end; +$$; + comment on function private.sheet_document_issues(jsonb) is 'Error-level referential rules of the canonical document (codes shared with packages/domain). Empty array = publishable as far as SQL can tell.'; +-- Asset ids referenced by the views of a document (lower-cased uuid text). +create or replace function private.sheet_document_asset_ids(p_doc jsonb) +returns text[] +language sql +immutable +set search_path = '' +as $$ + select coalesce(array_agg(distinct lower(v ->> 'svg_asset_id')), '{}') + from jsonb_array_elements(coalesce(p_doc -> 'views', '[]'::jsonb)) v + where v ->> 'svg_asset_id' is not null; +$$; + -- Every svg_asset_id used by a view must be an asset registered for the sheet. create or replace function private.sheet_document_unknown_assets(p_sheet_id uuid, p_doc jsonb) returns text[] @@ -403,13 +480,12 @@ stable security definer set search_path = '' as $$ - select coalesce(array_agg(v ->> 'svg_asset_id'), '{}') - from jsonb_array_elements(coalesce(p_doc -> 'views', '[]'::jsonb)) v - where v ->> 'svg_asset_id' is not null - and not exists ( - select 1 from public.anatomical_sheet_assets a - where a.sheet_id = p_sheet_id and a.id::text = v ->> 'svg_asset_id' - ); + select coalesce(array_agg(ref), '{}') + from unnest(private.sheet_document_asset_ids(p_doc)) as ref + where not exists ( + select 1 from public.anatomical_sheet_assets a + where a.sheet_id = p_sheet_id and a.id::text = ref + ); $$; -- --------------------------------------------------------------------------- @@ -470,6 +546,10 @@ begin if v_actor is null then raise exception 'authentication required' using errcode = '42501'; end if; + -- A staff-deactivated account keeps no write access (profiles.active). + if not exists (select 1 from public.profiles p where p.id = v_actor and p.active) then + raise exception 'account is not active' using errcode = '42501'; + end if; return v_actor; end; $$; @@ -487,6 +567,24 @@ begin end; $$; +-- Same check through a version id; unknown and foreign versions get one answer. +create or replace function private.require_version_editor(p_actor uuid, p_version_id uuid) +returns void +language plpgsql +stable +security definer +set search_path = '' +as $$ +declare + v_sheet uuid; +begin + select sheet_id into v_sheet from public.anatomical_sheet_versions where id = p_version_id; + if v_sheet is null or not private.can_edit_sheet(p_actor, v_sheet) then + raise exception 'version % is not editable by the caller', p_version_id using errcode = '42501'; + end if; +end; +$$; + -- Inserts a draft with the next version number. The sheet row is locked so -- two concurrent calls cannot pick the same number. create or replace function private.insert_sheet_draft( @@ -504,6 +602,9 @@ declare v_number integer; v_id uuid; begin + if jsonb_typeof(p_content -> 'schema_version') is distinct from 'number' then + raise exception 'document.schema_version must be a number' using errcode = '23514'; + end if; perform 1 from public.anatomical_sheets where id = p_sheet_id for update; if exists ( select 1 from public.anatomical_sheet_versions @@ -511,8 +612,10 @@ begin ) then raise exception 'sheet % already has a draft', p_sheet_id using errcode = '23505'; end if; - select coalesce(max(version_number), 0) + 1 into v_number - from public.anatomical_sheet_versions where sheet_id = p_sheet_id; + update public.anatomical_sheets + set last_version_number = last_version_number + 1 + where id = p_sheet_id + returning last_version_number into v_number; insert into public.anatomical_sheet_versions ( sheet_id, version_number, status, document_schema_version, content, change_note, created_by @@ -531,8 +634,8 @@ begin end; $$; --- Copies the asset rows of one sheet to another; returns old id → new id. -create or replace function private.copy_sheet_assets(p_actor uuid, p_from uuid, p_to uuid) +-- Copies the asset rows a document references to another sheet; returns old id → new id. +create or replace function private.copy_sheet_assets(p_actor uuid, p_from uuid, p_to uuid, p_doc jsonb) returns jsonb language plpgsql security definer @@ -545,7 +648,8 @@ declare begin for r in select id, sha256, byte_size, content_type, file_name - from public.anatomical_sheet_assets where sheet_id = p_from + from public.anatomical_sheet_assets + where sheet_id = p_from and id::text = any (private.sheet_document_asset_ids(p_doc)) loop insert into public.anatomical_sheet_assets ( sheet_id, sha256, byte_size, content_type, file_name, created_by @@ -571,8 +675,8 @@ as $$ coalesce(( select jsonb_agg( case - when v ->> 'svg_asset_id' is not null and p_map ? (v ->> 'svg_asset_id') - then jsonb_set(v, '{svg_asset_id}', to_jsonb(p_map ->> (v ->> 'svg_asset_id'))) + when v ->> 'svg_asset_id' is not null and p_map ? lower(v ->> 'svg_asset_id') + then jsonb_set(v, '{svg_asset_id}', to_jsonb(p_map ->> lower(v ->> 'svg_asset_id'))) else v end order by ord @@ -668,11 +772,8 @@ declare v_version public.anatomical_sheet_versions%rowtype; v_issues text[]; begin + perform private.require_version_editor(v_actor, version_id); select * into v_version from public.anatomical_sheet_versions where id = version_id for update; - if v_version.id is null then - raise exception 'unknown version %', version_id using errcode = 'P0002'; - end if; - perform private.require_sheet_editor(v_actor, v_version.sheet_id); if v_version.status <> 'draft' then raise exception 'version % is not a draft', version_id using errcode = '55000'; end if; @@ -714,11 +815,11 @@ declare v_version public.anatomical_sheet_versions%rowtype; v_next uuid; begin - select * into v_version from public.anatomical_sheet_versions where id = version_id for update; - if v_version.id is null then - raise exception 'unknown version %', version_id using errcode = 'P0002'; + if char_length(reason) > 500 then + raise exception 'reason exceeds 500 characters' using errcode = '22023'; end if; - perform private.require_sheet_editor(v_actor, v_version.sheet_id); + perform private.require_version_editor(v_actor, version_id); + select * into v_version from public.anatomical_sheet_versions where id = version_id for update; if v_version.status <> 'published' then raise exception 'version % is not published', version_id using errcode = '55000'; end if; @@ -754,12 +855,9 @@ declare v_sheet uuid; v_number integer; begin + perform private.require_version_editor(v_actor, version_id); select sheet_id, version_number into v_sheet, v_number from public.anatomical_sheet_versions where id = version_id; - if v_sheet is null then - raise exception 'unknown version %', version_id using errcode = 'P0002'; - end if; - perform private.require_sheet_editor(v_actor, v_sheet); -- Preconditions (published, current, active fork) are raised by the delete guard. delete from public.anatomical_sheet_versions where id = version_id; @@ -791,14 +889,10 @@ declare v_map jsonb; begin select * into v_source from public.anatomical_sheet_versions where id = source_version_id; - if v_source.id is null then - raise exception 'unknown version %', source_version_id using errcode = 'P0002'; - end if; - if not private.can_use_sheet(v_actor, v_source.sheet_id) then - raise exception 'sheet % is not usable by the caller', v_source.sheet_id using errcode = '42501'; - end if; - if v_source.status <> 'published' then - raise exception 'only a published version can be copied' using errcode = '55000'; + -- One answer for "unknown", "not published" and "not usable": no existence oracle. + if v_source.id is null or v_source.status <> 'published' + or not private.can_use_sheet(v_actor, v_source.sheet_id) then + raise exception 'version % is not available for copy', source_version_id using errcode = '42501'; end if; select species_id into v_species from public.anatomical_sheets where id = v_source.sheet_id; @@ -808,7 +902,7 @@ begin values (v_species, name, slug, v_actor, visibility, v_source.sheet_id, source_version_id) returning id into v_sheet; - v_map := private.copy_sheet_assets(v_actor, v_source.sheet_id, v_sheet); + v_map := private.copy_sheet_assets(v_actor, v_source.sheet_id, v_sheet, v_source.content); perform private.log_event( v_actor, 'anatomical_sheet.forked', 'anatomical_sheet', v_sheet, null, null, jsonb_build_object('source_sheet_id', v_source.sheet_id, 'source_version_id', source_version_id) @@ -886,6 +980,8 @@ declare v_status public.sheet_status; begin perform private.require_sheet_editor(v_actor, sheet_id); + -- Lock before the copies check so a concurrent fork cannot slip in. + perform 1 from public.anatomical_sheets s where s.id = sheet_id for update; if exists ( select 1 from public.anatomical_sheets f where f.based_on_sheet_id = delete_anatomical_sheet.sheet_id and f.status <> 'deleted' @@ -898,6 +994,30 @@ begin end; $$; +-- Sharing is sensitive state: audited, never a direct column write. +create or replace function public.set_sheet_visibility(sheet_id uuid, visibility public.sheet_visibility) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_actor(); +begin + perform private.require_sheet_editor(v_actor, sheet_id); + update public.anatomical_sheets s + set visibility = set_sheet_visibility.visibility + where s.id = sheet_id and s.visibility <> set_sheet_visibility.visibility; + if found then + perform private.log_event( + v_actor, 'anatomical_sheet.visibility_changed', 'anatomical_sheet', sheet_id, null, null, + jsonb_build_object('visibility', visibility) + ); + end if; + return sheet_id; +end; +$$; + create or replace function public.register_sheet_asset( sheet_id uuid, sha256 text, @@ -943,14 +1063,12 @@ declare v_sheet uuid; begin select sheet_id into v_sheet from public.anatomical_sheet_assets where id = asset_id; - if v_sheet is null then - raise exception 'unknown asset %', asset_id using errcode = 'P0002'; + if v_sheet is null or not private.can_edit_sheet(v_actor, v_sheet) then + raise exception 'asset % is not editable by the caller', asset_id using errcode = '42501'; end if; - perform private.require_sheet_editor(v_actor, v_sheet); if exists ( - select 1 from public.anatomical_sheet_versions v, - jsonb_array_elements(coalesce(v.content -> 'views', '[]'::jsonb)) w - where v.sheet_id = v_sheet and w ->> 'svg_asset_id' = asset_id::text + select 1 from public.anatomical_sheet_versions v + where v.sheet_id = v_sheet and asset_id::text = any (private.sheet_document_asset_ids(v.content)) ) then raise exception 'asset % is referenced by a version', asset_id using errcode = '55000'; end if; @@ -978,10 +1096,38 @@ comment on function public.fork_anatomical_sheet(uuid, text, text, public.sheet_ 'Personal copy of a published version: new sheet with based_on_* provenance, assets copied, draft v1. The source is not modified.'; comment on function public.delete_anatomical_sheet(uuid) is 'Soft delete (status deleted); refused while active copies derive from the sheet.'; +comment on function public.set_sheet_visibility(uuid, public.sheet_visibility) is + 'private ↔ public. Audited; the only way to change sharing.'; -- --------------------------------------------------------------------------- -- Privileges + RLS -- --------------------------------------------------------------------------- +-- PostgreSQL grants EXECUTE to PUBLIC on every new function and a per-schema +-- ALTER DEFAULT PRIVILEGES cannot take that built-in default away: revoke it +-- explicitly on every private function (the policies need only the two +-- predicates granted above). +revoke all on function private.check_sheet_version_document() from public; +revoke all on function private.guard_sheet_version_update() from public; +revoke all on function private.guard_sheet_version_delete() from public; +revoke all on function private.sheet_version_dependents(uuid) from public; +revoke all on function private.append_issue(text[], text) from public; +revoke all on function private.sheet_document_duplicate_issues(jsonb) from public; +revoke all on function private.sheet_document_view_issues(jsonb) from public; +revoke all on function private.sheet_document_annotation_issues(jsonb) from public; +revoke all on function private.sheet_document_has_shape(jsonb) from public; +revoke all on function private.sheet_document_issues(jsonb) from public; +revoke all on function private.sheet_document_asset_ids(jsonb) from public; +revoke all on function private.sheet_document_unknown_assets(uuid, jsonb) from public; +revoke all on function private.can_edit_sheet(uuid, uuid) from public; +revoke all on function private.can_use_sheet(uuid, uuid) from public; +revoke all on function private.require_actor() from public; +revoke all on function private.require_sheet_editor(uuid, uuid) from public; +revoke all on function private.require_version_editor(uuid, uuid) from public; +revoke all on function private.insert_sheet_draft(uuid, uuid, jsonb, text) from public; +revoke all on function private.copy_sheet_assets(uuid, uuid, uuid, jsonb) from public; +revoke all on function private.remap_document_assets(jsonb, jsonb) from public; +revoke all on function private.set_sheet_status(uuid, uuid, public.sheet_status, public.sheet_status, text) from public; + revoke all on function public.create_anatomical_sheet(text, text, text, jsonb, text, public.sheet_visibility, boolean) from public, anon; revoke all on function public.create_sheet_draft(uuid, uuid, text) from public, anon; revoke all on function public.publish_sheet_version(uuid) from public, anon; @@ -991,6 +1137,7 @@ revoke all on function public.fork_anatomical_sheet(uuid, text, text, public.she revoke all on function public.archive_anatomical_sheet(uuid) from public, anon; revoke all on function public.restore_anatomical_sheet(uuid) from public, anon; revoke all on function public.delete_anatomical_sheet(uuid) from public, anon; +revoke all on function public.set_sheet_visibility(uuid, public.sheet_visibility) from public, anon; revoke all on function public.register_sheet_asset(uuid, text, integer, text) from public, anon; revoke all on function public.delete_sheet_asset(uuid) from public, anon; @@ -1003,6 +1150,7 @@ grant execute on function public.fork_anatomical_sheet(uuid, text, text, public. grant execute on function public.archive_anatomical_sheet(uuid) to authenticated, service_role; grant execute on function public.restore_anatomical_sheet(uuid) to authenticated, service_role; grant execute on function public.delete_anatomical_sheet(uuid) to authenticated, service_role; +grant execute on function public.set_sheet_visibility(uuid, public.sheet_visibility) to authenticated, service_role; grant execute on function public.register_sheet_asset(uuid, text, integer, text) to authenticated, service_role; grant execute on function public.delete_sheet_asset(uuid) to authenticated, service_role; @@ -1013,13 +1161,12 @@ revoke all on public.anatomical_sheet_assets from public, anon, authenticated; grant select on public.species to authenticated; grant select on public.anatomical_sheets to authenticated; --- Editors change the identity columns in place; status, provenance, ownership go through RPCs. -grant update (name, slug, description, visibility) on public.anatomical_sheets to authenticated; +-- Editors change the identity columns in place; visibility, status, provenance, ownership go through RPCs. +grant update (name, slug, description) on public.anatomical_sheets to authenticated; grant select on public.anatomical_sheet_versions to authenticated; -- Draft autosave: editors patch content and change_note; the guards keep -- published rows frozen whatever the grant says. grant update (content, change_note) on public.anatomical_sheet_versions to authenticated; -grant delete on public.anatomical_sheet_versions to authenticated; grant select on public.anatomical_sheet_assets to authenticated; alter table public.species enable row level security; @@ -1067,12 +1214,6 @@ create policy anatomical_sheet_versions_update_own_draft using (status = 'draft' and private.can_edit_sheet((select auth.uid()), sheet_id)) with check (status = 'draft' and private.can_edit_sheet((select auth.uid()), sheet_id)); -create policy anatomical_sheet_versions_delete_own_draft - on public.anatomical_sheet_versions - for delete - to authenticated - using (status = 'draft' and private.can_edit_sheet((select auth.uid()), sheet_id)); - create policy anatomical_sheet_assets_select on public.anatomical_sheet_assets for select diff --git a/supabase/migrations/20261008110100_private_execute_hardening.sql b/supabase/migrations/20261008110100_private_execute_hardening.sql new file mode 100644 index 00000000..15e79baf --- /dev/null +++ b/supabase/migrations/20261008110100_private_execute_hardening.sql @@ -0,0 +1,28 @@ +-- Harden EXECUTE on the private helpers created by the foundation, profiles +-- and platform-roles migrations. +-- +-- The foundation ran `alter default privileges in schema private revoke +-- execute on functions from public`. PostgreSQL applies per-schema default +-- privileges on top of the built-in defaults; a per-schema REVOKE cannot +-- remove the built-in EXECUTE for PUBLIC. Every function created since kept +-- it. Nothing was reachable through the API (PostgREST exposes `public` +-- only and anon has no USAGE on `private`), but the project rule is +-- "EXECUTE revoked from public, granted only to the roles that evaluate +-- it". This migration makes it true; pgTAP 001 pins it with a census. + +revoke all on function private.set_updated_at() from public; +revoke all on function private.reset_phone_verification() from public; +revoke all on function private.handle_new_auth_user() from public; +revoke all on function audit.reject_mutation() from public; + +-- Role predicates keep their explicit grant to authenticated (policies). +revoke all on function private.has_platform_role(uuid, public.platform_role[]) from public; +revoke all on function private.is_platform_owner(uuid) from public; +revoke all on function private.is_platform_admin(uuid) from public; +revoke all on function private.is_platform_moderator(uuid) from public; +revoke all on function private.is_support(uuid) from public; + +-- Owner-context helpers: RPCs and privileged SQL sessions only. +revoke all on function private.can_manage_platform_role(uuid, public.platform_role) from public; +revoke all on function private.assign_platform_role(uuid, uuid, public.platform_role) from public; +revoke all on function private.withdraw_platform_role(uuid, uuid, public.platform_role, text) from public; diff --git a/supabase/tests/001_schema.sql b/supabase/tests/001_schema.sql index ad7283bf..a2a12645 100644 --- a/supabase/tests/001_schema.sql +++ b/supabase/tests/001_schema.sql @@ -1,6 +1,6 @@ -- Schema contract: objects exist, RLS is on, API roles start from zero. begin; -select plan(24); +select plan(26); -- Schemas select has_schema('private', 'schema private exists'); @@ -51,5 +51,20 @@ select ok(not has_column_privilege('authenticated', 'public.profiles', 'active', select ok(not has_schema_privilege('anon', 'private', 'usage'), 'anon has no usage on schema private'); select ok(not has_function_privilege('anon', 'public.grant_platform_role(uuid, public.platform_role)', 'execute'), 'anon cannot execute grant_platform_role'); +-- Private helpers: EXECUTE revoked from everyone except the predicates the policies evaluate. +-- (has_function_privilege is true for any role while proacl is null, i.e. the built-in PUBLIC default.) +select is( + (select count(*) from pg_proc p join pg_namespace n on n.oid = p.pronamespace + where n.nspname in ('private', 'audit') and has_function_privilege('anon', p.oid, 'execute')), + 0::bigint, 'anon can execute nothing in private/audit' +); +select is( + (select string_agg(p.proname::text, ',' order by p.proname::text collate "C") + from pg_proc p join pg_namespace n on n.oid = p.pronamespace + where n.nspname in ('private', 'audit') and has_function_privilege('authenticated', p.oid, 'execute')), + 'can_edit_sheet,can_use_sheet,has_platform_role,is_platform_admin,is_platform_moderator,is_platform_owner,is_support', + 'authenticated executes only the policy predicates in private' +); + select * from finish(); rollback; diff --git a/supabase/tests/005_anatomical_sheets.sql b/supabase/tests/005_anatomical_sheets.sql index b7151985..7c44ba0f 100644 --- a/supabase/tests/005_anatomical_sheets.sql +++ b/supabase/tests/005_anatomical_sheets.sql @@ -3,7 +3,7 @@ -- denied path (other user, anon, direct writes, official sheets). -- Counts are scoped to fixture ids: the real stack also carries seed rows. begin; -select plan(95); +select plan(127); -- --------------------------------------------------------------------------- -- Fixtures @@ -106,7 +106,23 @@ select ok(not has_table_privilege('authenticated', 'public.anatomical_sheet_vers select ok(not has_column_privilege('authenticated', 'public.anatomical_sheet_versions', 'status', 'update'), 'authenticated cannot update versions.status'); select ok(has_column_privilege('authenticated', 'public.anatomical_sheet_versions', 'content', 'update'), 'authenticated may update versions.content (RLS: own draft)'); select ok(not has_table_privilege('authenticated', 'public.anatomical_sheet_assets', 'insert'), 'authenticated cannot insert assets directly'); -select ok(not has_function_privilege('anon', 'public.publish_sheet_version(uuid)', 'execute'), 'anon cannot execute publish_sheet_version'); +select ok( + not (has_column_privilege('authenticated', 'public.anatomical_sheets', 'visibility', 'update') + or has_column_privilege('authenticated', 'public.anatomical_sheets', 'creator_user_id', 'update') + or has_column_privilege('authenticated', 'public.anatomical_sheets', 'current_version_id', 'update') + or has_column_privilege('authenticated', 'public.anatomical_sheets', 'based_on_sheet_id', 'update') + or has_column_privilege('authenticated', 'public.anatomical_sheets', 'based_on_version_id', 'update') + or has_column_privilege('authenticated', 'public.anatomical_sheets', 'species_id', 'update')), + 'visibility, ownership, provenance, current version and species are not user-updatable' +); +select ok(not has_table_privilege('authenticated', 'public.anatomical_sheet_versions', 'delete'), 'authenticated cannot delete versions directly (RPC only)'); +select is( + (select count(*) from pg_proc p join pg_namespace n on n.oid = p.pronamespace + where n.nspname = 'public' and p.prokind = 'f' + and not exists (select 1 from pg_depend d where d.objid = p.oid and d.deptype = 'e') + and has_function_privilege('anon', p.oid, 'execute')), + 0::bigint, 'anon can execute no public RPC' +); -- --------------------------------------------------------------------------- -- 2. Alice creates a private sheet (draft v1), registers an asset, publishes @@ -138,6 +154,17 @@ select throws_ok( '23505', null, 'slug is unique per owner' ); +select throws_ok( + $$ select public.create_anatomical_sheet('equine', 'Bad', 'bad-doc', '{"schema_version":"abc","species_id":"equine"}'::jsonb) $$, + '23514', null, 'a non-numeric schema_version is refused' +); +select throws_ok( + $$ update public.anatomical_sheet_versions + set content = jsonb_build_object('schema_version', 1, 'species_id', 'equine', 'pad', repeat('x', 2200000)) + where id = pg_temp.id('v1') $$, + '23514', null, 'a document over 2 MiB is refused' +); + -- Publishing a draft whose main view has no asset is refused with the rule code select throws_ok( $$ select public.publish_sheet_version(pg_temp.id('v1')) $$, @@ -196,6 +223,61 @@ select throws_ok( '23514', 'document not publishable: annotation.id.duplicate', 'publish refuses duplicate annotation ids' ); +create function pg_temp.publish_issue(p_doc jsonb) returns text language plpgsql as $$ +begin + update public.anatomical_sheet_versions set content = p_doc where id = pg_temp.id('v1'); + perform public.publish_sheet_version(pg_temp.id('v1')); + return 'published'; +exception when check_violation then + return sqlerrm; +end $$; +grant execute on function pg_temp.publish_issue(jsonb) to authenticated; +select is( + pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{views,0,kind}', '"detail"')), + 'document not publishable: view.main.count, view.parent.missing', 'SQL gate: no main view' +); +select is( + pg_temp.publish_issue(pg_temp.sheet_doc(pg_temp.id('asset')) #- '{annotations,2}'), + 'document not publishable: view.unreachable', 'SQL gate: detail view without trigger' +); +select is( + pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{views,1,parent_view_id}', '"nowhere"')), + 'document not publishable: view.parent.missing, annotation.opens_view.invalid', 'SQL gate: dangling parent view' +); +select is( + pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{views,1,id}', '"view-main"')), + 'document not publishable: view.unreachable, view.id.duplicate, annotation.opens_view.invalid', 'SQL gate: duplicate view id' +); +select is( + pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{annotations,0,view_id}', '"nowhere"')), + 'document not publishable: annotation.view.missing', 'SQL gate: annotation on a missing view' +); +select is( + pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{annotations,0,category_id}', '"nowhere"')), + 'document not publishable: annotation.category.missing', 'SQL gate: missing category' +); +select is( + pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{annotations,1,vertebral_region_code}', '"Z"')), + 'document not publishable: annotation.region.missing', 'SQL gate: unknown vertebral region' +); +select is( + pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{annotations,2,opens_view_id}', '"view-main"')), + 'document not publishable: view.unreachable, annotation.opens_view.invalid', 'SQL gate: trigger opening a non-child view' +); +select is( + pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{vertebral_config,regions}', + '[{"code":"C","name":{"fr":"a","en":"a"},"count":7},{"code":"C","name":{"fr":"b","en":"b"},"count":7}]')), + 'document not publishable: region.code.duplicate', 'SQL gate: duplicate region code' +); +select is( + pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{finding_zones}', + '[{"id":"hip","name":{"fr":"a","en":"a"},"categories":[]},{"id":"hip","name":{"fr":"b","en":"b"},"categories":[]}]')), + 'document not publishable: finding_zone.id.duplicate', 'SQL gate: duplicate finding zone id' +); +select is( + pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{views}', '"not-an-array"')), + 'document not publishable: document.shape', 'SQL gate: views not an array' +); update public.anatomical_sheet_versions set content = pg_temp.sheet_doc(pg_temp.id('asset')) where id = pg_temp.id('v1'); @@ -233,10 +315,9 @@ select is( (select change_note from public.anatomical_sheet_versions where id = pg_temp.id('v1')), 'asset wired', 'editor UPDATE of a published change note touches no row' ); -delete from public.anatomical_sheet_versions where id = pg_temp.id('v1'); -select is( - (select count(*) from public.anatomical_sheet_versions where id = pg_temp.id('v1')), - 1::bigint, 'editor DELETE of a published version touches no row' +select throws_ok( + $$ delete from public.anatomical_sheet_versions where id = pg_temp.id('v1') $$, + '42501', null, 'editor has no DELETE privilege on versions (RPC only)' ); reset role; select throws_ok( @@ -331,8 +412,11 @@ select throws_ok( -- alice makes the sheet public through the identity-column policy select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); select is((select name from public.anatomical_sheets where id = pg_temp.id('sheet')), 'Mon cheval', 'bob update on alice sheet changed nothing'); -update public.anatomical_sheets set visibility = 'public' where id = pg_temp.id('sheet'); +select lives_ok($$ select public.set_sheet_visibility(pg_temp.id('sheet'), 'public') $$, 'alice makes the sheet public (audited RPC)'); insert into pg_temp.ids select 'v3', public.create_sheet_draft(pg_temp.id('sheet'), null, 'work in progress'); +insert into pg_temp.ids select 'asset-unused', public.register_sheet_asset( + pg_temp.id('sheet'), repeat('b', 64), 1000, 'Unused.svg' +); select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000b","role":"authenticated"}', true); select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('sheet')), 1::bigint, 'bob sees the public sheet'); @@ -348,8 +432,25 @@ select is( update public.anatomical_sheet_versions set content = '{"schema_version":1}'::jsonb where id = pg_temp.id('v3'); select throws_ok( $$ select public.fork_anatomical_sheet(pg_temp.id('v3'), 'Copie', 'copie-bob') $$, - '55000', null, 'only a published version can be copied' + '42501', null, 'a draft cannot be copied (hidden from non-editors)' ); +update public.anatomical_sheets set name = 'hijack-public' where id = pg_temp.id('sheet'); +select is((select name from public.anatomical_sheets where id = pg_temp.id('sheet')), 'Mon cheval', 'bob cannot rename a public sheet he does not edit'); +-- Every editor-gated RPC refuses a non-editor, even on a public sheet +select throws_ok($$ select public.publish_sheet_version(pg_temp.id('v3')) $$, '42501', null, 'non-editor cannot publish'); +select throws_ok($$ select public.deprecate_sheet_version(pg_temp.id('v2'), 'x') $$, '42501', null, 'non-editor cannot deprecate'); +select throws_ok($$ select public.delete_sheet_version(pg_temp.id('v3')) $$, '42501', null, 'non-editor cannot delete a version'); +select throws_ok($$ select public.archive_anatomical_sheet(pg_temp.id('sheet')) $$, '42501', null, 'non-editor cannot archive'); +select throws_ok($$ select public.restore_anatomical_sheet(pg_temp.id('sheet')) $$, '42501', null, 'non-editor cannot restore'); +select throws_ok($$ select public.delete_anatomical_sheet(pg_temp.id('sheet')) $$, '42501', null, 'non-editor cannot delete a sheet'); +select throws_ok($$ select public.set_sheet_visibility(pg_temp.id('sheet'), 'private') $$, '42501', null, 'non-editor cannot change visibility'); +select throws_ok($$ select public.register_sheet_asset(pg_temp.id('sheet'), repeat('c', 64), 10, 'x.svg') $$, '42501', null, 'non-editor cannot register an asset'); +select throws_ok($$ select public.delete_sheet_asset(pg_temp.id('asset-unused')) $$, '42501', null, 'non-editor cannot delete an asset'); +select throws_ok($$ select public.publish_sheet_version(gen_random_uuid()) $$, '42501', null, 'unknown version gets the same answer as a foreign one'); +-- A platform admin is not an editor of a personal sheet +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-000000000001","role":"authenticated"}', true); +select throws_ok($$ select public.create_sheet_draft(pg_temp.id('sheet')) $$, '42501', null, 'platform owner cannot edit a personal sheet'); +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000b","role":"authenticated"}', true); create table pg_temp.source_snapshot as select s.updated_at as sheet_updated_at, s.current_version_id, v.content, v.updated_at as version_updated_at, @@ -374,7 +475,7 @@ select results_eq( select results_eq( $$ select sha256, byte_size, id <> pg_temp.id('asset') from public.anatomical_sheet_assets where sheet_id = pg_temp.id('fork') $$, $$ values (repeat('a', 64), 142400, true) $$, - 'asset rows are copied (same content, new id)' + 'only the asset referenced by the copied version is copied (same content, new id)' ); select is( (select content -> 'views' -> 0 ->> 'svg_asset_id' from public.anatomical_sheet_versions where id = pg_temp.id('fork-v1')), @@ -434,6 +535,7 @@ select throws_ok( '55000', null, 'the sheet cannot be deleted while a copy is active' ); select lives_ok($$ select public.archive_anatomical_sheet(pg_temp.id('sheet')) $$, 'alice archives the sheet'); +select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('sheet')), 1::bigint, 'the editor still reads her archived sheet'); select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000b","role":"authenticated"}', true); select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('sheet')), 0::bigint, 'an archived sheet is no longer usable by others'); select throws_ok( @@ -447,14 +549,36 @@ select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-0000000 select lives_ok($$ select public.restore_anatomical_sheet(pg_temp.id('sheet')) $$, 'alice restores the sheet'); select lives_ok($$ select public.delete_sheet_version(pg_temp.id('v2')) $$, 'deprecated v2 is deleted once no active copy depends on it'); select is((select count(*) from public.anatomical_sheet_versions where id = pg_temp.id('v2')), 0::bigint, 'v2 row is gone'); -select lives_ok($$ delete from public.anatomical_sheet_versions where id = pg_temp.id('v3') $$, 'editor drops her own draft directly'); +select lives_ok($$ select public.delete_sheet_version(pg_temp.id('v3')) $$, 'editor drops her own draft through the RPC'); +insert into pg_temp.ids select 'v4', public.create_sheet_draft(pg_temp.id('sheet'), null, 'after deletion'); +select is( + (select version_number from public.anatomical_sheet_versions where id = pg_temp.id('v4')), + 4, 'a deleted version number is never reused' +); +select lives_ok($$ select public.delete_sheet_asset(pg_temp.id('asset-unused')) $$, 'an unreferenced asset can be deleted'); select throws_ok( $$ select public.delete_sheet_asset(pg_temp.id('asset')) $$, '55000', null, 'an asset referenced by a version cannot be deleted' ); -- --------------------------------------------------------------------------- --- 7. Official sheets: platform admins only +-- 7. Deactivated account +-- --------------------------------------------------------------------------- +reset role; +update public.profiles set active = false where id = '20000000-0000-0000-0000-00000000000b'; +set local role authenticated; +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000b","role":"authenticated"}', true); +select throws_ok( + $$ select public.create_anatomical_sheet('equine', 'Nope', 'nope', pg_temp.sheet_doc(null)) $$, + '42501', null, 'a deactivated account cannot write' +); +reset role; +update public.profiles set active = true where id = '20000000-0000-0000-0000-00000000000b'; +set local role authenticated; +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); + +-- --------------------------------------------------------------------------- +-- 8. Official sheets: platform admins only -- --------------------------------------------------------------------------- select throws_ok( $$ select public.create_anatomical_sheet('equine', 'Officielle', 'officielle', pg_temp.sheet_doc(null), '', 'public', true) $$, @@ -481,7 +605,7 @@ select throws_ok( ); -- --------------------------------------------------------------------------- --- 8. Anonymous +-- 9. Anonymous -- --------------------------------------------------------------------------- set local role anon; select set_config('request.jwt.claims', '', true); @@ -493,15 +617,17 @@ select throws_ok( ); -- --------------------------------------------------------------------------- --- 9. Audit trail +-- 10. Audit trail -- --------------------------------------------------------------------------- reset role; select results_eq( $$ select action from audit.audit_logs - where resource_id in (pg_temp.id('sheet'), pg_temp.id('v1'), pg_temp.id('v2'), pg_temp.id('fork'), pg_temp.id('asset')) + where resource_id in (pg_temp.id('sheet'), pg_temp.id('v1'), pg_temp.id('v2'), pg_temp.id('v3'), pg_temp.id('fork'), + pg_temp.id('asset'), pg_temp.id('asset-unused')) group by action order by action collate "C" $$, $$ values ('anatomical_sheet.archived'), ('anatomical_sheet.created'), ('anatomical_sheet.deleted'), - ('anatomical_sheet.forked'), ('anatomical_sheet.restored'), ('anatomical_sheet_asset.registered'), + ('anatomical_sheet.forked'), ('anatomical_sheet.restored'), ('anatomical_sheet.visibility_changed'), + ('anatomical_sheet_asset.deleted'), ('anatomical_sheet_asset.registered'), ('anatomical_sheet_version.created'), ('anatomical_sheet_version.deleted'), ('anatomical_sheet_version.deprecated'), ('anatomical_sheet_version.published') $$, 'every lifecycle step left an audit event'