fix(supabase): revoke PUBLIC EXECUTE on private helpers, audited visibility RPC, input caps, authz-first RPCs, +32 pgTAP checks
This commit is contained in:
1 parent
6966c54a2e
commit
d3fa65af29
15 files changed
+682
-221
No files matched your search
@@ -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/<sha256>.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.
|
||||
Reference in new issue
Block a user