fix(supabase): confirmed uploads gate asset reads (hash claim), seeds-listed test, Dockerfile workspace manifests; importer declares every authored label, real in=out control

This commit is contained in:
bchanot committed 2026-10-09 00:50:36 +02:00
1 parent bbfb8d6203
commit dee4ce43d9
28 files changed
+511 -87

No files matched your search

+5 -3
View File
@@ -31,9 +31,11 @@ schema_paths = []
[db.seed]
enabled = true
# seed.sql: local development accounts + first owner, never run in prod.
# seed/**: versioned reference data (official anatomical sheets as drafts),
# idempotent, applied in every environment (docs/development/SUPABASE.md §3).
# seed.sql: local development accounts + first owner, LOCAL ONLY (never
# `db push --include-seed` against a shared database: it would run this file).
# seed/...: versioned reference data (official anatomical sheets as drafts),
# idempotent. The CLI takes literal paths: list every new seed file here; the
# PGlite harness test fails when one is missing (docs/development/SUPABASE.md §3).
sql_paths = ["./seed.sql", "./seed/anatomical-sheets/equine/v1/equine_v1.sql"]
[realtime]
@@ -4,18 +4,63 @@
-- Bucket anatomical-sheet-assets, private. Objects are content-addressed:
-- key = <sha256>.svg, so two sheets with the same drawing share one object
-- and a copy of a sheet never copies bytes. Reading an object is authorised
-- THROUGH a sheet (an asset row the caller may use or edit), never through
-- the hash alone; drafts stay visible to editors only, as the sheet rows do.
-- No API role writes objects: uploads are an operator / server task
-- THROUGH a sheet: an asset row the caller may use or edit AND whose upload
-- was confirmed server-side (uploaded_at), never through a hash a user
-- merely registered; drafts stay visible to editors only, as the sheet rows
-- do. No API role writes objects: uploads are an operator / server task
-- (import tool with the service key) until the editor step adds a signed
-- upload path.
insert into storage.buckets (id, name, public, file_size_limit, allowed_mime_types)
values ('anatomical-sheet-assets', 'anatomical-sheet-assets', false, 20971520, array['image/svg+xml'])
on conflict (id) do nothing;
on conflict (id) do update
set public = false, file_size_limit = excluded.file_size_limit,
allowed_mime_types = excluded.allowed_mime_types;
-- An object is readable when a usable sheet publishes it (a non-draft
-- version references the asset) or when the caller edits the sheet.
-- ---------------------------------------------------------------------------
-- Upload confirmation. An editor may register any sha256 as metadata, so a
-- hash alone must never open an object: the read predicate requires
-- uploaded_at, which only the operator / server path (service role) sets
-- after the bytes have landed in the bucket for that sheet.
-- ---------------------------------------------------------------------------
alter table public.anatomical_sheet_assets
add column uploaded_at timestamptz;
comment on column public.anatomical_sheet_assets.uploaded_at is
'Set by confirm_sheet_asset_upload (service role) once the object <sha256>.svg exists for this sheet. Null = metadata only, object not readable through this row.';
create index anatomical_sheet_assets_sha256_idx on public.anatomical_sheet_assets (sha256);
create or replace function public.confirm_sheet_asset_upload(asset_id uuid)
returns uuid
language plpgsql
security definer
set search_path = ''
as $$
begin
update public.anatomical_sheet_assets
set uploaded_at = now()
where id = asset_id and uploaded_at is null;
if not found and not exists (select 1 from public.anatomical_sheet_assets where id = asset_id) then
raise exception 'unknown asset %', asset_id using errcode = 'P0002';
end if;
perform private.log_event(
auth.uid(), 'anatomical_sheet_asset.uploaded', 'anatomical_sheet_asset', asset_id
);
return asset_id;
end;
$$;
comment on function public.confirm_sheet_asset_upload(uuid) is
'Operator / server only (service role): marks the asset bytes as present in Storage. Idempotent.';
revoke all on function public.confirm_sheet_asset_upload(uuid) from public, anon, authenticated;
grant execute on function public.confirm_sheet_asset_upload(uuid) to service_role;
-- ---------------------------------------------------------------------------
-- Read predicate: a confirmed asset row of a sheet the caller edits, or of a
-- usable sheet whose non-draft version references it. Sargable on sha256.
-- ---------------------------------------------------------------------------
create or replace function private.can_read_sheet_asset_object(p_user_id uuid, p_object_name text)
returns boolean
language sql
@@ -26,7 +71,9 @@ as $$
select exists (
select 1
from public.anatomical_sheet_assets a
where a.sha256 || '.svg' = p_object_name
where a.sha256 = left(p_object_name, 64)
and p_object_name = a.sha256 || '.svg'
and a.uploaded_at is not null
and (
private.can_edit_sheet(p_user_id, a.sheet_id)
or (
@@ -43,7 +90,7 @@ as $$
$$;
comment on function private.can_read_sheet_asset_object(uuid, text) is
'Storage read predicate for bucket anatomical-sheet-assets: object <sha256>.svg referenced by a published version of a usable sheet, or by any version of a sheet the caller edits.';
'Storage read predicate for bucket anatomical-sheet-assets: object <sha256>.svg whose upload is confirmed, referenced by a published version of a usable sheet, or by any version of a sheet the caller edits.';
revoke all on function private.can_read_sheet_asset_object(uuid, text) from public;
grant execute on function private.can_read_sheet_asset_object(uuid, text) to authenticated;
@@ -37,7 +37,14 @@ Les ids d'asset sont dérivés du sha256 du fichier (UUID déterministe), les de
| Feuilles | 612 |
| Orientations vétérinaires | 41 |
Contrôle entrée = sortie : 27 annotations lues, 27 écrites ; 792 nœuds lus, 792 écrits. L'importateur s'arrête si un nœud manque.
Contrôle entrée = sortie, compté des deux côtés (sources lues, document écrit). L'importateur s'arrête au moindre écart :
| Contrôle | Lu (sources) | Écrit (document) |
| ------------------------------------ | ------------ | ---------------- |
| Annotations (data-anno-id distincts) | 27 | 27 |
| Nœuds (catégories incluses) | 792 | 792 |
| Feuilles | 612 | 612 |
| Orientations vétérinaires | 41 | 41 |
## 3. Annotations
@@ -85,13 +92,15 @@ Couleur : `null` partout (les couleurs du SVG restent dans l'asset). Dans les SV
## 5. Configuration vertébrale
| Code | Nom FR | Nom EN | Vertèbres |
| ---- | ----------- | -------- | --------- |
| `C` | Cervicales | Cervical | 7 |
| `T` | Thoraciques | Thoracic | 18 |
| `L` | Lombaires | Lumbar | 6 |
| `S` | Sacrales | Sacral | 5 |
| `Cd` | Caudales | Caudal | 18 |
| Code | Nom FR | Nom EN | Vertèbres | Origine du libellé |
| ---- | ----------- | -------- | --------- | ---------------------- |
| `C` | Cervicales | Cervical | 7 | importateur, à valider |
| `T` | Thoraciques | Thoracic | 18 | importateur, à valider |
| `L` | Lombaires | Lumbar | 6 | importateur, à valider |
| `S` | Sacrales | Sacral | 5 | importateur, à valider |
| `Cd` | Caudales | Caudal | 18 | importateur, à valider |
Nombres de vertèbres : `vertebrae.ts`. Noms de région : écrits par l'importateur (aucune source ne les porte).
Codes de région déduits des libellés (racines `cervic`, `thorac`/`dors`, `lombair`/`lumbar`, `sacral`/`sacre`, `caudal`/`coccyg`, FR puis EN). Déduction faite une fois ici, le document porte le code :
@@ -139,12 +148,21 @@ Copie fidèle du catalogue : ids, libellés, descriptions présentes, orientatio
## 7. Anomalies à valider
12 points demandent une décision, 6 sont informatifs.
21 points demandent une décision, 6 sont informatifs.
### À valider
| Code | Objet | Détail |
| --------------------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `label.authored` | name | Libellé écrit par l'importateur : FR « Cheval », EN « Horse ». |
| `label.authored` | description | Libellé écrit par l'importateur : FR « Fiche anatomique officielle Faunosteo », EN « Official Faunosteo anatomical sheet ». |
| `label.authored` | views.main | Libellé écrit par l'importateur : FR « Vue générale », EN « Overview ». |
| `label.authored` | views.head | Libellé écrit par l'importateur : FR « Tête », EN « Head ». |
| `label.authored` | vertebral_config.C | Libellé écrit par l'importateur : FR « Cervicales », EN « Cervical ». |
| `label.authored` | vertebral_config.T | Libellé écrit par l'importateur : FR « Thoraciques », EN « Thoracic ». |
| `label.authored` | vertebral_config.L | Libellé écrit par l'importateur : FR « Lombaires », EN « Lumbar ». |
| `label.authored` | vertebral_config.S | Libellé écrit par l'importateur : FR « Sacrales », EN « Sacral ». |
| `label.authored` | vertebral_config.Cd | Libellé écrit par l'importateur : FR « Caudales », EN « Caudal ». |
| `category.label.authored` | articulations | Libellé écrit par l'importateur : FR « Articulations », EN « Joints ». |
| `category.label.authored` | os | Libellé écrit par l'importateur : FR « Os », EN « Bones ». |
| `category.slug.normalised` | charni-res-vert-brales | Slug technique dégradé (accents perdus) normalisé en « charnieres-vertebrales ». |
@@ -173,7 +191,12 @@ Copie fidèle du catalogue : ids, libellés, descriptions présentes, orientatio
Aucune donnée métier écartée.
Non repris par construction : le second élément graphique de chaque annotation (marqueur visuel), qui reste dans l'asset SVG copié à l'identique.
Non repris par construction :
- `schema_version` du catalogue (`2.0`) : version du format historique, remplacée par `schema_version: 1` du document canonique ; la valeur d'origine est citée dans `attribution.notes`.
- bloc `species` du catalogue (`equine`, Cheval / Horse) : porté par `species_id` du document et par la table `public.species` ; le nom de la fiche est écrit séparément (voir anomalies `label.authored`).
- second élément graphique de chaque annotation (marqueur visuel) : reste dans l'asset SVG copié à l'identique, le document ne garde que la zone de clic.
- `data-anno-category-name` : répète le slug technique (`articulations`, `os`), ce n'est pas un libellé ; le libellé de catégorie vient de la table de l'importateur (section 4).
## 9. Résultat de validation
+50 -8
View File
@@ -2,7 +2,7 @@
-- through a sheet (published reference for users, any version for editors),
-- never through its hash alone. No API writes.
begin;
select plan(14);
select plan(28);
insert into auth.users (id, email) values
('30000000-0000-0000-0000-00000000000a', 'alice-assets@test.local'),
@@ -11,8 +11,8 @@ insert into auth.users (id, email) values
create table pg_temp.ids (key text primary key, id uuid not null);
create function pg_temp.id(p_key text) returns uuid language sql stable
as $$ select id from pg_temp.ids where key = p_key $$;
grant all on pg_temp.ids to anon, authenticated;
grant execute on function pg_temp.id(text) to anon, authenticated;
grant all on pg_temp.ids to anon, authenticated, service_role;
grant execute on function pg_temp.id(text) to anon, authenticated, service_role;
-- Minimal publishable document with one main view on a given asset.
create function pg_temp.doc(p_asset uuid) returns jsonb language sql as $$
@@ -27,7 +27,7 @@ create function pg_temp.doc(p_asset uuid) returns jsonb language sql as $$
'name', jsonb_build_object('fr', 'V', 'en', 'V'), 'svg_asset_id', p_asset, 'view_box', null)),
'annotations', '[]'::jsonb, 'finding_zones', '[]'::jsonb);
$$;
grant execute on function pg_temp.doc(uuid) to authenticated;
grant execute on function pg_temp.doc(uuid) to authenticated, service_role;
-- 1. Bucket contract
select is((select public from storage.buckets where id = 'anatomical-sheet-assets'), false, 'bucket is private');
@@ -59,26 +59,45 @@ select lives_ok($$ select public.publish_sheet_version(pg_temp.id('v1')) $$, 'v1
insert into pg_temp.ids select 'v2', public.create_sheet_draft(pg_temp.id('sheet'));
update public.anatomical_sheet_versions set content = pg_temp.doc(pg_temp.id('b')) where id = pg_temp.id('v2');
-- Objects uploaded by the operator (owner session)
-- Objects uploaded by the operator (owner session), then confirmed through the
-- service-role RPC for A and B only; C stays metadata without bytes.
reset role;
insert into storage.objects (bucket_id, name) values
('anatomical-sheet-assets', repeat('a', 64) || '.svg'),
('anatomical-sheet-assets', repeat('b', 64) || '.svg'),
('anatomical-sheet-assets', repeat('c', 64) || '.svg'),
('anatomical-sheet-assets', repeat('d', 64) || '.svg');
set local role authenticated;
select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'nothing is readable before the upload is confirmed');
select throws_ok(
$$ select public.confirm_sheet_asset_upload(pg_temp.id('a')) $$,
'42501', null, 'an editor cannot confirm an upload (service role only)'
);
set local role service_role;
select lives_ok($$ select public.confirm_sheet_asset_upload(pg_temp.id('a')) $$, 'service role confirms asset A');
select lives_ok($$ select public.confirm_sheet_asset_upload(pg_temp.id('b')) $$, 'service role confirms asset B');
select is(public.confirm_sheet_asset_upload(pg_temp.id('a')), pg_temp.id('a'), 'confirming twice is idempotent');
reset role;
-- 3. Editor reads every object of her sheet (published, draft, unreferenced), not foreign ones
set local role authenticated;
select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
select results_eq(
$$ select name from storage.objects where bucket_id = 'anatomical-sheet-assets' order by name $$,
$$ values (repeat('a', 64) || '.svg'), (repeat('b', 64) || '.svg'), (repeat('c', 64) || '.svg') $$,
'editor reads the objects of her sheet; the object no sheet registered stays hidden'
$$ values (repeat('a', 64) || '.svg'), (repeat('b', 64) || '.svg') $$,
'editor reads the confirmed objects of her sheet; unconfirmed and foreign objects stay hidden'
);
-- 4. Bob: private sheet → nothing; public sheet → published reference only
-- 4. Bob: private sheet → nothing; claiming the hash on his own sheet opens nothing
select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000b","role":"authenticated"}', true);
select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'other user reads nothing from a private sheet');
insert into pg_temp.ids select 'bob-sheet', public.create_anatomical_sheet('equine', 'Claim', 'claim-test', pg_temp.doc(null));
select lives_ok(
$$ select public.register_sheet_asset(pg_temp.id('bob-sheet'), repeat('a', 64), 100, 'A.svg') $$,
'bob registers the known hash on his own sheet'
);
select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'a self-registered hash without a confirmed upload opens no object');
select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
select lives_ok($$ select public.set_sheet_visibility(pg_temp.id('sheet'), 'public') $$, 'alice makes the sheet public');
select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000b","role":"authenticated"}', true);
@@ -100,11 +119,34 @@ select is(
0::bigint, 'no API role has an insert/update/delete policy on the bucket objects'
);
-- Name variants never match the strict key
select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
select ok(
not private.can_read_sheet_asset_object('30000000-0000-0000-0000-00000000000a', repeat('a', 64))
and not private.can_read_sheet_asset_object('30000000-0000-0000-0000-00000000000a', upper(repeat('a', 64)) || '.svg')
and not private.can_read_sheet_asset_object('30000000-0000-0000-0000-00000000000a', 'x/' || repeat('a', 64) || '.svg')
and not private.can_read_sheet_asset_object('30000000-0000-0000-0000-00000000000a', repeat('a', 64) || '.svg/'),
'object name must be exactly <sha256>.svg'
);
-- A deprecated version still publishes its asset
select lives_ok($$ select public.publish_sheet_version(pg_temp.id('v2')) $$, 'v2 (asset B) published');
select lives_ok($$ select public.deprecate_sheet_version(pg_temp.id('v1'), 'old') $$, 'v1 (asset A) deprecated');
select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000b","role":"authenticated"}', true);
select results_eq(
$$ select name from storage.objects where bucket_id = 'anatomical-sheet-assets' order by name $$,
$$ values (repeat('a', 64) || '.svg'), (repeat('b', 64) || '.svg') $$,
'published and deprecated references both open the object for users of a public sheet'
);
-- 5. Archived sheet hides objects from others; anon sees nothing
select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
select lives_ok($$ select public.archive_anatomical_sheet(pg_temp.id('sheet')) $$, 'alice archives');
select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000b","role":"authenticated"}', true);
select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'archived sheet: others read nothing');
select set_config('request.jwt.claims', '{"sub":"30000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
select lives_ok($$ select public.restore_anatomical_sheet(pg_temp.id('sheet')) $$, 'alice restores');
select lives_ok($$ select public.delete_anatomical_sheet(pg_temp.id('sheet')) $$, 'alice soft-deletes the sheet');
select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'deleted sheet: even the creator reads nothing');
set local role anon;
select set_config('request.jwt.claims', '', true);
select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'anon reads nothing');
+23 -3
View File
@@ -2,7 +2,7 @@
-- present as a platform-owned DRAFT, never published by the seed, publishable
-- by platform admins only, content accepted by the SQL referential gate.
begin;
select plan(14);
select plan(18);
insert into auth.users (id, email) values
('40000000-0000-0000-0000-000000000001', 'root-seed@test.local'),
@@ -12,8 +12,8 @@ select private.assign_platform_role(null, '40000000-0000-0000-0000-000000000001'
create table pg_temp.ids (key text primary key, id uuid not null);
create function pg_temp.id(p_key text) returns uuid language sql stable
as $$ select id from pg_temp.ids where key = p_key $$;
grant all on pg_temp.ids to anon, authenticated;
grant execute on function pg_temp.id(text) to anon, authenticated;
grant all on pg_temp.ids to anon, authenticated, service_role;
grant execute on function pg_temp.id(text) to anon, authenticated, service_role;
insert into pg_temp.ids select 'sheet', id from public.anatomical_sheets where slug = 'faunosteo-cheval' and is_official;
insert into pg_temp.ids select 'draft', id from public.anatomical_sheet_versions where sheet_id = pg_temp.id('sheet');
@@ -74,5 +74,25 @@ select set_config('request.jwt.claims', '{"sub":"40000000-0000-0000-0000-0000000
select is((select count(*) from public.anatomical_sheet_versions where id = pg_temp.id('draft')), 1::bigint, 'a platform admin sees the official draft');
select lives_ok($$ select public.publish_sheet_version(pg_temp.id('draft')) $$, 'a platform admin could publish it (rolled back here)');
-- 3. Storage: the seed registers metadata only; after the operator upload + confirmation,
-- a platform admin reads both objects and a plain user none.
reset role;
insert into storage.objects (bucket_id, name)
select 'anatomical-sheet-assets', a.sha256 || '.svg' from public.anatomical_sheet_assets a where a.sheet_id = pg_temp.id('sheet');
set local role authenticated;
select set_config('request.jwt.claims', '{"sub":"40000000-0000-0000-0000-000000000001","role":"authenticated"}', true);
select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'seed objects are not readable before confirmation');
set local role service_role;
select is(
(select count(*) from public.anatomical_sheet_assets a where a.sheet_id = pg_temp.id('sheet')
and public.confirm_sheet_asset_upload(a.id) = a.id),
2::bigint, 'operator confirms the two uploads'
);
set local role authenticated;
select set_config('request.jwt.claims', '{"sub":"40000000-0000-0000-0000-000000000001","role":"authenticated"}', true);
select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 2::bigint, 'a platform admin reads both official SVGs');
select set_config('request.jwt.claims', '{"sub":"40000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'a plain user reads no official draft SVG');
select * from finish();
rollback;