fix(supabase): revoke PUBLIC EXECUTE on private helpers, audited visibility RPC, input caps, authz-first RPCs, +32 pgTAP checks

This commit is contained in:
bchanot committed 2026-10-08 23:59:39 +02:00
1 parent 6966c54a2e
commit d3fa65af29
15 files changed
+682 -221

No files matched your search

@@ -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
@@ -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;
+16 -1
View File
@@ -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;
+141 -15
View File
@@ -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'