feat(supabase): clients M2 with RPCs, search and per-workspace budget
V1-1.2 (contract V1-1_OWNERS_ANIMALS.md §5, §9, §10). public.clients (person or organization, display name only, optional contact, folded search keys), create/update/set_archived as definer RPCs (identical not_found, idempotent create with divergent-replay refusal, revisions, archive read-only), search_clients invoker with keyset pages and phone search, write budget per workspace in UTC hour/day windows under a row lock, 20 000-client cap, ids-only audit hidden from platform staff (N9), nothing for anon or service_role. pgTAP 013 (130), field-limits parity test, sandbox suite (concurrency, budget races, 20 000-client search), types regenerated.
This commit is contained in:
1 parent
2c0531d638
commit
4adbfcb608
9 files changed
+1916
-2
No files matched your search
@@ -0,0 +1,514 @@
|
||||
-- V1-1.2 Clients (M2): the clients of a workspace, written only through RPCs,
|
||||
-- read through RLS, searched through a POST RPC. Contract:
|
||||
-- docs/development/V1-1_OWNERS_ANIMALS.md §5 (text rules), §5.1 (fields),
|
||||
-- §8 (schema), §9 (helpers, RLS, RPCs, failures), §10 (limits), §13.2 (N2,
|
||||
-- N3, N6, N7, N9).
|
||||
--
|
||||
-- Invariants pinned by supabase/tests/013_clients.sql and the sandbox suite:
|
||||
-- * a client belongs to one workspace; only a member with a write role of
|
||||
-- an active, confirmed account writes it, through the four RPCs; every
|
||||
-- foreign or unknown id is answered with the same 42501 `not_found`;
|
||||
-- * a create is idempotent by (workspace, create_request_id); a replay
|
||||
-- with other content is refused (`request_conflict`), never applied;
|
||||
-- * an update needs the current revision; an archived client is read-only
|
||||
-- until restored;
|
||||
-- * writes are capped per workspace (20 000 clients; 1 000 audited writes
|
||||
-- per UTC hour, 5 000 per UTC day) under locks, so concurrent calls
|
||||
-- cannot pass a cap and a refused or replayed call consumes nothing;
|
||||
-- * audit rows carry ids only, and platform staff do not read them (N9).
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Text folding for search keys
|
||||
-- ---------------------------------------------------------------------------
|
||||
create extension if not exists unaccent with schema extensions;
|
||||
|
||||
-- Accents removed with the explicit dictionary, then ASCII lower case
|
||||
-- (collation "C"), so PGlite and the real image fold identically. Letters
|
||||
-- outside ASCII that unaccent keeps (Cyrillic, Greek) keep their case.
|
||||
-- Declared immutable for the generated columns: the dictionary is fixed by
|
||||
-- the extension version (contract §8).
|
||||
create or replace function private.fold_text(p_value text)
|
||||
returns text
|
||||
language sql
|
||||
immutable
|
||||
parallel safe
|
||||
set search_path = ''
|
||||
as $$
|
||||
select lower(extensions.unaccent('extensions.unaccent'::regdictionary, p_value) collate "C");
|
||||
$$;
|
||||
|
||||
comment on function private.fold_text(text) is
|
||||
'Search key folding: unaccent (explicit dictionary) then ASCII lower case. Used by generated columns and by search_clients.';
|
||||
|
||||
-- The text rule of contract §5: 1 to p_max characters (code points), no
|
||||
-- leading or trailing space, no control character of the explicit ranges.
|
||||
-- Null passes (an absent value is null, never an empty string).
|
||||
create or replace function private.is_clean_text(p_value text, p_max integer)
|
||||
returns boolean
|
||||
language sql
|
||||
immutable
|
||||
parallel safe
|
||||
set search_path = ''
|
||||
as $$
|
||||
select p_value is null
|
||||
or (char_length(p_value) between 1 and p_max
|
||||
and p_value = btrim(p_value)
|
||||
and p_value !~ '[\u0001-\u001f\u007f-\u009f\u2028\u2029]');
|
||||
$$;
|
||||
|
||||
comment on function private.is_clean_text(text, integer) is
|
||||
'Contract §5 text rule for CHECK constraints: length 1..p_max in code points, trimmed, no control character.';
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- clients
|
||||
-- ---------------------------------------------------------------------------
|
||||
create type public.client_kind as enum ('person', 'organization');
|
||||
|
||||
create table public.clients (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
-- restrict: an account whose workspace holds clients cannot be deleted (D9a).
|
||||
workspace_id uuid not null references public.workspaces (id) on delete restrict,
|
||||
kind public.client_kind not null,
|
||||
display_name text not null
|
||||
constraint clients_display_name_text check (private.is_clean_text(display_name, 120)),
|
||||
email text
|
||||
constraint clients_email_format check (
|
||||
private.is_clean_text(email, 254)
|
||||
and email = lower(email)
|
||||
and email ~ '^[^@\s]+@[^@\s]+\.[^@\s]+$'
|
||||
),
|
||||
phone text
|
||||
constraint clients_phone_e164 check (phone ~ '^\+[1-9][0-9]{6,14}$'),
|
||||
address_line1 text
|
||||
constraint clients_address_line1_text check (private.is_clean_text(address_line1, 120)),
|
||||
address_line2 text
|
||||
constraint clients_address_line2_text check (private.is_clean_text(address_line2, 120)),
|
||||
postal_code text
|
||||
constraint clients_postal_code_text check (private.is_clean_text(postal_code, 16)),
|
||||
city text
|
||||
constraint clients_city_text check (private.is_clean_text(city, 80)),
|
||||
country text
|
||||
constraint clients_country_code check (country ~ '^[A-Z]{2}$'),
|
||||
name_key text collate "C"
|
||||
generated always as (private.fold_text(display_name)) stored,
|
||||
search_key text collate "C"
|
||||
generated always as (
|
||||
private.fold_text(display_name || ' ' || coalesce(city, '') || ' ' || coalesce(email, ''))
|
||||
) stored,
|
||||
phone_digits text collate "C" generated always as (ltrim(phone, '+')) stored,
|
||||
-- Idempotency: the form sends one uuid per create attempt. The digest of the
|
||||
-- creation content tells a replay from a divergent reuse; never readable
|
||||
-- through the API.
|
||||
create_request_id uuid not null,
|
||||
create_request_digest bytea not null,
|
||||
revision integer not null default 1
|
||||
constraint clients_revision_positive check (revision >= 1),
|
||||
archived_at timestamptz,
|
||||
created_at timestamptz not null default now(),
|
||||
updated_at timestamptz not null default now(),
|
||||
constraint clients_workspace_id_unique unique (workspace_id, id),
|
||||
constraint clients_create_request_unique unique (workspace_id, create_request_id)
|
||||
);
|
||||
|
||||
comment on table public.clients is
|
||||
'Clients of a workspace (person or organization). Writes only through create_client, update_client, set_client_archived; reads through RLS and search_clients.';
|
||||
comment on column public.clients.display_name is
|
||||
'The single name reference (N2): display, search, sorting, documents.';
|
||||
|
||||
-- Workspace filter, name order, keyset pagination and the search scan.
|
||||
create index clients_workspace_name_idx on public.clients (workspace_id, name_key, id);
|
||||
|
||||
create trigger clients_set_updated_at
|
||||
before update on public.clients
|
||||
for each row execute function private.set_updated_at();
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Write budget per workspace (N6, owner decision on the counter)
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- One row per workspace, fixed UTC windows: the hour starting at hh:00:00 UTC
|
||||
-- and the day starting at 00:00:00 UTC. A window that has passed restarts at
|
||||
-- 1 on the next write. The row lock of the upsert serialises the writes of
|
||||
-- one workspace only; it is the last lock a write RPC takes, so no lock
|
||||
-- cycle can form. The counts are rolled back with any refused write.
|
||||
create table private.workspace_write_budgets (
|
||||
workspace_id uuid primary key references public.workspaces (id) on delete cascade,
|
||||
hour_start timestamptz not null,
|
||||
hour_count integer not null,
|
||||
day_start timestamptz not null,
|
||||
day_count integer not null
|
||||
);
|
||||
|
||||
comment on table private.workspace_write_budgets is
|
||||
'Audited writes per workspace in the current UTC hour and day (contract §10). Written only by private.consume_write_budget.';
|
||||
|
||||
create or replace function private.consume_write_budget(p_workspace_id uuid)
|
||||
returns void
|
||||
language plpgsql
|
||||
security definer
|
||||
set search_path = ''
|
||||
as $$
|
||||
declare
|
||||
v_hour timestamptz := date_trunc('hour', now(), 'UTC');
|
||||
v_day timestamptz := date_trunc('day', now(), 'UTC');
|
||||
v_hour_count integer;
|
||||
v_day_count integer;
|
||||
begin
|
||||
insert into private.workspace_write_budgets as b (workspace_id, hour_start, hour_count, day_start, day_count)
|
||||
values (p_workspace_id, v_hour, 1, v_day, 1)
|
||||
on conflict (workspace_id) do update set
|
||||
hour_count = case when b.hour_start = excluded.hour_start then b.hour_count + 1 else 1 end,
|
||||
hour_start = excluded.hour_start,
|
||||
day_count = case when b.day_start = excluded.day_start then b.day_count + 1 else 1 end,
|
||||
day_start = excluded.day_start
|
||||
returning b.hour_count, b.day_count into v_hour_count, v_day_count;
|
||||
|
||||
-- Raising undoes the increment with the rest of the refused write.
|
||||
if v_hour_count > 1000 or v_day_count > 5000 then
|
||||
raise exception 'rate_limited' using errcode = 'P0001';
|
||||
end if;
|
||||
end;
|
||||
$$;
|
||||
|
||||
comment on function private.consume_write_budget(uuid) is
|
||||
'Counts one audited write of the workspace in its UTC hour and day; raises rate_limited past 1 000 / 5 000. Call last, after the entity locks.';
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Write RPCs (contract §9.3). Each one: authorise and lock in one statement
|
||||
-- (no row = 42501 not_found, the same for a foreign and an unknown id), then
|
||||
-- archived, then revision, then rules; the budget last; one audit row with
|
||||
-- ids only; returns ids and revision.
|
||||
-- ---------------------------------------------------------------------------
|
||||
create or replace function public.create_client(
|
||||
workspace_id uuid,
|
||||
create_request_id uuid,
|
||||
kind text,
|
||||
display_name text,
|
||||
email text default null,
|
||||
phone text default null,
|
||||
address_line1 text default null,
|
||||
address_line2 text default null,
|
||||
postal_code text default null,
|
||||
city text default null,
|
||||
country text default null
|
||||
)
|
||||
returns jsonb
|
||||
language plpgsql
|
||||
volatile
|
||||
security definer
|
||||
set search_path = ''
|
||||
as $$
|
||||
#variable_conflict use_column
|
||||
declare
|
||||
v_kind public.client_kind;
|
||||
v_email text := lower(create_client.email);
|
||||
v_digest bytea;
|
||||
v_existing_id uuid;
|
||||
v_existing_revision integer;
|
||||
v_existing_digest bytea;
|
||||
v_id uuid;
|
||||
begin
|
||||
-- Serialises the creates of this workspace (replay check, cap, insert).
|
||||
perform 1 from public.workspaces w
|
||||
where w.id = create_client.workspace_id
|
||||
and w.id in (select private.writable_workspace_ids())
|
||||
for no key update;
|
||||
if not found then
|
||||
raise exception 'not_found' using errcode = '42501';
|
||||
end if;
|
||||
|
||||
begin
|
||||
v_kind := create_client.kind::public.client_kind;
|
||||
exception when invalid_text_representation then
|
||||
raise exception 'invalid_input' using errcode = 'P0001';
|
||||
end;
|
||||
v_digest := sha256(convert_to(jsonb_build_array(
|
||||
v_kind, create_client.display_name, v_email, create_client.phone,
|
||||
create_client.address_line1, create_client.address_line2,
|
||||
create_client.postal_code, create_client.city, create_client.country
|
||||
)::text, 'UTF8'));
|
||||
|
||||
select c.id, c.revision, c.create_request_digest
|
||||
into v_existing_id, v_existing_revision, v_existing_digest
|
||||
from public.clients c
|
||||
where c.workspace_id = create_client.workspace_id
|
||||
and c.create_request_id = create_client.create_request_id;
|
||||
if found then
|
||||
if v_existing_digest <> v_digest then
|
||||
raise exception 'request_conflict' using errcode = 'P0001';
|
||||
end if;
|
||||
return jsonb_build_object('id', v_existing_id, 'revision', v_existing_revision);
|
||||
end if;
|
||||
|
||||
if (select count(*) from public.clients c where c.workspace_id = create_client.workspace_id) >= 20000 then
|
||||
raise exception 'limit_reached' using errcode = 'P0001';
|
||||
end if;
|
||||
perform private.consume_write_budget(create_client.workspace_id);
|
||||
|
||||
begin
|
||||
insert into public.clients (
|
||||
workspace_id, kind, display_name, email, phone, address_line1, address_line2,
|
||||
postal_code, city, country, create_request_id, create_request_digest
|
||||
)
|
||||
values (
|
||||
create_client.workspace_id, v_kind, create_client.display_name, v_email, create_client.phone,
|
||||
create_client.address_line1, create_client.address_line2, create_client.postal_code,
|
||||
create_client.city, create_client.country, create_client.create_request_id, v_digest
|
||||
)
|
||||
returning id into v_id;
|
||||
exception when check_violation or not_null_violation or string_data_right_truncation
|
||||
or invalid_text_representation then
|
||||
raise exception 'invalid_input' using errcode = 'P0001';
|
||||
end;
|
||||
|
||||
perform private.log_event(
|
||||
auth.uid(), 'client.created', 'client', v_id, null, null,
|
||||
jsonb_build_object('workspace_id', create_client.workspace_id)
|
||||
);
|
||||
return jsonb_build_object('id', v_id, 'revision', 1);
|
||||
end;
|
||||
$$;
|
||||
|
||||
create or replace function public.update_client(
|
||||
client_id uuid,
|
||||
expected_revision integer,
|
||||
kind text,
|
||||
display_name text,
|
||||
email text,
|
||||
phone text,
|
||||
address_line1 text,
|
||||
address_line2 text,
|
||||
postal_code text,
|
||||
city text,
|
||||
country text
|
||||
)
|
||||
returns jsonb
|
||||
language plpgsql
|
||||
volatile
|
||||
security definer
|
||||
set search_path = ''
|
||||
as $$
|
||||
#variable_conflict use_column
|
||||
declare
|
||||
v_row public.clients;
|
||||
v_kind public.client_kind;
|
||||
v_email text := lower(update_client.email);
|
||||
begin
|
||||
select c.* into v_row
|
||||
from public.clients c
|
||||
where c.id = update_client.client_id
|
||||
and c.workspace_id in (select private.writable_workspace_ids())
|
||||
for update;
|
||||
if not found then
|
||||
raise exception 'not_found' using errcode = '42501';
|
||||
end if;
|
||||
if v_row.archived_at is not null then
|
||||
raise exception 'archived' using errcode = 'P0001';
|
||||
end if;
|
||||
if update_client.expected_revision is distinct from v_row.revision then
|
||||
raise exception 'conflict' using errcode = 'P0001';
|
||||
end if;
|
||||
|
||||
begin
|
||||
v_kind := update_client.kind::public.client_kind;
|
||||
exception when invalid_text_representation then
|
||||
raise exception 'invalid_input' using errcode = 'P0001';
|
||||
end;
|
||||
|
||||
-- No change: nothing written, nothing counted.
|
||||
if (v_kind, update_client.display_name, v_email, update_client.phone, update_client.address_line1,
|
||||
update_client.address_line2, update_client.postal_code, update_client.city, update_client.country)
|
||||
is not distinct from
|
||||
(v_row.kind, v_row.display_name, v_row.email, v_row.phone, v_row.address_line1,
|
||||
v_row.address_line2, v_row.postal_code, v_row.city, v_row.country) then
|
||||
return jsonb_build_object('revision', v_row.revision);
|
||||
end if;
|
||||
|
||||
perform private.consume_write_budget(v_row.workspace_id);
|
||||
begin
|
||||
update public.clients c
|
||||
set kind = v_kind, display_name = update_client.display_name, email = v_email,
|
||||
phone = update_client.phone, address_line1 = update_client.address_line1,
|
||||
address_line2 = update_client.address_line2, postal_code = update_client.postal_code,
|
||||
city = update_client.city, country = update_client.country,
|
||||
revision = c.revision + 1
|
||||
where c.id = v_row.id;
|
||||
exception when check_violation or not_null_violation or string_data_right_truncation
|
||||
or invalid_text_representation then
|
||||
raise exception 'invalid_input' using errcode = 'P0001';
|
||||
end;
|
||||
|
||||
perform private.log_event(
|
||||
auth.uid(), 'client.updated', 'client', v_row.id, null, null,
|
||||
jsonb_build_object('workspace_id', v_row.workspace_id)
|
||||
);
|
||||
return jsonb_build_object('revision', v_row.revision + 1);
|
||||
end;
|
||||
$$;
|
||||
|
||||
create or replace function public.set_client_archived(
|
||||
client_id uuid,
|
||||
archived boolean
|
||||
)
|
||||
returns jsonb
|
||||
language plpgsql
|
||||
volatile
|
||||
security definer
|
||||
set search_path = ''
|
||||
as $$
|
||||
#variable_conflict use_column
|
||||
declare
|
||||
v_row public.clients;
|
||||
begin
|
||||
select c.* into v_row
|
||||
from public.clients c
|
||||
where c.id = set_client_archived.client_id
|
||||
and c.workspace_id in (select private.writable_workspace_ids())
|
||||
for update;
|
||||
if not found then
|
||||
raise exception 'not_found' using errcode = '42501';
|
||||
end if;
|
||||
if set_client_archived.archived is null then
|
||||
raise exception 'invalid_input' using errcode = 'P0001';
|
||||
end if;
|
||||
-- Already in that state: nothing written, nothing counted.
|
||||
if (v_row.archived_at is not null) = set_client_archived.archived then
|
||||
return jsonb_build_object('revision', v_row.revision);
|
||||
end if;
|
||||
|
||||
perform private.consume_write_budget(v_row.workspace_id);
|
||||
update public.clients c
|
||||
set archived_at = case when set_client_archived.archived then now() end,
|
||||
revision = c.revision + 1
|
||||
where c.id = v_row.id;
|
||||
|
||||
perform private.log_event(
|
||||
auth.uid(),
|
||||
case when set_client_archived.archived then 'client.archived' else 'client.restored' end,
|
||||
'client', v_row.id, null, null,
|
||||
jsonb_build_object('workspace_id', v_row.workspace_id)
|
||||
);
|
||||
return jsonb_build_object('revision', v_row.revision + 1);
|
||||
end;
|
||||
$$;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Search (contract §9.3): security invoker, so RLS limits it to the caller's
|
||||
-- workspaces; a foreign workspace id returns no row. Called with POST, so the
|
||||
-- term and the cursor stay out of URLs.
|
||||
-- ---------------------------------------------------------------------------
|
||||
create or replace function public.search_clients(
|
||||
workspace_id uuid,
|
||||
query text default '',
|
||||
archived boolean default false,
|
||||
page_size integer default 25,
|
||||
after_name_key text default null,
|
||||
after_id uuid default null
|
||||
)
|
||||
returns table (
|
||||
id uuid,
|
||||
kind public.client_kind,
|
||||
display_name text,
|
||||
city text,
|
||||
phone text,
|
||||
email text,
|
||||
archived_at timestamptz,
|
||||
name_key text
|
||||
)
|
||||
language plpgsql
|
||||
stable
|
||||
security invoker
|
||||
set search_path = ''
|
||||
as $$
|
||||
#variable_conflict use_column
|
||||
declare
|
||||
v_term text := btrim(coalesce(search_clients.query, ''));
|
||||
v_pattern text;
|
||||
v_digits text;
|
||||
begin
|
||||
if char_length(v_term) > 100
|
||||
or search_clients.archived is null
|
||||
or search_clients.page_size is null
|
||||
or search_clients.page_size not between 1 and 100
|
||||
or (search_clients.after_name_key is null) <> (search_clients.after_id is null) then
|
||||
raise exception 'invalid_input' using errcode = 'P0001';
|
||||
end if;
|
||||
|
||||
-- Folded term inside search_key; LIKE wildcards escaped, backslash first.
|
||||
v_pattern := '%' || replace(replace(replace(private.fold_text(v_term), '\', '\\'), '%', '\%'), '_', '\_') || '%';
|
||||
-- A phone-like term (digits, spaces, dots, hyphens, +; at least 4 digits)
|
||||
-- is also looked for in phone_digits, without one leading 0.
|
||||
if v_term ~ '^[0-9 .+-]+$' and char_length(regexp_replace(v_term, '[^0-9]', '', 'g')) >= 4 then
|
||||
v_digits := regexp_replace(regexp_replace(v_term, '[^0-9]', '', 'g'), '^0', '');
|
||||
end if;
|
||||
|
||||
return query
|
||||
select c.id, c.kind, c.display_name, c.city, c.phone, c.email, c.archived_at, c.name_key
|
||||
from public.clients c
|
||||
where c.workspace_id = search_clients.workspace_id
|
||||
and (c.archived_at is not null) = search_clients.archived
|
||||
and (v_term = ''
|
||||
or c.search_key like v_pattern
|
||||
or (v_digits is not null and c.phone_digits like '%' || v_digits || '%'))
|
||||
and (search_clients.after_name_key is null
|
||||
or (c.name_key, c.id) > (search_clients.after_name_key collate "C", search_clients.after_id))
|
||||
order by c.name_key, c.id
|
||||
limit search_clients.page_size;
|
||||
end;
|
||||
$$;
|
||||
|
||||
comment on function public.create_client(uuid, uuid, text, text, text, text, text, text, text, text, text) is
|
||||
'Creates a client in a writable workspace; idempotent by create_request_id (divergent replay: request_conflict). Returns {id, revision}.';
|
||||
comment on function public.update_client(uuid, integer, text, text, text, text, text, text, text, text, text) is
|
||||
'Replaces the nine fields of an active client at expected_revision. Returns {revision}.';
|
||||
comment on function public.set_client_archived(uuid, boolean) is
|
||||
'Archives or restores a client (same state: no write). Returns {revision}.';
|
||||
comment on function public.search_clients(uuid, text, boolean, integer, text, uuid) is
|
||||
'Folded search (name, city, email; phone digits) in one workspace, keyset pages on (name_key, id), 25 by default, 100 at most.';
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Audit (N9): platform owners and admins keep reading platform events, not
|
||||
-- the activity of private records.
|
||||
-- ---------------------------------------------------------------------------
|
||||
alter policy audit_logs_select_admin on audit.audit_logs
|
||||
using (
|
||||
private.is_platform_admin((select auth.uid()))
|
||||
and split_part(action, '.', 1) not in ('client', 'animal', 'animal_client_relation')
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Privileges + RLS (N7: nothing for anon or service_role)
|
||||
-- ---------------------------------------------------------------------------
|
||||
revoke all on public.clients from public, anon, authenticated, service_role;
|
||||
grant select (
|
||||
id, workspace_id, kind, display_name, email, phone, address_line1, address_line2,
|
||||
postal_code, city, country, name_key, search_key, phone_digits, create_request_id,
|
||||
revision, archived_at, created_at, updated_at
|
||||
) on public.clients to authenticated;
|
||||
|
||||
alter table public.clients enable row level security;
|
||||
|
||||
create policy clients_select_member
|
||||
on public.clients
|
||||
for select
|
||||
to authenticated
|
||||
using (workspace_id in (select private.caller_workspace_ids()));
|
||||
|
||||
revoke all on private.workspace_write_budgets from public, anon, authenticated, service_role;
|
||||
|
||||
revoke all on function private.fold_text(text) from public, anon, authenticated, service_role;
|
||||
revoke all on function private.is_clean_text(text, integer) from public, anon, authenticated, service_role;
|
||||
revoke all on function private.consume_write_budget(uuid) from public, anon, authenticated, service_role;
|
||||
revoke all on function public.create_client(uuid, uuid, text, text, text, text, text, text, text, text, text)
|
||||
from public, anon, authenticated, service_role;
|
||||
revoke all on function public.update_client(uuid, integer, text, text, text, text, text, text, text, text, text)
|
||||
from public, anon, authenticated, service_role;
|
||||
revoke all on function public.set_client_archived(uuid, boolean) from public, anon, authenticated, service_role;
|
||||
revoke all on function public.search_clients(uuid, text, boolean, integer, text, uuid)
|
||||
from public, anon, authenticated, service_role;
|
||||
|
||||
grant execute on function public.create_client(uuid, uuid, text, text, text, text, text, text, text, text, text) to authenticated;
|
||||
grant execute on function public.update_client(uuid, integer, text, text, text, text, text, text, text, text, text) to authenticated;
|
||||
grant execute on function public.set_client_archived(uuid, boolean) to authenticated;
|
||||
grant execute on function public.search_clients(uuid, text, boolean, integer, text, uuid) to authenticated;
|
||||
-- The invoker search folds its term as the caller.
|
||||
grant execute on function private.fold_text(text) to authenticated;
|
||||
@@ -62,7 +62,7 @@ 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')),
|
||||
'caller_workspace_ids,can_edit_sheet,can_read_avatar_object,can_read_sheet_asset_object,can_upload_avatar_object,can_use_sheet,has_platform_role,is_platform_admin,is_platform_moderator,is_platform_owner,is_support',
|
||||
'caller_workspace_ids,can_edit_sheet,can_read_avatar_object,can_read_sheet_asset_object,can_upload_avatar_object,can_use_sheet,fold_text,has_platform_role,is_platform_admin,is_platform_moderator,is_platform_owner,is_support',
|
||||
'authenticated executes only the policy predicates in private'
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
-- V1-1.2 Clients (M2): fields and text rules, idempotent creates, revisions,
|
||||
-- archive, search, isolation between workspaces, refusals for every other
|
||||
-- actor, caps and write budget, minimised audit, privileges and census.
|
||||
-- Contract: docs/development/V1-1_OWNERS_ANIMALS.md §5, §9, §10, §12.1.
|
||||
-- Actors: A and B confirmed and active; C unconfirmed; D deactivated after
|
||||
-- creating a client; S a platform owner; E (cap) and F (budget) confirmed;
|
||||
-- G an account without clients.
|
||||
begin;
|
||||
select plan(130);
|
||||
|
||||
insert into auth.users (id, email, email_confirmed_at) values
|
||||
('60000000-0000-0000-0000-00000000000a', 'alice-cl@test.local', now()),
|
||||
('60000000-0000-0000-0000-00000000000b', 'bob-cl@test.local', now()),
|
||||
('60000000-0000-0000-0000-00000000000c', 'carol-cl@test.local', null),
|
||||
('60000000-0000-0000-0000-00000000000d', 'dave-cl@test.local', now()),
|
||||
('60000000-0000-0000-0000-000000000005', 'staff-cl@test.local', now()),
|
||||
('60000000-0000-0000-0000-00000000000e', 'cap-cl@test.local', now()),
|
||||
('60000000-0000-0000-0000-00000000000f', 'budget-cl@test.local', now()),
|
||||
('60000000-0000-0000-0000-000000000010', 'empty-cl@test.local', now());
|
||||
select private.assign_platform_role(null, '60000000-0000-0000-0000-000000000005', 'owner');
|
||||
|
||||
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.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 function pg_temp.client(p_id uuid) returns public.clients language sql stable security definer
|
||||
as $$ select c from public.clients c where c.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 $$;
|
||||
-- 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 ("Grant the required privileges ..."), PGlite does not.
|
||||
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 table pg_temp.ids (key text primary key, id uuid not null);
|
||||
grant all on pg_temp.ids to authenticated, anon, service_role;
|
||||
grant execute on function pg_temp.ws(uuid), pg_temp.act_as(uuid), pg_temp.client(uuid), pg_temp.budget(uuid),
|
||||
pg_temp.audit_count(uuid), pg_temp.err(text), pg_temp.denial(text) to authenticated, anon, service_role;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 1. Schema, privileges, census
|
||||
-- ---------------------------------------------------------------------------
|
||||
select has_table('public', 'clients', 'table public.clients exists');
|
||||
select ok((select relrowsecurity from pg_class where oid = 'public.clients'::regclass), 'RLS enabled on clients');
|
||||
select enum_has_labels('public', 'client_kind', array['person', 'organization'], 'client_kind: person, organization');
|
||||
select is((select tableowner::text from pg_tables where schemaname = 'public' and tablename = 'clients'), 'postgres', 'clients belongs to postgres');
|
||||
select is(
|
||||
(select count(*) from (values ('anon'), ('service_role')) r(role)
|
||||
cross join (values ('select'), ('insert'), ('update'), ('delete'), ('truncate'), ('references'), ('trigger')) p(priv)
|
||||
where has_table_privilege(r.role, 'public.clients', p.priv)),
|
||||
0::bigint, 'anon and service_role hold no privilege on clients'
|
||||
);
|
||||
select is(
|
||||
(select count(*) from (values ('insert'), ('update'), ('delete'), ('truncate'), ('references'), ('trigger')) p(priv)
|
||||
where has_table_privilege('authenticated', 'public.clients', p.priv)),
|
||||
0::bigint, 'authenticated holds no write privilege on clients'
|
||||
);
|
||||
select ok(has_column_privilege('authenticated', 'public.clients', 'display_name', 'select')
|
||||
and not has_column_privilege('authenticated', 'public.clients', 'create_request_digest', 'select'),
|
||||
'authenticated reads the record columns, never the request digest');
|
||||
select is(
|
||||
(select count(*) from (values ('anon'), ('authenticated'), ('service_role')) r(role)
|
||||
cross join (values ('select'), ('insert'), ('update'), ('delete')) p(priv)
|
||||
where has_table_privilege(r.role, 'private.workspace_write_budgets', p.priv)),
|
||||
0::bigint, 'no API role touches the budget table'
|
||||
);
|
||||
select is(
|
||||
(select string_agg(policyname || ':' || cmd || ':' || array_to_string(roles, '+'), ',')
|
||||
from pg_policies where schemaname = 'public' and tablename = 'clients'),
|
||||
'clients_select_member:SELECT:authenticated', 'one SELECT policy on clients, for authenticated'
|
||||
);
|
||||
select is(
|
||||
(select count(*) from pg_policies where schemaname = 'public' and tablename = 'clients'
|
||||
and (qual not like '%caller_workspace_ids()%' or qual like '%platform%')),
|
||||
0::bigint, 'the clients policy goes through caller_workspace_ids() and names no platform role'
|
||||
);
|
||||
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_client', 'update_client', 'set_client_archived', 'search_clients',
|
||||
'fold_text', 'is_clean_text', 'consume_write_budget')
|
||||
and p.proconfig = array['search_path=""'] and pg_get_userbyid(p.proowner) = 'postgres'),
|
||||
'consume_write_budget:definer,create_client:definer,fold_text:invoker,is_clean_text:invoker,search_clients:invoker,set_client_archived:definer,update_client: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_client', 'update_client', 'set_client_archived', 'search_clients',
|
||||
'fold_text', 'is_clean_text', 'consume_write_budget')
|
||||
and has_function_privilege(r.role, p.oid, 'execute')),
|
||||
'authenticated:create_client,authenticated:fold_text,authenticated:search_clients,authenticated:set_client_archived,authenticated:update_client',
|
||||
'EXECUTE: authenticated on the four RPCs and the fold; anon and service_role on none'
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 2. Creation by A: fields, normalisation, derived keys
|
||||
-- ---------------------------------------------------------------------------
|
||||
set local role authenticated;
|
||||
select pg_temp.act_as('60000000-0000-0000-0000-00000000000a');
|
||||
insert into pg_temp.ids values
|
||||
('lac', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000001',
|
||||
'organization', 'Écurie du Lac', 'contact@ecurie-lac.test', '+33612345678', '1 chemin du Lac', null, '69000', 'Lyon', 'FR') ->> 'id')::uuid),
|
||||
('marie', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000002',
|
||||
'person', 'Marie Dupont', 'MARIE@Example.TEST', null, null, null, null, 'Évian') ->> 'id')::uuid),
|
||||
('ab', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000003', 'organization', 'A_B Haras') ->> 'id')::uuid),
|
||||
('axb', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000004', 'organization', 'AxB Haras') ->> 'id')::uuid),
|
||||
('pct', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000005', 'person', '100% Cheval') ->> 'id')::uuid),
|
||||
('bsl', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000006', 'person', 'Back\slash') ->> 'id')::uuid);
|
||||
|
||||
select results_eq(
|
||||
$$ select kind::text, display_name, email, phone, city, country, revision, archived_at is null
|
||||
from public.clients where id = (select id from pg_temp.ids where key = 'lac') $$,
|
||||
$$ values ('organization'::text, 'Écurie du Lac'::text, 'contact@ecurie-lac.test'::text, '+33612345678'::text,
|
||||
'Lyon'::text, 'FR'::text, 1, true) $$,
|
||||
'A reads the created organization with revision 1'
|
||||
);
|
||||
select is((pg_temp.client((select id from pg_temp.ids where key = 'marie'))).email, 'marie@example.test', 'the email is stored lower-case');
|
||||
select is((pg_temp.client((select id from pg_temp.ids where key = 'lac'))).name_key, 'ecurie du lac', 'name_key folds accents and case');
|
||||
select is((pg_temp.client((select id from pg_temp.ids where key = 'lac'))).phone_digits, '33612345678', 'phone_digits drops the +');
|
||||
select is((pg_temp.client((select id from pg_temp.ids where key = 'ab'))).country, null, 'no country is set by default');
|
||||
select is((select count(*) from public.clients), 6::bigint, 'A reads its six clients');
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 3. Text rules: refused with the bare code, nothing echoed
|
||||
-- ---------------------------------------------------------------------------
|
||||
create function pg_temp.try_create(p_kind text, p_name text, p_email text default null, p_phone text default null,
|
||||
p_postal text default null, p_country text default null) returns text language sql
|
||||
as $$ select pg_temp.err(format(
|
||||
'select public.create_client(%L, gen_random_uuid(), %L, %L, %L, %L, null, null, %L, null, %L)',
|
||||
pg_temp.ws('60000000-0000-0000-0000-00000000000a'), p_kind, p_name, p_email, p_phone, p_postal, p_country)) $$;
|
||||
grant execute on function pg_temp.try_create(text, text, text, text, text, text) to authenticated;
|
||||
|
||||
select is(pg_temp.try_create('person', ''), 'P0001|invalid_input||', 'an empty name is refused');
|
||||
select is(pg_temp.try_create('person', null), 'P0001|invalid_input||', 'a missing name is refused');
|
||||
select is(pg_temp.try_create('person', ' Lead'), 'P0001|invalid_input||', 'a leading space is refused');
|
||||
select is(pg_temp.try_create('person', e'Tab\there'), 'P0001|invalid_input||', 'a tab (control character) is refused');
|
||||
select is(pg_temp.try_create('person', e'Line\u2028sep'), 'P0001|invalid_input||', 'U+2028 is refused');
|
||||
select is(pg_temp.try_create('person', e'C1\u0085'), 'P0001|invalid_input||', 'a C1 control (U+0085) is refused');
|
||||
select is(pg_temp.try_create('person', repeat('x', 121)), 'P0001|invalid_input||', '121 characters are refused');
|
||||
select is(pg_temp.try_create('person', repeat('é', 121)), 'P0001|invalid_input||', '121 accented characters (code points) are refused');
|
||||
select is(pg_temp.try_create('robot', 'Kind'), 'P0001|invalid_input||', 'an unknown kind is refused');
|
||||
select is(pg_temp.try_create(null, 'Kind'), 'P0001|invalid_input||', 'a missing kind is refused');
|
||||
select is(pg_temp.try_create('person', 'Mail', 'not-an-email'), 'P0001|invalid_input||', 'a malformed email is refused');
|
||||
select is(pg_temp.try_create('person', 'Mail', 'a b@c.test'), 'P0001|invalid_input||', 'an email with a space is refused');
|
||||
select is(pg_temp.try_create('person', 'Mail', repeat('a', 247) || '@ex.test'), 'P0001|invalid_input||', 'a 255-character email is refused');
|
||||
select is(pg_temp.try_create('person', 'Mail', repeat('a', 246) || '@ex.test'), 'no error', 'a 254-character email is accepted');
|
||||
select is(pg_temp.try_create('person', 'Phone', null, '0612345678'), 'P0001|invalid_input||', 'a national phone (not E.164) is refused');
|
||||
select is(pg_temp.try_create('person', 'Postal', null, null, repeat('9', 17)), 'P0001|invalid_input||', 'a 17-character postal code is refused');
|
||||
select is(pg_temp.try_create('person', 'Country', null, null, null, 'fr'), 'P0001|invalid_input||', 'a lower-case country code is refused');
|
||||
select is(pg_temp.try_create('person', 'Country', null, null, null, 'FRA'), 'P0001|invalid_input||', 'a three-letter country code is refused');
|
||||
select is(pg_temp.try_create('person', repeat('é', 120)), 'no error', '120 accented characters are accepted');
|
||||
select is((select count(*) from public.clients), 8::bigint, 'only the two valid creates were written');
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 4. Idempotent create: replay, normalised replay, divergent replay
|
||||
-- ---------------------------------------------------------------------------
|
||||
select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000a')), '8/8', 'eight writes counted so far');
|
||||
select is(
|
||||
(public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000002',
|
||||
'person', 'Marie Dupont', 'marie@example.test', null, null, null, null, 'Évian') ->> 'id')::uuid,
|
||||
(select id from pg_temp.ids where key = 'marie'),
|
||||
'a replay (email in another case) returns the first client'
|
||||
);
|
||||
select is(pg_temp.audit_count((select id from pg_temp.ids where key = 'marie')), 1::bigint, 'the replay writes no audit row');
|
||||
select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000a')), '8/8', 'the replay consumes no budget');
|
||||
select is(
|
||||
pg_temp.err($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000002',
|
||||
'person', 'Marie Durand') $$),
|
||||
'P0001|request_conflict||', 'the same request id with other content is refused'
|
||||
);
|
||||
select is((select count(*) from public.clients where display_name like 'Marie%'), 1::bigint, 'no divergent client was created');
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 5. Update, revision, archive
|
||||
-- ---------------------------------------------------------------------------
|
||||
select is(
|
||||
public.update_client((select id from pg_temp.ids where key = 'marie'), 1, 'person', 'Marie Dupont', 'marie@example.test',
|
||||
'+41791234567', null, null, '1800', 'Vevey', 'CH') ->> 'revision', '2', 'an update at the current revision gives revision 2');
|
||||
select is(
|
||||
pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'marie'), 1, 'person', 'Marie D.',
|
||||
null, null, null, null, null, null, null) $$),
|
||||
'P0001|conflict||', 'a stale revision is refused'
|
||||
);
|
||||
select is((pg_temp.client((select id from pg_temp.ids where key = 'marie'))).city, 'Vevey', 'the stale update overwrote nothing');
|
||||
select is(
|
||||
pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'marie'), null, 'person', 'Marie D.',
|
||||
null, null, null, null, null, null, null) $$),
|
||||
'P0001|conflict||', 'a missing revision is refused'
|
||||
);
|
||||
select is(
|
||||
public.update_client((select id from pg_temp.ids where key = 'marie'), 2, 'person', 'Marie Dupont', 'MARIE@example.test',
|
||||
'+41791234567', null, null, '1800', 'Vevey', 'CH') ->> 'revision', '2', 'an update that changes nothing keeps the revision');
|
||||
select is(pg_temp.audit_count((select id from pg_temp.ids where key = 'marie')), 2::bigint, 'and writes no audit row');
|
||||
select is(
|
||||
pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'marie'), 2, 'person', '',
|
||||
null, null, null, null, null, null, null) $$),
|
||||
'P0001|invalid_input||', 'an update breaking a rule is refused'
|
||||
);
|
||||
select is(public.set_client_archived((select id from pg_temp.ids where key = 'axb'), true) ->> 'revision', '2', 'archiving adds one revision');
|
||||
select ok((pg_temp.client((select id from pg_temp.ids where key = 'axb'))).archived_at is not null, 'the client is archived');
|
||||
select is(public.set_client_archived((select id from pg_temp.ids where key = 'axb'), true) ->> 'revision', '2', 'archiving again changes nothing');
|
||||
select is(
|
||||
pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'axb'), 1, 'organization', 'AxB',
|
||||
null, null, null, null, null, null, null) $$),
|
||||
'P0001|archived||', 'an archived client refuses edits, archived reported before the stale revision'
|
||||
);
|
||||
select is(pg_temp.err($$ select public.set_client_archived((select id from pg_temp.ids where key = 'axb'), null) $$),
|
||||
'P0001|invalid_input||', 'a missing archive state is refused');
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 6. Search: folding, escaping, phone formats, filters, keyset pages
|
||||
-- ---------------------------------------------------------------------------
|
||||
create function pg_temp.names(p_query text, 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.display_name, '|' order by s.ord), '')
|
||||
from public.search_clients(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), p_query, p_archived, p_size,
|
||||
p_after_key, p_after_id) with ordinality s(id, kind, display_name, city, phone, email,
|
||||
archived_at, name_key, ord) $$;
|
||||
grant execute on function pg_temp.names(text, boolean, integer, text, uuid) to authenticated;
|
||||
|
||||
select is(pg_temp.names(''), '100% Cheval|A_B Haras|Back\slash|Écurie du Lac|' || repeat('é', 120) || '|Mail|Marie Dupont',
|
||||
'an empty term lists the active clients in name order (archived left out)');
|
||||
select is(pg_temp.names('', true), 'AxB Haras', 'the archived filter lists the archived client only');
|
||||
select is(pg_temp.names('ECU'), 'Écurie du Lac', 'search folds case and accents');
|
||||
select is(pg_temp.names('vevey'), 'Marie Dupont', 'search reads the city');
|
||||
select is(pg_temp.names('EXAMPLE.test'), 'Marie Dupont', 'search reads the email');
|
||||
select is(pg_temp.names('_'), 'A_B Haras', 'an underscore is a character, not a wildcard');
|
||||
select is(pg_temp.names('%'), '100% Cheval', 'a percent sign is a character, not a wildcard');
|
||||
select is(pg_temp.names('\'), 'Back\slash', 'a backslash is a character');
|
||||
select is(pg_temp.names('06 12'), 'Écurie du Lac', 'a national phone fragment finds the number');
|
||||
select is(pg_temp.names('0612345678'), 'Écurie du Lac', 'a full national number finds it');
|
||||
select is(pg_temp.names('+33 6 12'), 'Écurie du Lac', 'an international fragment finds it');
|
||||
select is(pg_temp.names('061'), '', 'fewer than four digits is not a phone search');
|
||||
select is(pg_temp.names(repeat('z', 100)), '', 'a 100-character term is accepted');
|
||||
select is(pg_temp.names('', false, 2), '100% Cheval|A_B Haras', 'page 1 of 2');
|
||||
select is(pg_temp.names('', false, 2, (pg_temp.client((select id from pg_temp.ids where key = 'ab'))).name_key,
|
||||
(select id from pg_temp.ids where key = 'ab')), 'Back\slash|Écurie du Lac', 'page 2 continues after the cursor, no gap, no repeat');
|
||||
select is(pg_temp.names('', false, 2, (pg_temp.client((select id from pg_temp.ids where key = 'marie'))).name_key,
|
||||
(select id from pg_temp.ids where key = 'marie')), '', 'after the last client the page is empty');
|
||||
select is(pg_temp.err($$ select pg_temp.names(repeat('z', 101)) $$), 'P0001|invalid_input||', 'a 101-character term is refused');
|
||||
select is(pg_temp.err($$ select pg_temp.names('', false, 0) $$), 'P0001|invalid_input||', 'page size 0 is refused');
|
||||
select is(pg_temp.err($$ select pg_temp.names('', false, 101) $$), 'P0001|invalid_input||', 'page size 101 is refused');
|
||||
select is(pg_temp.err($$ select pg_temp.names('', false, 25, 'a') $$), 'P0001|invalid_input||', 'a cursor without its id is refused');
|
||||
select is(pg_temp.err($$ select pg_temp.names('', null) $$), 'P0001|invalid_input||', 'a missing archive filter is refused');
|
||||
|
||||
-- Restore: editable again, back in the default list.
|
||||
select is(public.set_client_archived((select id from pg_temp.ids where key = 'axb'), false) ->> 'revision', '3', 'restoring adds one revision');
|
||||
select is(public.update_client((select id from pg_temp.ids where key = 'axb'), 3, 'organization', 'AxB Haras', null, null,
|
||||
null, null, null, 'Annecy', null) ->> 'revision', '4', 'a restored client is editable');
|
||||
|
||||
-- D creates a client while active (used after its deactivation).
|
||||
select pg_temp.act_as('60000000-0000-0000-0000-00000000000d');
|
||||
insert into pg_temp.ids values ('dave', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000d'),
|
||||
gen_random_uuid(), 'person', 'Client de Dave') ->> 'id')::uuid);
|
||||
reset role;
|
||||
update public.profiles set active = false where id = '60000000-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('60000000-0000-0000-0000-00000000000b');
|
||||
select is((select count(*) from public.clients), 0::bigint, 'B reads no client');
|
||||
select is((select count(*) from public.clients where id = (select id from pg_temp.ids where key = 'lac')), 0::bigint,
|
||||
'B naming a client of A reads nothing');
|
||||
select is((select count(*) from public.search_clients(pg_temp.ws('60000000-0000-0000-0000-00000000000a'))), 0::bigint,
|
||||
'B searching the workspace of A finds nothing');
|
||||
select is(pg_temp.err($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), gen_random_uuid(), 'person', 'X') $$),
|
||||
pg_temp.err($$ select public.create_client(gen_random_uuid(), gen_random_uuid(), 'person', 'X') $$),
|
||||
'B creating in the workspace of A gets the error of an unknown workspace');
|
||||
select is(pg_temp.err($$ select public.create_client(gen_random_uuid(), gen_random_uuid(), 'person', 'X') $$),
|
||||
'42501|not_found||', 'that error is 42501 not_found, no detail, no hint');
|
||||
select is(pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'lac'), 1, 'person', 'X', null, null, null, null, null, null, null) $$),
|
||||
pg_temp.err($$ select public.update_client(gen_random_uuid(), 1, 'person', 'X', null, null, null, null, null, null, null) $$),
|
||||
'B updating a client of A gets the error of an unknown client');
|
||||
select is(pg_temp.err($$ select public.set_client_archived((select id from pg_temp.ids where key = 'lac'), true) $$),
|
||||
'42501|not_found||', 'B archiving a client of A gets not_found');
|
||||
select is(pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'lac'), 1, 'person', '', null, null, null, null, null, null, null) $$),
|
||||
'42501|not_found||', 'invalid content on a foreign id still answers not_found (authorisation first)');
|
||||
select is(pg_temp.denial($$ insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest)
|
||||
values (pg_temp.ws('60000000-0000-0000-0000-00000000000b'), 'person', 'Direct', gen_random_uuid(), '\x00') $$),
|
||||
'42501|permission denied for table clients', 'a direct insert is refused by privilege');
|
||||
select is(pg_temp.denial($$ update public.clients set display_name = 'Direct' $$),
|
||||
'42501|permission denied for table clients', 'a direct update is refused by privilege');
|
||||
select is(pg_temp.denial($$ delete from public.clients $$),
|
||||
'42501|permission denied for table clients', 'a direct delete is refused by privilege');
|
||||
|
||||
select pg_temp.act_as('60000000-0000-0000-0000-00000000000c');
|
||||
select is((select count(*) from public.clients), 0::bigint, 'C (unconfirmed) reads no client');
|
||||
select is(pg_temp.err($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000c'), gen_random_uuid(), 'person', 'X') $$),
|
||||
'42501|not_found||', 'C cannot create, even in its own workspace');
|
||||
|
||||
select pg_temp.act_as('60000000-0000-0000-0000-00000000000d');
|
||||
select is((select count(*) from public.clients), 0::bigint, 'D (deactivated) no longer reads its own client');
|
||||
select is((select count(*) from public.search_clients(pg_temp.ws('60000000-0000-0000-0000-00000000000d'))), 0::bigint,
|
||||
'D finds nothing through search');
|
||||
select is(pg_temp.err($$ select public.set_client_archived((select id from pg_temp.ids where key = 'dave'), true) $$),
|
||||
'42501|not_found||', 'D cannot write its own client');
|
||||
|
||||
select pg_temp.act_as('60000000-0000-0000-0000-000000000005');
|
||||
select is((select count(*) from public.clients), 0::bigint, 'S (platform owner) reads no client: no platform-role branch');
|
||||
select is(pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'lac'), 1, 'person', 'X', null, null, null, null, null, null, null) $$),
|
||||
'42501|not_found||', 'S cannot write a client of A');
|
||||
reset role;
|
||||
|
||||
set local role anon;
|
||||
select is(pg_temp.denial($$ select id from public.clients $$), '42501|permission denied for table clients', 'anon cannot read clients');
|
||||
select is(pg_temp.err($$ select public.create_client(gen_random_uuid(), gen_random_uuid(), 'person', 'X') $$),
|
||||
'42501|permission denied for function create_client||', 'anon cannot execute create_client');
|
||||
select is(pg_temp.err($$ select * from public.search_clients(gen_random_uuid()) $$),
|
||||
'42501|permission denied for function search_clients||', 'anon cannot execute search_clients');
|
||||
reset role;
|
||||
set local role service_role;
|
||||
select is(pg_temp.denial($$ select id from public.clients $$), '42501|permission denied for table clients',
|
||||
'service_role cannot read clients despite BYPASSRLS');
|
||||
select is(pg_temp.err($$ select public.update_client(gen_random_uuid(), 1, 'person', 'X', null, null, null, null, null, null, null) $$),
|
||||
'42501|permission denied for function update_client||', 'service_role cannot execute update_client');
|
||||
select is(pg_temp.err($$ select private.consume_write_budget(gen_random_uuid()) $$),
|
||||
'42501|permission denied for function consume_write_budget||', 'service_role cannot touch the budget');
|
||||
reset role;
|
||||
set local role authenticated;
|
||||
select pg_temp.act_as('60000000-0000-0000-0000-00000000000a');
|
||||
select is(pg_temp.err($$ select private.consume_write_budget(pg_temp.ws('60000000-0000-0000-0000-00000000000a')) $$),
|
||||
'42501|permission denied for function consume_write_budget||', 'A cannot call the budget directly');
|
||||
select is(pg_temp.err($$ select private.is_clean_text('x', 1) $$),
|
||||
'42501|permission denied for function is_clean_text||', 'A cannot call the text rule directly');
|
||||
reset role;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 8. Write budget per workspace (fixed UTC windows), refused writes not counted
|
||||
-- ---------------------------------------------------------------------------
|
||||
insert into private.workspace_write_budgets values
|
||||
(pg_temp.ws('60000000-0000-0000-0000-00000000000f'), date_trunc('hour', now(), 'UTC'), 999, date_trunc('day', now(), 'UTC'), 999);
|
||||
set local role authenticated;
|
||||
select pg_temp.act_as('60000000-0000-0000-0000-00000000000f');
|
||||
insert into pg_temp.ids values ('f1', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000f'),
|
||||
'62000000-0000-0000-0000-000000000001', 'person', 'Budget One') ->> 'id')::uuid);
|
||||
select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000f')), '1000/1000', 'the 1 000th write of the hour passes');
|
||||
select is(pg_temp.err($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000f'), gen_random_uuid(), 'person', 'Budget Two') $$),
|
||||
'P0001|rate_limited||', 'the 1 001st write of the hour is refused');
|
||||
select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000f')), '1000/1000', 'the refused write consumed nothing');
|
||||
select is((public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000f'), '62000000-0000-0000-0000-000000000001',
|
||||
'person', 'Budget One') ->> 'id')::uuid, (select id from pg_temp.ids where key = 'f1'), 'a replay at the limit still answers');
|
||||
select is(public.set_client_archived((select id from pg_temp.ids where key = 'f1'), false) ->> 'revision', '1',
|
||||
'a no-op at the limit still answers');
|
||||
select is(pg_temp.err($$ select public.set_client_archived((select id from pg_temp.ids where key = 'f1'), true) $$),
|
||||
'P0001|rate_limited||', 'an archive at the limit is refused');
|
||||
reset role;
|
||||
update private.workspace_write_budgets set hour_start = hour_start - interval '1 hour'
|
||||
where workspace_id = pg_temp.ws('60000000-0000-0000-0000-00000000000f');
|
||||
set local role authenticated;
|
||||
select pg_temp.act_as('60000000-0000-0000-0000-00000000000f');
|
||||
select lives_ok($$ select public.set_client_archived((select id from pg_temp.ids where key = 'f1'), true) $$,
|
||||
'a new UTC hour restarts the hourly count');
|
||||
select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000f')), '1/1001', 'hour restarted at 1, the day keeps counting');
|
||||
reset role;
|
||||
update private.workspace_write_budgets set day_count = 5000 where workspace_id = pg_temp.ws('60000000-0000-0000-0000-00000000000f');
|
||||
set local role authenticated;
|
||||
select pg_temp.act_as('60000000-0000-0000-0000-00000000000f');
|
||||
select is(pg_temp.err($$ select public.set_client_archived((select id from pg_temp.ids where key = 'f1'), false) $$),
|
||||
'P0001|rate_limited||', 'the 5 001st write of the UTC day is refused');
|
||||
select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000f')), '1/5000', 'and consumed nothing');
|
||||
select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000b')), 'none', 'the budget of another workspace is untouched');
|
||||
reset role;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 9. Cap: 20 000 clients per workspace
|
||||
-- ---------------------------------------------------------------------------
|
||||
insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest)
|
||||
select pg_temp.ws('60000000-0000-0000-0000-00000000000e'), 'person', 'Cap ' || g, gen_random_uuid(), '\x00'
|
||||
from generate_series(1, 19999) g;
|
||||
set local role authenticated;
|
||||
select pg_temp.act_as('60000000-0000-0000-0000-00000000000e');
|
||||
select lives_ok($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000e'),
|
||||
'63000000-0000-0000-0000-000000000001', 'person', 'Cap last') $$, 'the 20 000th client is accepted');
|
||||
select is(pg_temp.err($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000e'), gen_random_uuid(), 'person', 'Cap over') $$),
|
||||
'P0001|limit_reached||', 'the 20 001st client is refused');
|
||||
select lives_ok($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000e'),
|
||||
'63000000-0000-0000-0000-000000000001', 'person', 'Cap last') $$, 'a replay at the cap still answers');
|
||||
reset role;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 10. Audit: ids only, hidden from platform staff (N9)
|
||||
-- ---------------------------------------------------------------------------
|
||||
select is(
|
||||
(select string_agg(action, ',' order by occurred_at, action) from audit.audit_logs
|
||||
where resource_id = (select id from pg_temp.ids where key = 'axb')),
|
||||
'client.archived,client.created,client.restored,client.updated',
|
||||
'each write of a client leaves one audit row'
|
||||
);
|
||||
select is(
|
||||
(select count(*) from audit.audit_logs a join pg_temp.ids i on i.id = a.resource_id
|
||||
where a.metadata <> jsonb_build_object('workspace_id', pg_temp.ws('60000000-0000-0000-0000-00000000000a'))
|
||||
and i.key in ('lac', 'marie', 'ab', 'axb', 'pct', 'bsl')),
|
||||
0::bigint, 'audit metadata is the workspace id only'
|
||||
);
|
||||
select is(
|
||||
(select count(*) from audit.audit_logs a join pg_temp.ids i on i.id = a.resource_id
|
||||
where a.actor_user_id is distinct from '60000000-0000-0000-0000-00000000000a' and i.key in ('lac', 'marie', 'axb')),
|
||||
0::bigint, 'the actor is the caller'
|
||||
);
|
||||
select is(
|
||||
(select count(*) from audit.audit_logs where action like 'client.%'
|
||||
and (metadata::text ~* '(lac|marie|dupont|vevey|example|cheval|haras)' or correlation_id is not null)),
|
||||
0::bigint, 'no name, contact or place in the audit rows'
|
||||
);
|
||||
set local role authenticated;
|
||||
select pg_temp.act_as('60000000-0000-0000-0000-000000000005');
|
||||
select is((select count(*) from audit.audit_logs where action like 'client.%'), 0::bigint, 'S reads no client audit row');
|
||||
select ok((select count(*) from audit.audit_logs where action like 'platform_role.%') > 0, 'S still reads platform audit rows');
|
||||
reset role;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 11. Integrity and account deletion (D9a)
|
||||
-- ---------------------------------------------------------------------------
|
||||
select throws_ok(
|
||||
$$ insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest)
|
||||
values (gen_random_uuid(), 'person', 'Orphan', gen_random_uuid(), '\x00') $$,
|
||||
'23503', null, 'a client of an unknown workspace is refused by the foreign key'
|
||||
);
|
||||
select throws_ok(
|
||||
$$ insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest)
|
||||
values (pg_temp.ws('60000000-0000-0000-0000-00000000000a'), 'person', 'Twice', '61000000-0000-0000-0000-000000000001', '\x00') $$,
|
||||
'23505', null, 'a request id is unique per workspace'
|
||||
);
|
||||
select throws_ok(
|
||||
$$ delete from auth.users where id = '60000000-0000-0000-0000-00000000000a' $$,
|
||||
'23503', null, 'an account whose workspace holds clients cannot be deleted (D9a)'
|
||||
);
|
||||
select is((select count(*) from public.clients where workspace_id = pg_temp.ws('60000000-0000-0000-0000-00000000000a')),
|
||||
8::bigint, 'its clients are intact');
|
||||
select lives_ok($$ delete from auth.users where id = '60000000-0000-0000-0000-000000000010' $$,
|
||||
'an account without clients is deleted as before');
|
||||
|
||||
select * from finish();
|
||||
rollback;
|
||||
Reference in new issue
Block a user