fix(supabase): V1-2.1 bound printed numbers before the size measure

check_document_structure sums the numbers' printed digits one at a time
before building the whole text, so huge exponents answer
document.too_large instead of an out-of-memory error. pgTAP 020: the
full AR-1 B matrix and the rights RPCs refused to every non-owner; 017:
exponent vectors, the number bomb, publish.species.other alone.
This commit is contained in:
bchanot committed 2026-10-28 20:08:18 +01:00
1 parent 12816671e4
commit 3eba6d89b2
4 files changed
+198 -3

No files matched your search

@@ -403,13 +403,20 @@ $$;
-- working copy (contract §12.2): an object whose id-bearing collections are
-- arrays, schema version 2, at most 2 MiB as the UTF-8 bytes of its JSON text
-- (the table CHECK of section 1 uses the same measure; checked here first so
-- the caller gets the closed code, never a raw constraint error).
-- the caller gets the closed code, never a raw constraint error). A number
-- prints as plain digits (`1e131071` is 131 072 bytes of text), so the printed
-- numbers are summed one at a time first: the whole text is built only once it
-- stays within the input's size plus the cap, never a gigabyte from a small
-- payload (an out-of-memory error instead of the closed code).
create or replace function private.check_document_structure(p_doc jsonb)
returns void
language plpgsql
immutable
set search_path = ''
as $$
declare
v_number jsonb;
v_number_bytes bigint := 0;
begin
if not private.sheet_document_has_shape(p_doc) then
raise exception 'document.shape' using errcode = '23514';
@@ -417,6 +424,12 @@ begin
if (p_doc -> 'schema_version') is distinct from '2'::jsonb then
raise exception 'document.schema_version' using errcode = '23514';
end if;
for v_number in select jsonb_path_query(p_doc, 'strict $.** ? (@.type() == "number")') loop
v_number_bytes := v_number_bytes + octet_length(v_number::text);
if v_number_bytes > 2097152 then
raise exception 'document.too_large' using errcode = '23514';
end if;
end loop;
if octet_length(p_doc::text) > 2097152 then
raise exception 'document.too_large' using errcode = '23514';
end if;
+1 -1
View File
@@ -1,7 +1,7 @@
-- Platform roles: bootstrap, AR-1 B (live aal2 session required), delegation
-- rules, every denied path, visibility. Since V1-2.1 (M4) every role change
-- needs an aal2 session that still exists in auth.sessions and, for a grant,
-- a verified TOTP factor on the target. Full AR-1 matrix: 015.
-- a verified TOTP factor on the target. AR-1 cases: 015; full matrix: 020.
begin;
select plan(25);
+34 -1
View File
@@ -8,7 +8,7 @@
-- ids created here, so the file also runs on a stack that already holds
-- sheets, rounds or a working copy.
begin;
select plan(104);
select plan(110);
-- Accounts: O owner, E admin + editor + publisher, V reviewer, V2 admin +
-- editor + reviewer (an author of a later round), V3 reviewer, R reader.
@@ -604,6 +604,19 @@ select pg_temp.fixture_round('o2', 'o2.f', 'c',
select throws_ok($$ select public.publish_sheet_version(pg_temp.id('o2.f')) $$,
'P0001', 'publish.approval.invalid', 'M6: publication refused after an approval by an author (the owner)');
-- ============ Publication refused for the species `other` alone (§6.7) ============
-- No RPC creates such a sheet (`sheet.species_invalid`); a row moved to `other`
-- by the table owner after an otherwise valid approval stands in for it.
select pg_temp.sheet('so', repeat('b6', 32));
select pg_temp.fixture_round('so', 'so.f', 'd', jsonb_set(pg_temp.doc(pg_temp.id('so.asset'), 'reviewed'), '{description,fr}', '"so"'), 'E', 'V', 'V');
reset role;
alter table public.anatomical_sheets disable trigger user;
update public.anatomical_sheets set species_id = 'other' where id = pg_temp.id('so');
alter table public.anatomical_sheets enable trigger user;
select pg_temp.as_user('E');
select throws_ok($$ select public.publish_sheet_version(pg_temp.id('so.f')) $$,
'P0001', 'publish.species.other', 'publication refused for the species other, every other rule met');
-- ============ Document size: UTF-8 bytes of the JSON text (§6.2, §12.2) ============
select pg_temp.sheet('sz', repeat('c3', 32));
select lives_ok($$ select pg_temp.save_now('sz', pg_temp.sized(pg_temp.doc(pg_temp.id('sz.asset'), 'reviewed'), 2097151, 'x')) $$,
@@ -650,6 +663,26 @@ select ok((select octet_length(content::text) <= 2097152 and jsonb_array_length(
select pg_temp.as_user('E');
select throws_ok($$ select public.create_official_sheet('r17-szbig', pg_temp.sized(pg_temp.doc(null, 'reviewed'), 2097153, 'x')) $$,
'23514', 'document.too_large', 'size: creation refuses a document of cap + 1 bytes with the closed code');
-- Numbers count as PostgreSQL prints them: plain digits, never an exponent.
select lives_ok($$ select pg_temp.save_now('sz', jsonb_set(pg_temp.doc(pg_temp.id('sz.asset'), 'reviewed'), '{pad}', '[1e-7, 1e21]')) $$,
'size: numbers that JavaScript prints with an exponent are saved');
reset role;
select is((select content -> 'pad' #>> '{}' from public.anatomical_sheet_versions where id = pg_temp.id('sz.v')),
'[0.0000001, 1000000000000000000000]', 'size: they are measured in their plain form');
create table pg_temp.sz_exp as select jsonb_set(pg_temp.doc(pg_temp.id('sz.asset'), 'reviewed'), '{pad}',
(select jsonb_agg(1e21) from generate_series(1, 100000))) as d;
grant select on pg_temp.sz_exp to authenticated;
select ok((select octet_length(replace(replace(d::text, ', ', ','), ': ', ':')) - 17 * 100000 <= 2097152
and octet_length(d::text) > 2097152 from pg_temp.sz_exp),
'size: the exponent fixture is under the cap in compact JavaScript form and over it as measured');
select pg_temp.as_user('E');
select throws_ok($$ select pg_temp.save_now('sz', (select d from pg_temp.sz_exp)) $$,
'23514', 'document.too_large', 'size: a document over the cap only once its numbers print in full is refused');
-- 9 000 numbers of 131 072 digits each: a 90 kB payload whose text would be
-- 1.2 GB. The closed code comes back, not an out-of-memory error.
select throws_ok($$ select pg_temp.save_now('sz', jsonb_set(pg_temp.doc(pg_temp.id('sz.asset'), 'reviewed'), '{pad}',
(select jsonb_agg(1e131071) from generate_series(1, 9000)))) $$,
'23514', 'document.too_large', 'size: numbers that print as gigabytes of digits get the closed code, not an out-of-memory error');
reset role;
select is((select pg_get_constraintdef(oid) from pg_constraint where conname = 'anatomical_sheet_versions_content_size'),
'CHECK ((octet_length((content)::text) <= 2097152))',
+149
View File
@@ -0,0 +1,149 @@
-- V1-2.1 M4: the AR-1 B matrix of contract §15 in full, and the catalogue
-- rights RPCs refused to every account that is not an owner at aal2 (§5.2,
-- §5.4; M6 keeps « no self-grant for a non-owner »). Table-driven: every
-- caller class (no role, owner, admin, moderator, support, deactivated owner)
-- at aal1 and aal2 grants and revokes each of the four roles, on itself and on
-- another account; expected: aal1 always `mfa_required`, self `self_target`,
-- aal2 allowed only where can_manage_platform_role allows (owner any role,
-- admin moderator and support), else `forbidden`. Every refused call leaves the
-- target's roles and the audit log unchanged. Fixtures are scoped to the ids
-- created here.
begin;
select plan(449);
create table pg_temp.who (label text primary key, id uuid not null);
insert into pg_temp.who values
('N', '20000000-0000-0000-0000-000000000001'), ('O', '20000000-0000-0000-0000-000000000002'),
('A', '20000000-0000-0000-0000-000000000003'), ('M', '20000000-0000-0000-0000-000000000004'),
('S', '20000000-0000-0000-0000-000000000005'), ('D', '20000000-0000-0000-0000-000000000006'),
('E', '20000000-0000-0000-0000-000000000007'), ('V', '20000000-0000-0000-0000-000000000008'),
('P', '20000000-0000-0000-0000-000000000009'), ('R', '20000000-0000-0000-0000-00000000000a'),
('T', '20000000-0000-0000-0000-0000000000ff');
insert into auth.users (id, email, email_confirmed_at)
select id, lower(label) || '@m20.local', now() from pg_temp.who;
insert into auth.mfa_factors (id, user_id, factor_type, status, created_at, updated_at)
select gen_random_uuid(), id, 'totp', 'verified', now(), now() from pg_temp.who;
-- Two live sessions per account: 2010… at aal2, 2020… at aal1.
insert into auth.sessions (id, user_id, aal)
select ('20100000' || substr(id::text, 9))::uuid, id, 'aal2'::auth.aal_level from pg_temp.who
union all
select ('20200000' || substr(id::text, 9))::uuid, id, 'aal1'::auth.aal_level from pg_temp.who;
select set_config('request.jwt.claims', '', true);
select private.assign_platform_role(null, id, r::public.platform_role)
from (values ('O', 'owner'), ('A', 'admin'), ('M', 'moderator'), ('S', 'support'), ('D', 'owner'),
('E', 'admin'), ('P', 'admin')) v(l, r)
join pg_temp.who w on w.label = v.l;
update public.profiles set active = false where id = '20000000-0000-0000-0000-000000000006';
insert into public.anatomical_catalog_grants (user_id, grant_kind, reason, verification_note, granted_by)
select w.id, v.k::public.catalog_grant_kind, 'm20', case when v.k = 'catalog_reader' then null else 'c' end,
'20000000-0000-0000-0000-000000000002'
from (values ('E', 'sheet_editor'), ('V', 'sheet_reviewer'), ('P', 'sheet_publisher'), ('R', 'catalog_reader')) v(l, k)
join pg_temp.who w on w.label = v.l;
create function pg_temp.uid(p text) returns uuid language sql stable as $$ select id from pg_temp.who where label = p $$;
-- The calling session of <p> at <aal> (its session row exists).
create function pg_temp.act(p text, p_aal text) returns void language plpgsql as $$
begin
perform set_config('role', 'authenticated', true);
perform set_config('request.jwt.claims', jsonb_build_object('sub', pg_temp.uid(p), 'role', 'authenticated', 'aal', p_aal,
'session_id', ((case p_aal when 'aal2' then '20100000' else '20200000' end) || substr(pg_temp.uid(p)::text, 9))::uuid)::text, true);
end $$;
-- The role rows and audit rows of the target T, as a fingerprint.
create function pg_temp.t_state() returns text language sql stable as $$
select coalesce((select string_agg(role::text || ':' || (revoked_at is null)::text, ',' order by id)
from public.profile_roles where user_id = '20000000-0000-0000-0000-0000000000ff'), '')
|| '|' || (select count(*) from audit.audit_logs where target_user_id = '20000000-0000-0000-0000-0000000000ff');
$$;
-- One case: as table owner, T holds <role> iff the operation is a revoke;
-- then the call; then the assertion, and for a refusal T's state unchanged.
create function pg_temp.role_case(p_caller text, p_aal text, p_op text, p_role text, p_self boolean)
returns setof text language plpgsql as $$
declare
v_target uuid := case when p_self then pg_temp.uid(p_caller) else pg_temp.uid('T') end;
v_call text := format(case p_op when 'grant' then 'select public.grant_platform_role(%L, %L)'
else 'select public.revoke_platform_role(%L, %L, ''m20'')' end, v_target, p_role);
v_expect text;
v_before text;
v_desc text := format('%s at %s %ss %s on %s', p_caller, p_aal, p_op, p_role, case when p_self then 'itself' else 'another account' end);
begin
perform set_config('role', 'postgres', true);
perform set_config('request.jwt.claims', '', true);
update public.profile_roles set revoked_at = now() where user_id = pg_temp.uid('T') and revoked_at is null;
if p_op = 'revoke' then
perform private.assign_platform_role(null, pg_temp.uid('T'), p_role::public.platform_role);
end if;
v_expect := case
when p_aal = 'aal1' then 'mfa_required'
when p_self then 'self_target'
when p_caller = 'O' then 'ok'
when p_caller = 'A' and p_role in ('moderator', 'support') then 'ok'
else 'forbidden' end;
v_before := pg_temp.t_state();
perform pg_temp.act(p_caller, p_aal);
if v_expect = 'ok' then
return next lives_ok(v_call, v_desc || ': allowed');
else
return next throws_ok(v_call, '42501', v_expect, v_desc || ': ' || v_expect);
perform set_config('role', 'postgres', true);
return next is(pg_temp.t_state(), v_before, v_desc || ': nothing written');
end if;
end $$;
grant execute on all functions in schema pg_temp to authenticated;
grant select on pg_temp.who to authenticated;
-- 6 callers x 2 levels x 2 operations x 4 roles x 2 targets = 192 cases: 16
-- allowed (one assertion), 176 refused (two assertions).
select pg_temp.role_case(c, l, o, r, s)
from unnest(array['N', 'O', 'A', 'M', 'S', 'D']) with ordinality c(c, ci),
unnest(array['aal1', 'aal2']) with ordinality l(l, li),
unnest(array['grant', 'revoke']) with ordinality o(o, oi),
unnest(array['owner', 'admin', 'moderator', 'support']) with ordinality r(r, ri),
unnest(array[false, true]) with ordinality s(s, si)
order by ci, li, oi, ri, si;
-- The regression chain on the real owner (§15): at aal1, an owner revoking
-- the other owner and demoting the admin is refused; both keep their role.
select pg_temp.act('O', 'aal1');
select throws_ok($$ select public.revoke_platform_role('20000000-0000-0000-0000-000000000006', 'owner', 'x') $$,
'42501', 'mfa_required', 'an aal1 owner cannot revoke another owner');
select throws_ok($$ select public.revoke_platform_role('20000000-0000-0000-0000-000000000003', 'admin', 'x') $$,
'42501', 'mfa_required', 'an aal1 owner cannot demote an admin');
reset role;
select ok(private.has_platform_role('20000000-0000-0000-0000-000000000003', 'admin'), 'the admin keeps its role');
-- Catalogue rights RPCs: only an owner at aal2. Every other account, with or
-- without a capability, is refused `rights.owner` at aal2, `rights.mfa` at
-- aal1, on itself and on another account (M6: no self-grant for a non-owner).
create function pg_temp.rights_case(p_caller text, p_aal text) returns setof text language plpgsql as $$
declare
v_code text := case p_aal when 'aal1' then 'rights.mfa' else 'rights.owner' end;
v_grant uuid := (select id from public.anatomical_catalog_grants where user_id = pg_temp.uid('R') and revoked_at is null);
v_calls text[] := array[
format('select public.grant_catalog_right(%L, ''sheet_reviewer'', ''self'', ''x'')', pg_temp.uid(p_caller)),
format('select public.grant_catalog_right(%L, ''sheet_editor'', ''self'', ''x'')', pg_temp.uid(p_caller)),
format('select public.grant_catalog_right(%L, ''catalog_reader'', ''other'')', pg_temp.uid('T')),
format('select public.revoke_catalog_right(%L, ''x'')', v_grant),
'select public.lookup_catalog_account(''t@m20.local'')',
'select public.list_catalog_grants()'];
v_call text;
begin
foreach v_call in array v_calls loop
perform pg_temp.act(p_caller, p_aal);
return next throws_ok(v_call, '42501', v_code, format('%s at %s: %s refused (%s)', p_caller, p_aal, split_part(split_part(v_call, '.', 2), '(', 1), v_code));
end loop;
end $$;
grant execute on all functions in schema pg_temp to authenticated;
select pg_temp.rights_case(c, l)
from unnest(array['N', 'A', 'M', 'S', 'D', 'E', 'V', 'P', 'R']) c,
unnest(array['aal2']) l;
select pg_temp.rights_case(c, 'aal1') from unnest(array['N', 'E', 'V']) c;
reset role;
select is((select count(*) from public.anatomical_catalog_grants g join pg_temp.who w on w.id = g.user_id), 4::bigint,
'no refused call wrote a grant');
select is((select count(*) from public.anatomical_catalog_grants where user_id = pg_temp.uid('R') and revoked_at is null), 1::bigint,
'the reader''s grant is still active');
select * from finish();
rollback;