Files
faunosteo/supabase/tests/014_animals_relations.sql
bchanot e7fd7e34e6 test(supabase): the audit privacy check no longer reads a uuid as a date
014 #237 matched « 20[0-9]{2}- » inside a workspace uuid on a long-lived stack.
The pattern now reads the metadata without workspace_id, still over every
audit row. It would have stopped the DEV procedure at db:test. Found by the
V1-1.6 verifier.
2026-10-26 17:53:37 +01:00

879 lines
69 KiB
PL/PgSQL

-- V1-1.4 Animals and relations (M3): species rows, animal fields and the
-- birth model, idempotent creates, revisions, archive, relations with their
-- history (current, ended, voided), derived values, searches, isolation
-- between workspaces, refusals for every other actor, caps and the write
-- budget shared with the clients, minimised audit, integrity under a
-- privileged writer, privileges and census.
-- Contract: docs/development/V1-1_OWNERS_ANIMALS.md §5.2-§5.4, §7.1, §9, §10, §12.1.
-- Actors: A and B confirmed and active; C unconfirmed; D deactivated after
-- creating an animal; S a platform owner; E (per-animal caps, animal cap),
-- F (budget), H (workspace relation cap) and G (D9a) confirmed.
begin;
select plan(258);
insert into auth.users (id, email, email_confirmed_at) values
('70000000-0000-0000-0000-00000000000a', 'alice-an@test.local', now()),
('70000000-0000-0000-0000-00000000000b', 'bob-an@test.local', now()),
('70000000-0000-0000-0000-00000000000c', 'carol-an@test.local', null),
('70000000-0000-0000-0000-00000000000d', 'dave-an@test.local', now()),
('70000000-0000-0000-0000-000000000005', 'staff-an@test.local', now()),
('70000000-0000-0000-0000-00000000000e', 'cap-an@test.local', now()),
('70000000-0000-0000-0000-00000000000f', 'budget-an@test.local', now()),
('70000000-0000-0000-0000-000000000011', 'wscap-an@test.local', now()),
('70000000-0000-0000-0000-000000000012', 'd9a-an@test.local', now());
select private.assign_platform_role(null, '70000000-0000-0000-0000-000000000005', 'owner');
-- A species that is later switched off (« species active or unchanged »).
insert into public.species (id, name_fr, name_en, sort_order) values ('zz-retired', 'Retirée', 'Retired', 5000);
create function pg_temp.ws(p_user uuid) returns uuid language sql stable security definer
as $$ select id from public.workspaces where personal_user_id = p_user $$;
create function pg_temp.wa() returns uuid language sql stable
as $$ select pg_temp.ws('70000000-0000-0000-0000-00000000000a') $$;
create function pg_temp.act_as(p_user uuid) returns text language sql
as $$ select set_config('request.jwt.claims',
json_build_object('sub', p_user, 'role', 'authenticated')::text, true) $$;
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 $$;
create function pg_temp.animal(p_id uuid) returns public.animals language sql stable security definer
as $$ select a from public.animals a where a.id = p_id $$;
create function pg_temp.relation(p_id uuid) returns public.animal_client_relations language sql stable security definer
as $$ select r from public.animal_client_relations r where r.id = p_id $$;
create function pg_temp.budget(p_ws uuid) returns text language sql stable security definer
as $$ select coalesce((select hour_count || '/' || day_count from private.workspace_write_budgets where workspace_id = p_ws), 'none') $$;
create function pg_temp.audit_count(p_resource uuid) returns bigint language sql stable security definer
as $$ select count(*) from audit.audit_logs where resource_id = p_resource $$;
create function pg_temp.tomorrow() returns text language sql stable
as $$ select ((now() at time zone 'UTC')::date + 1)::text $$;
-- The whole error of a statement, run as the calling role: SQLSTATE, message, detail, hint.
create function pg_temp.err(p_sql text) returns text language plpgsql
as $$
declare v_state text; v_msg text; v_detail text; v_hint text;
begin
execute p_sql;
return 'no error';
exception when others then
get stacked diagnostics v_state = returned_sqlstate, v_msg = message_text,
v_detail = pg_exception_detail, v_hint = pg_exception_hint;
return v_state || '|' || v_msg || '|' || coalesce(v_detail, '') || '|' || coalesce(v_hint, '');
end;
$$;
-- SQLSTATE and message only: the real image appends a hint to table-privilege refusals.
create function pg_temp.denial(p_sql text) returns text language sql
as $$ select split_part(pg_temp.err(p_sql), '|', 1) || '|' || split_part(pg_temp.err(p_sql), '|', 2) $$;
-- create_animal as the current caller in A's workspace, keyed for later use.
create function pg_temp.new_animal(p_key text, p_name text, p_species text, p_sex text, p_detail text default null,
p_breed text default null, p_year text default null, p_date text default null) returns uuid language sql
as $$ insert into pg_temp.ids values (p_key, (public.create_animal(pg_temp.wa(), gen_random_uuid(), p_name, p_species, p_sex,
p_detail, p_breed, p_year, p_date) ->> 'id')::uuid) returning id $$;
create function pg_temp.new_relation(p_key text, p_animal text, p_client text, p_role text, p_started text default null)
returns uuid language sql
as $$ insert into pg_temp.ids values (p_key, (public.create_animal_client_relation(pg_temp.id(p_animal), pg_temp.id(p_client),
gen_random_uuid(), p_role, p_started) ->> 'id')::uuid) returning id $$;
create function pg_temp.try_animal(p_name text, p_species text, p_sex text, p_detail text default null,
p_breed text default null, p_year text default null, p_date text default null) returns text language sql
as $$ select pg_temp.err(format('select public.create_animal(%L, gen_random_uuid(), %L, %L, %L, %L, %L, %L, %L)',
pg_temp.wa(), p_name, p_species, p_sex, p_detail, p_breed, p_year, p_date)) $$;
grant all on pg_temp.ids to authenticated, anon, service_role;
grant execute on all functions in schema pg_temp to authenticated, anon, service_role;
-- ---------------------------------------------------------------------------
-- 1. Schema, species, privileges, census
-- ---------------------------------------------------------------------------
select has_table('public', 'animals', 'table public.animals exists');
select has_table('public', 'animal_client_relations', 'table public.animal_client_relations exists');
select ok((select bool_and(relrowsecurity) from pg_class
where oid in ('public.animals'::regclass, 'public.animal_client_relations'::regclass)),
'RLS enabled on animals and animal_client_relations');
select enum_has_labels('public', 'animal_sex', array['male', 'female', 'unknown'], 'animal_sex: male, female, unknown');
select enum_has_labels('public', 'animal_relation_role', array['owner', 'keeper', 'contact'],
'animal_relation_role: owner, keeper, contact');
select results_eq(
$$ select id, name_fr, name_en, sort_order from public.species where id <> 'zz-retired' order by sort_order $$,
$$ values ('equine'::text, 'Cheval'::text, 'Horse'::text, 10), ('asinine', 'Âne', 'Donkey', 20), ('canine', 'Chien', 'Dog', 30),
('feline', 'Chat', 'Cat', 40), ('bovine', 'Bovin', 'Cattle', 50), ('caprine', 'Chèvre', 'Goat', 60),
('ovine', 'Mouton', 'Sheep', 70), ('porcine', 'Porc', 'Pig', 80), ('leporine', 'Lapin', 'Rabbit', 90),
('other', 'Autre', 'Other', 1000) $$,
'exactly the nine species of the contract and other, equine unchanged'
);
select ok((select bool_and(active) from public.species where id <> 'zz-retired'), 'every species row is active');
select ok(obj_description('public.species'::regclass, 'pg_class') like 'Species of animals and of anatomical sheets.%',
'the species table comment names animals');
select is(
(select string_agg(tablename || ':' || tableowner, ',' order by tablename collate "C") from pg_tables
where schemaname = 'public' and tablename in ('animals', 'animal_client_relations')),
'animal_client_relations:postgres,animals:postgres', 'both tables belong to postgres'
);
select is(
(select count(*) from (values ('anon'), ('service_role')) r(role)
cross join (values ('animals'), ('animal_client_relations')) t(tbl)
cross join (values ('select'), ('insert'), ('update'), ('delete'), ('truncate'), ('references'), ('trigger')) p(priv)
where has_table_privilege(r.role, 'public.' || t.tbl, p.priv)),
0::bigint, 'anon and service_role hold no privilege on either table'
);
select is(
(select count(*) from (values ('animals'), ('animal_client_relations')) t(tbl)
cross join (values ('insert'), ('update'), ('delete'), ('truncate'), ('references'), ('trigger')) p(priv)
where has_table_privilege('authenticated', 'public.' || t.tbl, p.priv)),
0::bigint, 'authenticated holds no write privilege on either table'
);
select ok(has_column_privilege('authenticated', 'public.animals', 'name', 'select')
and has_column_privilege('authenticated', 'public.animal_client_relations', 'voided_at', 'select')
and not has_column_privilege('authenticated', 'public.animals', 'create_request_digest', 'select')
and not has_column_privilege('authenticated', 'public.animal_client_relations', 'create_request_digest', 'select'),
'authenticated reads the record columns, never the request digests');
select is(
(select string_agg(tablename || ':' || policyname || ':' || cmd || ':' || array_to_string(roles, '+'), ',' order by tablename collate "C")
from pg_policies where schemaname = 'public' and tablename in ('animals', 'animal_client_relations')),
'animal_client_relations:animal_client_relations_select_member:SELECT:authenticated,animals:animals_select_member:SELECT:authenticated',
'one SELECT policy per table, for authenticated'
);
select is(
(select count(*) from pg_policies where schemaname = 'public' and tablename in ('animals', 'animal_client_relations')
and (qual not like '%caller_workspace_ids()%' or qual like '%platform%')),
0::bigint, 'both policies go through caller_workspace_ids() and name no platform role'
);
select is(
(select string_agg(c.conname || '(' || (select string_agg(a.attname, ',' order by k.i)
from unnest(c.conkey) with ordinality k(n, i) join pg_attribute a on a.attrelid = c.conrelid and a.attnum = k.n)
|| ')->' || c.confrelid::regclass::text || ':' || c.condeferrable, ';' order by c.conname collate "C")
from pg_constraint c where c.conrelid = 'public.animal_client_relations'::regclass and c.contype = 'f'),
'animal_client_relations_animal_fk(workspace_id,animal_id)->animals:false;animal_client_relations_client_fk(workspace_id,client_id)->clients:false',
'relations reference animal and client through (workspace_id, id), not deferrable'
);
select ok(
(select indisunique and pg_get_expr(indpred, indrelid) like '%ended_at IS NULL%voided_at IS NULL%'
from pg_index where indexrelid = 'public.animal_client_relations_current_unique'::regclass),
'the current-relation index is unique on rows neither ended nor voided'
);
select is(
(select string_agg(p.proname || ':' || case when p.prosecdef then 'definer' else 'invoker' end, ',' order by p.proname::text collate "C")
from pg_proc p join pg_namespace n on n.oid = p.pronamespace
where p.proname in ('create_animal', 'update_animal', 'set_animal_archived', 'create_animal_client_relation',
'end_animal_client_relation', 'update_animal_client_relation', 'void_animal_client_relation', 'search_animals',
'list_client_animals', 'client_archive_preview', 'search_clients', 'utc_tomorrow', 'parse_record_date',
'parse_birth_year', 'lock_relation_for_write')
and p.proconfig = array['search_path=""'] and pg_get_userbyid(p.proowner) = 'postgres'),
'client_archive_preview:invoker,create_animal:definer,create_animal_client_relation:definer,end_animal_client_relation:definer,'
|| 'list_client_animals:invoker,lock_relation_for_write:definer,parse_birth_year:invoker,parse_record_date:invoker,'
|| 'search_animals:invoker,search_clients:invoker,set_animal_archived:definer,update_animal:definer,'
|| 'update_animal_client_relation:definer,utc_tomorrow:invoker,void_animal_client_relation:definer',
'definer and invoker as designed; search_path empty; owner postgres'
);
select is(
(select string_agg(r.role || ':' || p.proname::text, ',' order by r.role, p.proname::text collate "C")
from pg_proc p cross join (values ('anon'), ('authenticated'), ('service_role')) r(role)
where p.proname in ('create_animal', 'update_animal', 'set_animal_archived', 'create_animal_client_relation',
'end_animal_client_relation', 'update_animal_client_relation', 'void_animal_client_relation', 'search_animals',
'list_client_animals', 'client_archive_preview', 'search_clients', 'utc_tomorrow', 'parse_record_date',
'parse_birth_year', 'lock_relation_for_write')
and has_function_privilege(r.role, p.oid, 'execute')),
'authenticated:client_archive_preview,authenticated:create_animal,authenticated:create_animal_client_relation,'
|| 'authenticated:end_animal_client_relation,authenticated:list_client_animals,authenticated:search_animals,'
|| 'authenticated:search_clients,authenticated:set_animal_archived,authenticated:update_animal,'
|| 'authenticated:update_animal_client_relation,authenticated:void_animal_client_relation',
'EXECUTE: authenticated on the eleven RPCs; the private helpers for nobody; anon and service_role on none'
);
select is(private.utc_tomorrow('2026-12-31 23:30:00+00'), date '2027-01-01',
'on 31 December UTC, 1 January is the latest accepted date');
select is(private.utc_tomorrow('2026-12-31 23:30:00-05'), date '2027-01-02',
'the UTC date decides, not the caller''s zone');
-- ---------------------------------------------------------------------------
-- 2. Animals: fields, species, the birth model (D6b), text rules
-- ---------------------------------------------------------------------------
set local role authenticated;
select pg_temp.act_as('70000000-0000-0000-0000-00000000000a');
insert into pg_temp.ids values
('marie', (public.create_client(pg_temp.wa(), gen_random_uuid(), 'person', 'Marie Dupont') ->> 'id')::uuid),
('lac', (public.create_client(pg_temp.wa(), gen_random_uuid(), 'organization', 'Écurie du Lac') ->> 'id')::uuid),
('paul', (public.create_client(pg_temp.wa(), gen_random_uuid(), 'person', 'Paul Martin') ->> 'id')::uuid),
('zoe', (public.create_client(pg_temp.wa(), gen_random_uuid(), 'person', 'Zoé Bernard') ->> 'id')::uuid),
('ana', (public.create_client(pg_temp.wa(), gen_random_uuid(), 'person', 'Ana Petit') ->> 'id')::uuid);
select is(
public.create_animal(pg_temp.wa(), '71000000-0000-0000-0000-000000000001', 'Éclair', 'equine', 'male', null,
'Selle Français', '2015', '2015-04-12') - 'id',
'{"revision": 1, "relation_id": null}'::jsonb, 'create_animal answers revision 1 and no relation');
insert into pg_temp.ids select 'eclair', id from public.animals where create_request_id = '71000000-0000-0000-0000-000000000001';
select results_eq(
$$ select name, species_id, sex::text, breed, birth_year::integer, birth_date, revision, archived_at is null
from public.animals where id = pg_temp.id('eclair') $$,
$$ values ('Éclair'::text, 'equine'::text, 'male'::text, 'Selle Français'::text, 2015, date '2015-04-12', 1, true) $$,
'A reads the created animal'
);
select is((pg_temp.animal(pg_temp.id('eclair'))).name_key, 'eclair', 'name_key folds accents and case');
select is((pg_temp.animal(pg_temp.id('eclair'))).search_key, 'eclair selle francais ', 'search_key holds name, breed and detail');
select lives_ok($$ select pg_temp.new_animal('bijou', 'Bijou', 'equine', 'female', null, null, '2016') $$,
'year alone: born in 2016, day unknown');
select is((pg_temp.animal(pg_temp.id('bijou'))).birth_date, null, 'no date is invented from a year');
select lives_ok($$ select pg_temp.new_animal('sans', 'Sans Maître', 'equine', 'unknown') $$,
'birth unknown and sex unknown, chosen explicitly');
select lives_ok($$ select pg_temp.new_animal('furet', 'Pistache', 'other', 'unknown', 'Furet') $$,
'other with its detail is accepted');
select lives_ok($$ select pg_temp.new_animal('rex', 'Rex', 'canine', 'male') $$, 'a canine is accepted');
select lives_ok($$ select pg_temp.new_animal('luna', 'Luna', 'feline', 'female') $$, 'a feline is accepted');
select lives_ok($$ select pg_temp.new_animal('quatuor', 'Quatuor', 'equine', 'male') $$, 'another horse');
select lives_ok($$ select pg_temp.new_animal('retired', 'Ancien', 'zz-retired', 'male') $$, 'an animal of a species still active');
select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, null, '2015-04-12'), 'P0001|invalid_input||',
'a date without its year is refused');
select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, '2016', '2015-04-12'), 'P0001|invalid_input||',
'a date of another year is refused');
select is(pg_temp.try_animal('Other', 'other', 'male'), 'P0001|invalid_input||', 'other without detail is refused');
select is(pg_temp.try_animal('Detail', 'equine', 'male', 'Furet'), 'P0001|invalid_input||', 'a detail on another species is refused');
select is(pg_temp.try_animal('Unicorn', 'unicorn', 'male'), 'P0001|invalid_input||', 'an unknown species is refused');
select is(pg_temp.try_animal('Nothing', null, 'male'), 'P0001|invalid_input||', 'a missing species is refused');
select is(pg_temp.try_animal('Sex', 'equine', null), 'P0001|invalid_input||', 'a missing sex is refused (no default)');
select is(pg_temp.try_animal('Sex', 'equine', 'robot'), 'P0001|invalid_input||', 'an unknown sex is refused');
select is(pg_temp.try_animal('', 'equine', 'male'), 'P0001|invalid_input||', 'an empty name is refused');
select is(pg_temp.try_animal(' Lead', 'equine', 'male'), 'P0001|invalid_input||', 'a leading space is refused');
select is(pg_temp.try_animal(e'Tab\there', 'equine', 'male'), 'P0001|invalid_input||', 'a control character is refused');
select is(pg_temp.try_animal(repeat('é', 81), 'equine', 'male'), 'P0001|invalid_input||', '81 characters are refused');
select is(pg_temp.try_animal(repeat('é', 80), 'equine', 'male'), 'no error', '80 accented characters are accepted');
select is(pg_temp.try_animal('Breed', 'equine', 'male', null, repeat('b', 81)), 'P0001|invalid_input||', 'an 81-character breed is refused');
select is(pg_temp.try_animal('Detail', 'other', 'male', repeat('d', 81)), 'P0001|invalid_input||', 'an 81-character detail is refused');
select is(pg_temp.try_animal('Year', 'equine', 'male', null, null, '1899'), 'P0001|invalid_input||', 'birth year 1899 is refused');
select is(pg_temp.try_animal('Year', 'equine', 'male', null, null, '1900'), 'no error', 'birth year 1900 is accepted');
select is(pg_temp.try_animal('Year', 'equine', 'male', null, null, left(pg_temp.tomorrow(), 4)), 'no error',
'the year of tomorrow UTC is accepted');
select is(pg_temp.try_animal('Year', 'equine', 'male', null, null, (left(pg_temp.tomorrow(), 4)::integer + 1)::text),
'P0001|invalid_input||', 'a later year is refused');
select is(pg_temp.try_animal('Year', 'equine', 'male', null, null, '15'), 'P0001|invalid_input||', 'a two-digit year is refused');
select is(pg_temp.try_animal('Year', 'equine', 'male', null, null, 'abcd'), 'P0001|invalid_input||', 'a non-numeric year is refused');
select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, '2015', '2015-02-30'), 'P0001|invalid_input||',
'an impossible date is refused without echoing it');
select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, '2015', '12/04/2015'), 'P0001|invalid_input||',
'a date in another format is refused');
select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, '1899', '1899-12-31'), 'P0001|invalid_input||',
'a date before 1900 is refused');
select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, left(pg_temp.tomorrow(), 4), pg_temp.tomorrow()), 'no error',
'tomorrow UTC is accepted (today somewhere)');
select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, left((pg_temp.tomorrow()::date + 1)::text, 4),
(pg_temp.tomorrow()::date + 1)::text), 'P0001|invalid_input||', 'the day after tomorrow UTC is refused');
select is((select count(*) from public.animals where workspace_id = pg_temp.wa()), 12::bigint, 'only the valid creates were written');
-- ---------------------------------------------------------------------------
-- 3. Idempotent create, update, revision, archive
-- ---------------------------------------------------------------------------
select is(pg_temp.budget(pg_temp.wa()), '17/17', 'five clients and twelve animals counted so far');
select is(
(public.create_animal(pg_temp.wa(), '71000000-0000-0000-0000-000000000001', 'Éclair', 'equine', 'male', null,
'Selle Français', '2015', '2015-04-12') ->> 'id')::uuid,
pg_temp.id('eclair'), 'a replay returns the first animal');
select is(pg_temp.audit_count(pg_temp.id('eclair')), 1::bigint, 'the replay writes no audit row');
select is(pg_temp.budget(pg_temp.wa()), '17/17', 'the replay consumes no budget');
select is(pg_temp.err($$ select public.create_animal(pg_temp.wa(), '71000000-0000-0000-0000-000000000001', 'Éclair', 'equine',
'female') $$), 'P0001|request_conflict||', 'the same request id with other content is refused');
select is(public.update_animal(pg_temp.id('bijou'), 1, 'Bijou', 'equine', 'female', null, 'Pur-sang', '2016', null) ->> 'revision',
'2', 'an update at the current revision gives revision 2');
select is(pg_temp.err($$ select public.update_animal(pg_temp.id('bijou'), 1, 'Bijou II', 'equine', 'female', null, null, null, null) $$),
'P0001|conflict||', 'a stale revision is refused');
select is((pg_temp.animal(pg_temp.id('bijou'))).breed, 'Pur-sang', 'the stale update overwrote nothing');
select is(public.update_animal(pg_temp.id('bijou'), 2, 'Bijou', 'equine', 'female', null, 'Pur-sang', '2016', null) ->> 'revision',
'2', 'an update that changes nothing keeps the revision');
select is(pg_temp.audit_count(pg_temp.id('bijou')), 2::bigint, 'and writes no audit row');
select is(pg_temp.err($$ select public.update_animal(pg_temp.id('bijou'), 2, 'Bijou', 'other', 'female', null, null, '2016', null) $$),
'P0001|invalid_input||', 'an update to other without detail is refused');
reset role;
update public.species set active = false where id = 'zz-retired';
set local role authenticated;
select pg_temp.act_as('70000000-0000-0000-0000-00000000000a');
select is(public.update_animal(pg_temp.id('retired'), 1, 'Ancien renommé', 'zz-retired', 'male', null, null, null, null) ->> 'revision',
'2', 'an animal keeps a species switched off since');
select is(pg_temp.err($$ select public.update_animal(pg_temp.id('bijou'), 2, 'Bijou', 'zz-retired', 'female', null, null, '2016', null) $$),
'P0001|invalid_input||', 'an animal cannot move to an inactive species');
select is(pg_temp.try_animal('Retired', 'zz-retired', 'male'), 'P0001|invalid_input||', 'an inactive species is refused at creation');
-- ---------------------------------------------------------------------------
-- 4. Relations: owners, roles, history, voiding
-- ---------------------------------------------------------------------------
select isnt(
public.create_animal(pg_temp.wa(), '71000000-0000-0000-0000-000000000002', 'Tonnerre', 'equine', 'male',
client_id => pg_temp.id('marie'), relation_role => 'owner', started_on => '2020-01-01') ->> 'relation_id',
null, 'create_animal with an initial owner relation');
insert into pg_temp.ids select 'tonnerre', id from public.animals where create_request_id = '71000000-0000-0000-0000-000000000002';
insert into pg_temp.ids select 'r_tonnerre', id from public.animal_client_relations where animal_id = pg_temp.id('tonnerre');
select results_eq(
$$ select client_id, relation_role::text, started_on, ended_at is null, voided_at is null, revision
from public.animal_client_relations where animal_id = pg_temp.id('tonnerre') $$,
$$ values (pg_temp.id('marie'), 'owner'::text, date '2020-01-01', true, true, 1) $$,
'the initial relation is current, with its start date'
);
select is(pg_temp.budget(pg_temp.wa()), '21/21', 'animal and relation are two audited writes');
select is(
public.create_animal(pg_temp.wa(), '71000000-0000-0000-0000-000000000002', 'Tonnerre', 'equine', 'male',
client_id => pg_temp.id('marie'), relation_role => 'owner', started_on => '2020-01-01') ->> 'relation_id',
pg_temp.id('r_tonnerre')::text, 'a replay returns the same relation');
select is(pg_temp.err($$ select public.create_animal(pg_temp.wa(), '71000000-0000-0000-0000-000000000002', 'Tonnerre', 'equine', 'male',
client_id => pg_temp.id('marie'), relation_role => 'keeper', started_on => '2020-01-01') $$),
'P0001|request_conflict||', 'a replay with another relation role is refused');
select is(pg_temp.err($$ select public.create_animal(pg_temp.wa(), gen_random_uuid(), 'X', 'equine', 'male',
client_id => pg_temp.id('marie')) $$), 'P0001|invalid_input||', 'a client without a role is refused');
select is(pg_temp.err($$ select public.create_animal(pg_temp.wa(), gen_random_uuid(), 'X', 'equine', 'male',
relation_role => 'owner') $$), 'P0001|invalid_input||', 'a role without a client is refused');
select is(pg_temp.err($$ select public.create_animal(pg_temp.wa(), gen_random_uuid(), 'X', 'equine', 'male',
started_on => '2020-01-01') $$), 'P0001|invalid_input||', 'a start date without a client is refused');
select lives_ok($$ select pg_temp.new_relation('r_eclair_marie_owner', 'eclair', 'marie', 'owner') $$, 'A links an owner');
select lives_ok($$ select pg_temp.new_relation('r_eclair_paul_owner', 'eclair', 'paul', 'owner') $$, 'co-ownership: a second owner');
select lives_ok($$ select pg_temp.new_relation('r_eclair_marie_keeper', 'eclair', 'marie', 'keeper') $$,
'the same client may also be the keeper');
select lives_ok($$ select pg_temp.new_relation('r_eclair_lac_keeper', 'eclair', 'lac', 'keeper') $$, 'a stable as keeper');
select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('eclair'), pg_temp.id('marie'), gen_random_uuid(), 'owner') $$),
'P0001|duplicate_relation||', 'a second current identical relation is refused');
select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('eclair'), pg_temp.id('ana'), gen_random_uuid(), 'boss') $$),
'P0001|invalid_input||', 'an unknown role is refused');
select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('eclair'), pg_temp.id('ana'), gen_random_uuid(), null) $$),
'P0001|invalid_input||', 'a missing role is refused');
select is(pg_temp.err(format('select public.create_animal_client_relation(%L, %L, gen_random_uuid(), %L, %L)',
pg_temp.id('eclair'), pg_temp.id('ana'), 'contact', (pg_temp.tomorrow()::date + 1)::text)),
'P0001|invalid_input||', 'a start date after tomorrow UTC is refused');
select is((select count(*) from public.animal_client_relations where animal_id = pg_temp.id('sans')), 0::bigint,
'an animal may have no owner and no relation');
-- Ending, dates, successive relations.
select lives_ok($$ select pg_temp.new_relation('r_bijou_paul_1', 'bijou', 'paul', 'owner', '2018-05-01') $$, 'Paul owns Bijou since 2018');
select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 1, '2017-01-01') $$),
'P0001|invalid_input||', 'an end before the start is refused');
select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 1, '2017-02-30') $$),
'P0001|invalid_input||', 'an impossible end date is refused');
select is(pg_temp.err($$ select public.update_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 1, '2018-05-01', '2021-06-30') $$),
'P0001|invalid_input||', 'an end date on a current relation is refused');
select is(public.end_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 1, '2021-06-30') ->> 'revision', '2',
'ending the relation with its date gives revision 2');
select ok((pg_temp.relation(pg_temp.id('r_bijou_paul_1'))).ended_at is not null
and (pg_temp.relation(pg_temp.id('r_bijou_paul_1'))).ended_on = date '2021-06-30', 'the ended relation keeps its row and dates');
select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 2) $$),
'P0001|already_ended||', 'ending an ended relation is refused');
select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 1) $$),
'P0001|conflict||', 'a stale revision is refused before the state');
select is(public.update_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 2, '2018-05-01', '2021-07-01') ->> 'revision', '3',
'the dates of an ended relation can be corrected');
select is(public.update_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 3, '2018-05-01', '2021-07-01') ->> 'revision', '3',
'a correction that changes nothing keeps the revision');
select is(pg_temp.err($$ select public.update_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 3, '2022-01-01', '2021-07-01') $$),
'P0001|invalid_input||', 'a start after the end is refused');
select lives_ok($$ select pg_temp.new_relation('r_bijou_paul_2', 'bijou', 'paul', 'owner', '2023-03-01') $$,
'a successive relation of the same triple is accepted once the first has ended');
select lives_ok($$ select pg_temp.new_relation('r_bijou_lac', 'bijou', 'lac', 'owner') $$, 'Écurie du Lac also owned Bijou');
select is(public.end_animal_client_relation(pg_temp.id('r_bijou_lac'), 1) ->> 'revision', '2', 'an end with no known date');
select ok((pg_temp.relation(pg_temp.id('r_bijou_lac'))).ended_at is not null and (pg_temp.relation(pg_temp.id('r_bijou_lac'))).ended_on is null,
'ended, date unknown: ended_at set, ended_on null, distinct from a current relation');
-- Voiding (N4).
select lives_ok($$ select pg_temp.new_relation('r_rex_marie_wrong', 'rex', 'marie', 'owner', '2019-01-01') $$, 'a relation entered by mistake');
select is(public.void_animal_client_relation(pg_temp.id('r_rex_marie_wrong'), 1) ->> 'revision', '2', 'voiding gives revision 2');
select results_eq(
$$ select client_id, relation_role::text, started_on, ended_on, ended_at is null, voided_at is not null
from public.animal_client_relations where id = pg_temp.id('r_rex_marie_wrong') $$,
$$ values (pg_temp.id('marie'), 'owner'::text, date '2019-01-01', null::date, true, true) $$,
'a voided relation keeps every value as entered and gains voided_at, no end date invented'
);
select is(pg_temp.err($$ select public.void_animal_client_relation(pg_temp.id('r_rex_marie_wrong'), 2) $$),
'P0001|invalid_input||', 'voiding twice is refused');
select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_rex_marie_wrong'), 2) $$),
'P0001|invalid_input||', 'a voided relation cannot be ended');
select is(pg_temp.err($$ select public.update_animal_client_relation(pg_temp.id('r_rex_marie_wrong'), 2, null, null) $$),
'P0001|invalid_input||', 'a voided relation cannot be corrected');
select lives_ok($$ select pg_temp.new_relation('r_rex_marie', 'rex', 'marie', 'owner') $$,
'a voided relation no longer holds the current-relation slot');
select lives_ok($$ select pg_temp.new_relation('r_sans_ana_wrong', 'sans', 'ana', 'keeper') $$, 'Ana entered as keeper by mistake');
select is(public.void_animal_client_relation(pg_temp.id('r_sans_ana_wrong'), 1) ->> 'revision', '2', 'voided while current');
select lives_ok($$ select pg_temp.new_relation('r_rex_lac_contact', 'rex', 'lac', 'contact') $$, 'a contact');
select is(public.end_animal_client_relation(pg_temp.id('r_rex_lac_contact'), 1, '2024-01-01') ->> 'revision', '2', 'the contact ends');
select is(public.void_animal_client_relation(pg_temp.id('r_rex_lac_contact'), 2) ->> 'revision', '3',
'an ended relation recorded by mistake can be voided');
-- Four owners for the derived values; a keeper and an owner later archived.
select lives_ok($$ select pg_temp.new_relation('r_q_ana', 'quatuor', 'ana', 'owner'), pg_temp.new_relation('r_q_lac', 'quatuor', 'lac', 'owner'),
pg_temp.new_relation('r_q_marie', 'quatuor', 'marie', 'owner'), pg_temp.new_relation('r_q_paul', 'quatuor', 'paul', 'owner') $$,
'four co-owners');
select lives_ok($$ select pg_temp.new_relation('r_luna_lac', 'luna', 'lac', 'owner'), pg_temp.new_relation('r_luna_zoe', 'luna', 'zoe', 'owner'),
pg_temp.new_relation('r_rex_zoe_keeper', 'rex', 'zoe', 'keeper') $$, 'Luna owned by the stable and Zoé, Zoé keeps Rex');
-- ---------------------------------------------------------------------------
-- 5. Archive (§7.1): no cascade, frozen relations, archived client
-- ---------------------------------------------------------------------------
select is(public.client_archive_preview(pg_temp.id('paul')),
jsonb_build_object('count', 1, 'animals', jsonb_build_array(jsonb_build_object('id', pg_temp.id('bijou'), 'name', 'Bijou'))),
'preview: Paul is the only current owner of Bijou');
select is(public.set_client_archived(pg_temp.id('zoe'), true) ->> 'revision', '2', 'Zoé is archived');
select is((select count(*) from public.animals where id = pg_temp.id('luna') and archived_at is null), 1::bigint,
'archiving a client archives none of its animals');
select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('luna'), pg_temp.id('zoe'), gen_random_uuid(), 'keeper') $$),
'P0001|archived||', 'a new relation needs an active client');
select is(pg_temp.err($$ select public.create_animal(pg_temp.wa(), gen_random_uuid(), 'X', 'equine', 'male',
client_id => pg_temp.id('zoe'), relation_role => 'owner') $$), 'P0001|archived||', 'so does the initial relation');
select is(public.end_animal_client_relation(pg_temp.id('r_rex_zoe_keeper'), 1) ->> 'revision', '2',
'the relation of an archived client with an active animal can still be ended');
select is(public.client_archive_preview(pg_temp.id('lac')), '{"count": 0, "animals": []}'::jsonb,
'a co-owner, even archived, means the stable is not the only owner of Luna');
select is(public.set_animal_archived(pg_temp.id('bijou'), true) ->> 'revision', '3', 'Bijou is archived');
select is(public.set_animal_archived(pg_temp.id('bijou'), true) ->> 'revision', '3', 'archiving again changes nothing');
select is((select count(*) from public.animal_client_relations where animal_id = pg_temp.id('bijou')
and ended_at is null and voided_at is null), 1::bigint, 'archiving an animal ends none of its relations');
select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('bijou'), pg_temp.id('ana'), gen_random_uuid(), 'keeper') $$),
'P0001|archived||', 'no new relation on an archived animal');
select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_bijou_paul_2'), 9) $$),
'P0001|archived||', 'the relations of an archived animal are frozen (archived before conflict)');
select is(pg_temp.err($$ select public.update_animal_client_relation(pg_temp.id('r_bijou_paul_2'), 1, null, null) $$),
'P0001|archived||', 'no date correction either');
select is(pg_temp.err($$ select public.void_animal_client_relation(pg_temp.id('r_bijou_paul_2'), 1) $$),
'P0001|archived||', 'no voiding either');
select is(pg_temp.err($$ select public.update_animal(pg_temp.id('bijou'), 1, 'Bijou', 'equine', 'female', null, null, null, null) $$),
'P0001|archived||', 'an archived animal refuses edits, archived reported before the stale revision');
select is(public.client_archive_preview(pg_temp.id('paul')), '{"count": 0, "animals": []}'::jsonb,
'the preview lists active animals only');
select is(pg_temp.err($$ select public.set_animal_archived(pg_temp.id('bijou'), null) $$), 'P0001|invalid_input||',
'a missing archive state is refused');
-- ---------------------------------------------------------------------------
-- 6. Reads: searches, derived values, a client's animals
-- ---------------------------------------------------------------------------
create function pg_temp.animals(p_query text, p_species text default null, p_archived boolean default false,
p_size integer default 25, p_after_key text default null, p_after_id uuid default null) returns text language sql
as $$ select coalesce(string_agg(s.name, '|' order by s.ord), '')
from public.search_animals(pg_temp.wa(), p_query, p_species, p_archived, p_size, p_after_key, p_after_id)
with ordinality s(id, name, species_id, species_detail, sex, breed, birth_year, archived_at, name_key,
current_owners, current_owner_count, ord) $$;
create function pg_temp.owners(p_key text) returns text language sql
as $$ select s.current_owner_count || ' ' || s.current_owners::text
from public.search_animals(pg_temp.wa(), (pg_temp.animal(pg_temp.id(p_key))).name,
null, (pg_temp.animal(pg_temp.id(p_key))).archived_at is not null) s
where s.id = pg_temp.id(p_key) $$;
create function pg_temp.client_count(p_key text) returns integer language sql
as $$ select s.current_animal_count from public.search_clients(pg_temp.wa(), '', true) s where s.id = pg_temp.id(p_key)
union all
select s.current_animal_count from public.search_clients(pg_temp.wa(), '', false) s where s.id = pg_temp.id(p_key) $$;
create function pg_temp.client_animals(p_key text, p_size integer default 50, p_after_sort text default null,
p_after_id uuid default null) returns text language sql
as $$ select coalesce(string_agg(s.animal_name || ':' || s.relation_role || ':' || case when s.is_current then 'current' else 'former' end,
'|' order by s.ord), '')
from public.list_client_animals(pg_temp.id(p_key), p_size, p_after_sort, p_after_id)
with ordinality s(relation_id, relation_role, started_on, ended_on, is_current, relation_revision, animal_id,
animal_name, species_id, species_detail, sex, breed, birth_year, animal_archived_at, sort_key, ord) $$;
grant execute on function pg_temp.animals(text, text, boolean, integer, text, uuid), pg_temp.owners(text),
pg_temp.client_count(text), pg_temp.client_animals(text, integer, text, uuid) to authenticated, anon, service_role;
select is(pg_temp.animals(''), 'Ancien renommé|Date|Éclair|' || repeat('é', 80) || '|Luna|Pistache|Quatuor|Rex|Sans Maître|Tonnerre|Year|Year',
'an empty term lists the active animals in name order (archived left out)');
select is(pg_temp.animals('', null, true), 'Bijou', 'the archived filter lists the archived animal only');
select is(pg_temp.animals('ECLA'), 'Éclair', 'search folds case and accents');
select is(pg_temp.animals('francais'), 'Éclair', 'search reads the breed');
select is(pg_temp.animals('furet'), 'Pistache', 'search reads the species detail');
select is(pg_temp.animals('', 'canine'), 'Rex', 'the species filter keeps one species');
select is(pg_temp.animals('', 'feline'), 'Luna', 'and excludes the others');
select is(pg_temp.animals('', null, false, 3), 'Ancien renommé|Date|Éclair', 'page 1 of 3');
select is(pg_temp.animals('', null, false, 3, (pg_temp.animal(pg_temp.id('eclair'))).name_key, pg_temp.id('eclair')),
repeat('é', 80) || '|Luna|Pistache', 'page 2 continues after the cursor, no gap, no repeat');
select is(pg_temp.err($$ select pg_temp.animals(repeat('z', 101)) $$), 'P0001|invalid_input||', 'a 101-character term is refused');
select is(pg_temp.err($$ select pg_temp.animals('', null, false, 101) $$), 'P0001|invalid_input||', 'page size 101 is refused');
select is(pg_temp.err($$ select pg_temp.animals('', null, false, 25, 'a') $$), 'P0001|invalid_input||', 'a cursor without its id is refused');
select is(pg_temp.err($$ select pg_temp.animals('', null, null) $$), 'P0001|invalid_input||', 'a missing archive filter is refused');
select is(pg_temp.owners('eclair'),
'2 ' || jsonb_build_array(jsonb_build_object('client_id', pg_temp.id('marie'), 'display_name', 'Marie Dupont', 'archived', false),
jsonb_build_object('client_id', pg_temp.id('paul'), 'display_name', 'Paul Martin', 'archived', false))::text,
'current owners in client name order, keepers left out');
select is(pg_temp.owners('quatuor'),
'4 ' || jsonb_build_array(jsonb_build_object('client_id', pg_temp.id('ana'), 'display_name', 'Ana Petit', 'archived', false),
jsonb_build_object('client_id', pg_temp.id('lac'), 'display_name', 'Écurie du Lac', 'archived', false),
jsonb_build_object('client_id', pg_temp.id('marie'), 'display_name', 'Marie Dupont', 'archived', false))::text,
'the first three owners, the count of all four');
select is(pg_temp.owners('luna'),
'2 ' || jsonb_build_array(jsonb_build_object('client_id', pg_temp.id('lac'), 'display_name', 'Écurie du Lac', 'archived', false),
jsonb_build_object('client_id', pg_temp.id('zoe'), 'display_name', 'Zoé Bernard', 'archived', true))::text,
'an archived owner stays, flagged');
select is(pg_temp.owners('rex'),
'1 ' || jsonb_build_array(jsonb_build_object('client_id', pg_temp.id('marie'), 'display_name', 'Marie Dupont', 'archived', false))::text,
'a voided owner relation is left out');
select is(pg_temp.owners('sans'), '0 []', 'no owner: an empty list (« Propriétaire non renseigné »)');
select is(pg_temp.owners('bijou'),
'1 ' || jsonb_build_array(jsonb_build_object('client_id', pg_temp.id('paul'), 'display_name', 'Paul Martin', 'archived', false))::text,
'ended relations are left out');
select is(pg_temp.client_count('marie'), 4, 'Marie: Éclair (two roles, counted once), Quatuor, Rex, Tonnerre; the voided one left out');
select is(pg_temp.client_count('paul'), 2, 'Paul: Éclair and Quatuor; Bijou archived is not counted');
select is(pg_temp.client_count('lac'), 3, 'the stable: Éclair, Luna, Quatuor; ended and voided relations left out');
select is(pg_temp.client_count('zoe'), 1, 'archived Zoé: Luna; her ended keeper relation left out');
select is(pg_temp.client_count('ana'), 1, 'Ana: Quatuor; her voided keeper relation to Sans Maître left out');
select is(pg_temp.client_animals('lac'), 'Éclair:keeper:current|Luna:owner:current|Quatuor:owner:current|Bijou:owner:former',
'a client''s animals: current first, then former, each by name; voided left out');
select is(pg_temp.client_animals('paul'), 'Bijou:owner:current|Éclair:owner:current|Quatuor:owner:current|Bijou:owner:former',
'successive relations of one animal appear as current and former');
select is(pg_temp.client_animals('lac', 2), 'Éclair:keeper:current|Luna:owner:current', 'page 1 of 2');
select is(pg_temp.client_animals('lac', 2,
(select s.sort_key from public.list_client_animals(pg_temp.id('lac'), 2) s order by s.sort_key desc limit 1),
(select s.relation_id from public.list_client_animals(pg_temp.id('lac'), 2) s order by s.sort_key desc limit 1)),
'Quatuor:owner:current|Bijou:owner:former', 'page 2 continues after the cursor');
select is(pg_temp.err($$ select pg_temp.client_animals('lac', 0) $$), 'P0001|invalid_input||', 'page size 0 is refused');
select is(pg_temp.err($$ select pg_temp.client_animals('lac', 50, '0x') $$), 'P0001|invalid_input||', 'a cursor without its id is refused');
select is(public.client_archive_preview(pg_temp.id('marie')),
jsonb_build_object('count', 2, 'animals', jsonb_build_array(jsonb_build_object('id', pg_temp.id('rex'), 'name', 'Rex'),
jsonb_build_object('id', pg_temp.id('tonnerre'), 'name', 'Tonnerre'))),
'preview: Marie is the only current owner of Rex and Tonnerre (co-owned animals left out)');
-- Restore: editable again.
select is(public.set_animal_archived(pg_temp.id('bijou'), false) ->> 'revision', '4', 'restoring adds one revision');
select is(public.end_animal_client_relation(pg_temp.id('r_bijou_paul_2'), 1) ->> 'revision', '2', 'its relations can change again');
-- D creates an animal while active (used after its deactivation).
select pg_temp.act_as('70000000-0000-0000-0000-00000000000d');
insert into pg_temp.ids values ('dave', (public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000d'),
gen_random_uuid(), 'Cheval de Dave', 'equine', 'male') ->> 'id')::uuid);
-- B's own records, for the cross-workspace attempts.
select pg_temp.act_as('70000000-0000-0000-0000-00000000000b');
insert into pg_temp.ids values
('b_client', (public.create_client(pg_temp.ws('70000000-0000-0000-0000-00000000000b'), gen_random_uuid(), 'person', 'Client B') ->> 'id')::uuid),
('b_animal', (public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000b'), gen_random_uuid(), 'Animal B', 'equine', 'male') ->> 'id')::uuid);
reset role;
update public.profiles set active = false where id = '70000000-0000-0000-0000-00000000000d';
-- ---------------------------------------------------------------------------
-- 7. Isolation: the same not_found for a foreign and an unknown id
-- ---------------------------------------------------------------------------
set local role authenticated;
select pg_temp.act_as('70000000-0000-0000-0000-00000000000b');
select is((select count(*) from public.animals), 1::bigint, 'B reads its own animal only');
select is((select count(*) from public.animal_client_relations), 0::bigint, 'B reads no relation of A');
select is((select count(*) from public.animals where id = pg_temp.id('eclair')), 0::bigint, 'B naming an animal of A reads nothing');
select is((select count(*) from public.search_animals(pg_temp.wa())), 0::bigint, 'B searching the workspace of A finds nothing');
select is((select count(*) from public.list_client_animals(pg_temp.id('lac'))), 0::bigint, 'B listing a client of A finds nothing');
select is(public.client_archive_preview(pg_temp.id('marie')), '{"count": 0, "animals": []}'::jsonb, 'B previews nothing of A');
select is(pg_temp.err($$ select public.create_animal(pg_temp.wa(), gen_random_uuid(), 'X', 'equine', 'male') $$),
pg_temp.err($$ select public.create_animal(gen_random_uuid(), gen_random_uuid(), 'X', 'equine', 'male') $$),
'B creating in the workspace of A gets the error of an unknown workspace');
select is(pg_temp.err($$ select public.create_animal(gen_random_uuid(), gen_random_uuid(), 'X', 'equine', 'male') $$),
'42501|not_found||', 'that error is 42501 not_found, no detail, no hint');
select is(pg_temp.err($$ select public.update_animal(pg_temp.id('eclair'), 1, 'X', 'equine', 'male', null, null, null, null) $$),
pg_temp.err($$ select public.update_animal(gen_random_uuid(), 1, 'X', 'equine', 'male', null, null, null, null) $$),
'B updating an animal of A gets the error of an unknown animal');
select is(pg_temp.err($$ select public.update_animal(pg_temp.id('eclair'), 1, '', 'nope', 'robot', null, null, 'x', 'y') $$),
'42501|not_found||', 'invalid content on a foreign id still answers not_found (authorisation first)');
select is(pg_temp.err($$ select public.set_animal_archived(pg_temp.id('eclair'), true) $$), '42501|not_found||',
'B archiving an animal of A gets not_found');
select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('b_animal'), pg_temp.id('marie'), gen_random_uuid(), 'owner') $$),
pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('b_animal'), gen_random_uuid(), gen_random_uuid(), 'owner') $$),
'B linking its animal to a client of A gets the error of an unknown client');
select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('eclair'), pg_temp.id('b_client'), gen_random_uuid(), 'owner') $$),
'42501|not_found||', 'B linking an animal of A to its client gets not_found');
select is(pg_temp.err($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000b'), gen_random_uuid(), 'X', 'equine',
'male', client_id => pg_temp.id('marie'), relation_role => 'owner') $$), '42501|not_found||',
'B creating an animal linked to a client of A gets not_found');
select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_eclair_marie_owner'), 1) $$),
pg_temp.err($$ select public.end_animal_client_relation(gen_random_uuid(), 1) $$),
'B ending a relation of A gets the error of an unknown relation');
select is(pg_temp.err($$ select public.update_animal_client_relation(pg_temp.id('r_eclair_marie_owner'), 1, null, null) $$),
'42501|not_found||', 'B correcting a relation of A gets not_found');
select is(pg_temp.err($$ select public.void_animal_client_relation(pg_temp.id('r_eclair_marie_owner'), 1) $$),
'42501|not_found||', 'B voiding a relation of A gets not_found');
select is(pg_temp.denial($$ insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest)
values (pg_temp.ws('70000000-0000-0000-0000-00000000000b'), 'Direct', 'equine', 'male', gen_random_uuid(), '\x00') $$),
'42501|permission denied for table animals', 'a direct insert of an animal is refused by privilege');
select is(pg_temp.denial($$ update public.animals set name = 'Direct' $$),
'42501|permission denied for table animals', 'a direct update of an animal is refused by privilege');
select is(pg_temp.denial($$ update public.animals set workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000b') $$),
'42501|permission denied for table animals', 'moving an animal to another workspace is refused by privilege');
select is(pg_temp.denial($$ delete from public.animals $$),
'42501|permission denied for table animals', 'a direct delete of an animal is refused by privilege');
select is(pg_temp.denial($$ insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role,
create_request_id, create_request_digest) values (pg_temp.ws('70000000-0000-0000-0000-00000000000b'), pg_temp.id('b_animal'),
pg_temp.id('b_client'), 'owner', gen_random_uuid(), '\x00') $$),
'42501|permission denied for table animal_client_relations', 'a direct insert of a relation is refused by privilege');
select is(pg_temp.denial($$ update public.animal_client_relations set voided_at = null $$),
'42501|permission denied for table animal_client_relations', 'a direct update of a relation is refused by privilege');
select is(pg_temp.denial($$ delete from public.animal_client_relations $$),
'42501|permission denied for table animal_client_relations', 'a direct delete of a relation is refused by privilege');
select pg_temp.act_as('70000000-0000-0000-0000-00000000000c');
select is((select count(*) from public.animals) + (select count(*) from public.animal_client_relations), 0::bigint,
'C (unconfirmed) reads no animal and no relation');
select is(pg_temp.err($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000c'), gen_random_uuid(), 'X', 'equine', 'male') $$),
'42501|not_found||', 'C cannot create, even in its own workspace');
select pg_temp.act_as('70000000-0000-0000-0000-00000000000d');
select is((select count(*) from public.animals), 0::bigint, 'D (deactivated) no longer reads its own animal');
select is((select count(*) from public.search_animals(pg_temp.ws('70000000-0000-0000-0000-00000000000d'))), 0::bigint,
'D finds nothing through search');
select is(pg_temp.err($$ select public.set_animal_archived(pg_temp.id('dave'), true) $$), '42501|not_found||',
'D cannot write its own animal');
select pg_temp.act_as('70000000-0000-0000-0000-000000000005');
select is((select count(*) from public.animals) + (select count(*) from public.animal_client_relations), 0::bigint,
'S (platform owner) reads nothing: no platform-role branch');
select is(pg_temp.err($$ select public.void_animal_client_relation(pg_temp.id('r_eclair_marie_owner'), 1) $$),
'42501|not_found||', 'S cannot write a relation of A');
reset role;
set local role anon;
select is(pg_temp.denial($$ select id from public.animals $$), '42501|permission denied for table animals', 'anon cannot read animals');
select is(pg_temp.denial($$ select id from public.animal_client_relations $$), '42501|permission denied for table animal_client_relations',
'anon cannot read relations');
select is(pg_temp.err($$ select public.create_animal(gen_random_uuid(), gen_random_uuid(), 'X', 'equine', 'male') $$),
'42501|permission denied for function create_animal||', 'anon cannot execute create_animal');
select is(pg_temp.err($$ select * from public.search_animals(gen_random_uuid()) $$),
'42501|permission denied for function search_animals||', 'anon cannot execute search_animals');
reset role;
set local role service_role;
select is(pg_temp.denial($$ select id from public.animal_client_relations $$),
'42501|permission denied for table animal_client_relations', 'service_role cannot read relations despite BYPASSRLS');
select is(pg_temp.err($$ select public.void_animal_client_relation(gen_random_uuid(), 1) $$),
'42501|permission denied for function void_animal_client_relation||', 'service_role cannot execute the relation RPCs');
select is(pg_temp.err($$ select * from public.list_client_animals(gen_random_uuid()) $$),
'42501|permission denied for function list_client_animals||', 'service_role cannot execute the reads');
reset role;
set local role authenticated;
select pg_temp.act_as('70000000-0000-0000-0000-00000000000a');
select is(pg_temp.err($$ select private.lock_relation_for_write(pg_temp.id('r_eclair_marie_owner'), 1) $$),
'42501|permission denied for function lock_relation_for_write||', 'A cannot call the relation lock directly');
select is(pg_temp.err($$ select private.parse_record_date('2020-01-01') $$),
'42501|permission denied for function parse_record_date||', 'A cannot call the date parser directly');
select is(pg_temp.err($$ select private.parse_birth_year('2020') $$),
'42501|permission denied for function parse_birth_year||', 'A cannot call the year parser directly');
select is(pg_temp.err($$ select private.utc_tomorrow(now()) $$),
'42501|permission denied for function utc_tomorrow||', 'A cannot call the date bound directly');
reset role;
-- ---------------------------------------------------------------------------
-- 8. Write budget shared with the clients (one counter per workspace)
-- ---------------------------------------------------------------------------
set local role authenticated;
select pg_temp.act_as('70000000-0000-0000-0000-00000000000f');
insert into pg_temp.ids values
('f_client', (public.create_client(pg_temp.ws('70000000-0000-0000-0000-00000000000f'), gen_random_uuid(), 'person', 'Budget Client') ->> 'id')::uuid);
reset role;
update private.workspace_write_budgets set hour_count = 999, day_count = 999
where workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000f');
set local role authenticated;
select pg_temp.act_as('70000000-0000-0000-0000-00000000000f');
select is(pg_temp.err($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000f'), gen_random_uuid(), 'Two writes',
'equine', 'male', client_id => pg_temp.id('f_client'), relation_role => 'owner') $$),
'P0001|rate_limited||', 'an animal with its relation needs two writes: refused at 999 of 1 000');
select is(pg_temp.budget(pg_temp.ws('70000000-0000-0000-0000-00000000000f')), '999/999', 'the refused create consumed nothing');
select is((select count(*) from public.animals where workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000f')), 0::bigint,
'and left no animal behind');
insert into pg_temp.ids values ('f_animal', (public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000f'),
'72000000-0000-0000-0000-000000000001', 'Budget Animal', 'equine', 'male') ->> 'id')::uuid);
select is(pg_temp.budget(pg_temp.ws('70000000-0000-0000-0000-00000000000f')), '1000/1000', 'the 1 000th write (an animal) passes');
select is(pg_temp.err($$ select public.create_client(pg_temp.ws('70000000-0000-0000-0000-00000000000f'), gen_random_uuid(), 'person', 'Late') $$),
'P0001|rate_limited||', 'the next client write is refused: one budget for clients and animals');
select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('f_animal'), pg_temp.id('f_client'), gen_random_uuid(), 'owner') $$),
'P0001|rate_limited||', 'so is a relation');
select is((public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000f'), '72000000-0000-0000-0000-000000000001',
'Budget Animal', 'equine', 'male') ->> 'id')::uuid, pg_temp.id('f_animal'), 'a replay at the limit still answers');
select is(public.update_animal(pg_temp.id('f_animal'), 1, 'Budget Animal', 'equine', 'male', null, null, null, null) ->> 'revision',
'1', 'a no-op at the limit still answers');
select is(pg_temp.budget(pg_temp.ws('70000000-0000-0000-0000-00000000000f')), '1000/1000', 'neither consumed anything');
reset role;
-- ---------------------------------------------------------------------------
-- 9. Caps: 20 current and 200 relations per animal, 20 000 animals and
-- 100 000 relations per workspace (rows inserted as postgres)
-- ---------------------------------------------------------------------------
insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest)
select pg_temp.ws('70000000-0000-0000-0000-00000000000e'), 'person', 'Cap client ' || g, gen_random_uuid(), '\x00'
from generate_series(1, 22) g;
insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest)
select pg_temp.ws('70000000-0000-0000-0000-00000000000e'), 'Cap animal ' || g, 'equine', 'male', gen_random_uuid(), '\x00'
from generate_series(1, 2) g;
insert into pg_temp.ids select 'e_animal_' || substr(name, 12), id from public.animals
where workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000e');
insert into pg_temp.ids select 'e_client_' || substr(display_name, 12), id from public.clients
where workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000e');
-- Animal 1: 20 current relations with 20 clients.
insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, create_request_id, create_request_digest)
select pg_temp.ws('70000000-0000-0000-0000-00000000000e'), pg_temp.id('e_animal_1'), pg_temp.id('e_client_' || g), 'contact',
gen_random_uuid(), '\x00'
from generate_series(1, 20) g;
-- Animal 2: 198 ended relations and one voided current one: 199 rows, none current.
insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, ended_at, voided_at,
create_request_id, create_request_digest)
select pg_temp.ws('70000000-0000-0000-0000-00000000000e'), pg_temp.id('e_animal_2'), pg_temp.id('e_client_1'), 'contact',
case when g < 199 then now() end, case when g = 199 then now() end, gen_random_uuid(), '\x00'
from generate_series(1, 199) g;
set local role authenticated;
select pg_temp.act_as('70000000-0000-0000-0000-00000000000e');
select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('e_animal_1'), pg_temp.id('e_client_21'), gen_random_uuid(), 'owner') $$),
'P0001|limit_reached||', 'the 21st current relation of an animal is refused');
reset role;
update public.animal_client_relations set voided_at = now()
where animal_id = pg_temp.id('e_animal_1') and client_id = pg_temp.id('e_client_20');
set local role authenticated;
select pg_temp.act_as('70000000-0000-0000-0000-00000000000e');
select lives_ok($$ select public.create_animal_client_relation(pg_temp.id('e_animal_1'), pg_temp.id('e_client_21'), gen_random_uuid(), 'owner') $$,
'a voided relation frees a current slot');
select lives_ok($$ select public.create_animal_client_relation(pg_temp.id('e_animal_2'), pg_temp.id('e_client_2'), gen_random_uuid(), 'owner') $$,
'the 200th relation of an animal is accepted (ended and voided rows count)');
select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('e_animal_2'), pg_temp.id('e_client_3'), gen_random_uuid(), 'owner') $$),
'P0001|limit_reached||', 'the 201st is refused although only one is current');
reset role;
insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest)
select pg_temp.ws('70000000-0000-0000-0000-00000000000e'), 'Bulk ' || g, 'equine', 'male', gen_random_uuid(), '\x00'
from generate_series(1, 19997) g;
set local role authenticated;
select pg_temp.act_as('70000000-0000-0000-0000-00000000000e');
select lives_ok($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000e'), '73000000-0000-0000-0000-000000000001',
'Cap last', 'equine', 'male') $$, 'the 20 000th animal is accepted');
select is(pg_temp.err($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000e'), gen_random_uuid(), 'Cap over',
'equine', 'male') $$), 'P0001|limit_reached||', 'the 20 001st animal is refused');
select lives_ok($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000e'), '73000000-0000-0000-0000-000000000001',
'Cap last', 'equine', 'male') $$, 'a replay at the cap still answers');
reset role;
-- H: 99 999 relations (ended) in one workspace, then the 100 000th through the RPC.
insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest)
values (pg_temp.ws('70000000-0000-0000-0000-000000000011'), 'person', 'Bulk client', gen_random_uuid(), '\x00');
insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest)
select pg_temp.ws('70000000-0000-0000-0000-000000000011'), 'H ' || g, 'equine', 'male', gen_random_uuid(), '\x00'
from generate_series(1, 501) g;
-- Animals numbered 1 to 501 by name: 1 holds 199 rows, 2 to 500 hold 200, 501 none.
create table pg_temp.h_animals as
select id, substr(name, 3)::integer as n from public.animals where workspace_id = pg_temp.ws('70000000-0000-0000-0000-000000000011');
insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, ended_at, create_request_id, create_request_digest)
select pg_temp.ws('70000000-0000-0000-0000-000000000011'), a.id, c.id, 'contact', now(), gen_random_uuid(), '\x00'
from pg_temp.h_animals a cross join generate_series(1, 200) g
cross join (select id from public.clients where workspace_id = pg_temp.ws('70000000-0000-0000-0000-000000000011')) c
where a.n <= 500 and (a.n > 1 or g < 200);
select is((select count(*) from public.animal_client_relations where workspace_id = pg_temp.ws('70000000-0000-0000-0000-000000000011')),
99999::bigint, 'H holds 99 999 relations');
insert into pg_temp.ids select 'h_client', id from public.clients where workspace_id = pg_temp.ws('70000000-0000-0000-0000-000000000011');
insert into pg_temp.ids select 'h_1', id from pg_temp.h_animals where n = 1;
insert into pg_temp.ids select 'h_free', id from pg_temp.h_animals where n = 501;
set local role authenticated;
select pg_temp.act_as('70000000-0000-0000-0000-000000000011');
select lives_ok($$ select public.create_animal_client_relation(pg_temp.id('h_1'), pg_temp.id('h_client'), gen_random_uuid(), 'owner') $$,
'the 100 000th relation of a workspace is accepted');
select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('h_free'), pg_temp.id('h_client'), gen_random_uuid(), 'owner') $$),
'P0001|limit_reached||', 'the 100 001st is refused, on an animal without any relation');
select is(pg_temp.err($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-000000000011'), gen_random_uuid(), 'H new',
'equine', 'male', client_id => pg_temp.id('h_client'), relation_role => 'owner') $$),
'P0001|limit_reached||', 'an animal with an initial relation too');
reset role;
-- ---------------------------------------------------------------------------
-- 10. Audit: one row per write, ids only, hidden from platform staff (N9)
-- ---------------------------------------------------------------------------
select is(
(select string_agg(action, ',' order by occurred_at, action collate "C") from audit.audit_logs where resource_id = pg_temp.id('r_bijou_paul_1')),
'animal_client_relation.created,animal_client_relation.ended,animal_client_relation.updated',
'each write of a relation leaves one audit row'
);
select is(
(select string_agg(action, ',' order by occurred_at, action collate "C") from audit.audit_logs
where resource_id in (pg_temp.id('tonnerre'), pg_temp.id('r_tonnerre'))),
'animal.created,animal_client_relation.created', 'create_animal with a relation leaves two rows'
);
select is(
(select string_agg(action, ',' order by occurred_at, action collate "C") from audit.audit_logs where resource_id = pg_temp.id('r_rex_marie_wrong')),
'animal_client_relation.created,animal_client_relation.voided', 'voiding is audited as such'
);
select is(
(select string_agg(action, ',' order by occurred_at, action collate "C") from audit.audit_logs where resource_id = pg_temp.id('bijou')),
'animal.archived,animal.created,animal.restored,animal.updated', 'archive and restore are audited'
);
select is(
(select count(*) from audit.audit_logs where split_part(action, '.', 1) in ('animal', 'animal_client_relation')
and resource_id in (select id from pg_temp.ids)
and ((metadata - 'workspace_id') <> '{}'::jsonb
or (metadata ->> 'workspace_id')::uuid not in (select id from public.workspaces))),
0::bigint, 'audit metadata is the workspace id only'
);
select is(
(select count(*) from audit.audit_logs where split_part(action, '.', 1) in ('animal', 'animal_client_relation')
-- The workspace uuid is left out: its hex digits can read as a year (« …2012-… »); the test above proves it is the only key.
and ((metadata - 'workspace_id')::text ~* '(eclair|bijou|tonnerre|furet|selle|owner|keeper|contact|20[0-9]{2}-)'
or correlation_id is not null)),
0::bigint, 'no name, role, breed or date in the audit rows'
);
select is(
(select count(*) from audit.audit_logs where resource_id = pg_temp.id('eclair')
and actor_user_id is distinct from '70000000-0000-0000-0000-00000000000a'),
0::bigint, 'the actor is the caller'
);
set local role authenticated;
select pg_temp.act_as('70000000-0000-0000-0000-000000000005');
select is((select count(*) from audit.audit_logs where split_part(action, '.', 1) in ('animal', 'animal_client_relation')),
0::bigint, 'S reads no animal or relation audit row');
reset role;
-- ---------------------------------------------------------------------------
-- 11. Integrity without the RPCs: a privileged writer (postgres, past RLS)
-- still meets the constraints
-- ---------------------------------------------------------------------------
select throws_ok(
$$ insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, create_request_id, create_request_digest)
values (pg_temp.wa(), pg_temp.id('eclair'), pg_temp.id('b_client'), 'owner', gen_random_uuid(), '\x00') $$,
'23503', null, 'a relation to a client of another workspace is refused by the composite foreign key');
select throws_ok(
$$ insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, create_request_id, create_request_digest)
values (pg_temp.ws('70000000-0000-0000-0000-00000000000b'), pg_temp.id('eclair'), pg_temp.id('b_client'), 'owner',
gen_random_uuid(), '\x00') $$,
'23503', null, 'a relation claiming the other workspace is refused too (the animal is not there)');
select throws_ok(
$$ update public.animal_client_relations set client_id = pg_temp.id('b_client') where id = pg_temp.id('r_eclair_marie_owner') $$,
'23503', null, 'repointing a relation to a client of another workspace is refused');
select throws_ok(
$$ update public.animal_client_relations set workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000b')
where id = pg_temp.id('r_eclair_marie_owner') $$,
'23503', null, 'moving a relation to another workspace is refused');
select throws_ok(
$$ update public.animals set workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000b') where id = pg_temp.id('eclair') $$,
'23503', null, 'moving an animal that has relations to another workspace is refused');
select throws_ok(
$$ update public.clients set workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000b') where id = pg_temp.id('marie') $$,
'23503', null, 'moving a client that has relations to another workspace is refused');
select throws_ok(
$$ insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, create_request_id, create_request_digest)
values (pg_temp.wa(), pg_temp.id('eclair'), pg_temp.id('marie'), 'owner', gen_random_uuid(), '\x00') $$,
'23505', null, 'a second current identical relation is refused by the partial unique index');
select throws_ok(
$$ update public.animal_client_relations set ended_on = '2020-01-01' where id = pg_temp.id('r_eclair_marie_owner') $$,
'23514', null, 'an end date without an end is refused');
select throws_ok(
$$ update public.animal_client_relations set ended_at = now(), started_on = '2021-01-01', ended_on = '2020-01-01'
where id = pg_temp.id('r_eclair_marie_owner') $$,
'23514', null, 'an end before the start is refused');
select throws_ok(
$$ update public.animal_client_relations set started_on = '1899-12-31' where id = pg_temp.id('r_eclair_marie_owner') $$,
'23514', null, 'a start before 1900 is refused');
select throws_ok(
$$ update public.animals set birth_date = '2014-01-01' where id = pg_temp.id('eclair') $$,
'23514', null, 'a birth date out of its year is refused');
select throws_ok(
$$ update public.animals set birth_year = null where id = pg_temp.id('eclair') $$,
'23514', null, 'a birth date without its year is refused');
select throws_ok(
$$ update public.animals set species_detail = null where id = pg_temp.id('furet') $$,
'23514', null, 'other without detail is refused');
select throws_ok(
$$ update public.animals set species_id = 'unicorn' where id = pg_temp.id('rex') $$,
'23503', null, 'an unknown species is refused by the foreign key');
select throws_ok(
$$ delete from public.animals where id = pg_temp.id('eclair') $$,
'23503', null, 'an animal with relations cannot be deleted');
select throws_ok(
$$ delete from public.clients where id = pg_temp.id('lac') $$,
'23503', null, 'a client with relations cannot be deleted');
-- ---------------------------------------------------------------------------
-- 12. Account deletion (D9a)
-- ---------------------------------------------------------------------------
set local role authenticated;
select pg_temp.act_as('70000000-0000-0000-0000-000000000012');
select lives_ok($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-000000000012'), gen_random_uuid(), 'Seul', 'equine', 'male') $$,
'G creates one animal and no client');
reset role;
select throws_ok(
$$ delete from auth.users where id = '70000000-0000-0000-0000-000000000012' $$,
'23503', null, 'an account whose workspace holds an animal cannot be deleted (D9a)'
);
select is((select count(*) from public.animals where workspace_id = pg_temp.ws('70000000-0000-0000-0000-000000000012')), 1::bigint,
'its animal is intact');
select * from finish();
rollback;