fix: red-team round 3 hardening across desktop, mobile, core and server

Batch of red-team r3 fixes that were in the working tree before the
2026-09-28 design overhaul, committed as one unit with their tests.

- desktop main: STT timeouts and sidecar, voice recording store, sync
  (credentials, audio, knowledge reindex, push gates), runtime
  provisioner, update policy, AltGr keybindings, voice-command policy,
  dictionary file codec/limits, meeting transcript condensing and a
  local recording ledger so interrupted-session recovery only closes
  meetings this device recorded (a phone's live meeting is left alone).
- mobile: login CSRF via implicit token callbacks rejected, account
  deletion/retention, durable queue retention, knowledge realtime
  without unfiltered DELETE, meeting re-record failure paths, cloud STT
  client, preferences store/resync.
- core: text chunking splits long unbroken transcripts to fit, template
  field policy, dictionary limits, meeting markdown inline handling.
- server: payple webhook policy and cancellation order scope, meeting
  document generation quota, team RPC null-role guard, unified LLM
  quota in-flight accounting, knowledge chunk vector index, meeting
  re-record failure paths (migrations 20260929*).
- ci: portable/runtime feed gates, update-policy schema, Forgejo file
  delete and alias planning.

Four older tests are updated to the new contracts rather than the old
behavior: token-pair auth callbacks are rejected, knowledge realtime no
longer subscribes to DELETE, long transcript lines are split, and
meeting recovery requires the local recording ledger for empty rows.
This commit is contained in:
Yun Chan 2026-09-28 20:45:52 +09:00
parent 2428ede03d
commit ba9ef9741e
161 changed files with 17056 additions and 2379 deletions

View file

@ -0,0 +1,307 @@
\set ON_ERROR_STOP on
-- Regression for 20260929030000_knowledge_chunks_vector_index.sql.
-- match_knowledge_chunks must return the caller's exact top-k chunks (own
-- documents + documents of teams they belong to), even when other tenants own
-- almost every row of knowledge_chunks and the planner is pushed towards
-- index scans. Before the fix an IVFFlat index trained on an empty table was
-- scanned across all tenants with probes = 1 and filtered by tenant only
-- afterwards, so the caller usually got 0-1 rows although exact matches
-- existed.
BEGIN;
CREATE OR REPLACE FUNCTION pg_temp.assert_true(condition boolean, message text)
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
IF condition IS NOT TRUE THEN
RAISE EXCEPTION 'assertion_failed: %', message;
END IF;
END;
$$;
CREATE OR REPLACE FUNCTION pg_temp.act_as(uid uuid)
RETURNS void
LANGUAGE sql
AS $$
SELECT set_config(
'request.jwt.claims',
json_build_object('sub', uid, 'role', 'authenticated')::text,
true
);
$$;
-- Uniform random direction in [-1, 1]^1536 (deterministic after setseed).
CREATE OR REPLACE FUNCTION pg_temp.rand_vec()
RETURNS public.vector
LANGUAGE sql
VOLATILE
AS $$
SELECT array_agg(random() * 2 - 1 ORDER BY i)::public.vector
FROM generate_series(1, 1536) AS g(i);
$$;
-- base plus a small random perturbation (still very similar to base).
CREATE OR REPLACE FUNCTION pg_temp.near_vec(base public.vector, eps double precision)
RETURNS public.vector
LANGUAGE sql
VOLATILE
AS $$
SELECT array_agg(x + eps * (random() * 2 - 1) ORDER BY i)::public.vector
FROM unnest(base::real[]) WITH ORDINALITY AS t(x, i);
$$;
-- Ids returned by match_knowledge_chunks, in result order.
CREATE OR REPLACE FUNCTION pg_temp.match_ids(q public.vector, k integer, threshold double precision)
RETURNS uuid[]
LANGUAGE sql
VOLATILE
AS $$
SELECT coalesce(array_agg(m.id ORDER BY m.ord), ARRAY[]::uuid[])
FROM public.match_knowledge_chunks(q, k, threshold)
WITH ORDINALITY AS m(id, document_id, chunk_index, content, similarity, ord);
$$;
-- ── 0) the broken IVFFlat index is gone ──────────────────────────────────
SELECT pg_temp.assert_true(
NOT EXISTS (
SELECT 1 FROM pg_indexes
WHERE schemaname = 'public'
AND tablename = 'knowledge_chunks'
AND indexdef ILIKE '%ivfflat%'
),
'knowledge_chunks has no IVFFlat index trained on an empty table'
);
-- ── fixtures (as postgres) ───────────────────────────────────────────────
SELECT setseed(0.4242);
INSERT INTO auth.users (
id, aud, role, email, encrypted_password, email_confirmed_at,
raw_app_meta_data, raw_user_meta_data, created_at, updated_at
) VALUES
(
'39000000-0000-4000-8000-00000000000a', 'authenticated', 'authenticated',
'rag-searcher@example.invalid', crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{"name":"Searcher"}'::jsonb, now(), now()
),
(
'39000000-0000-4000-8000-00000000000b', 'authenticated', 'authenticated',
'rag-other-tenant@example.invalid', crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{"name":"Other"}'::jsonb, now(), now()
),
(
'39000000-0000-4000-8000-00000000000c', 'authenticated', 'authenticated',
'rag-teammate@example.invalid', crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{"name":"Teammate"}'::jsonb, now(), now()
);
-- Team T: searcher + teammate. Team T2: other tenant only.
INSERT INTO public.teams (id, name, owner_id) VALUES
('39100000-0000-4000-8000-00000000000a', 'RAG Team', '39000000-0000-4000-8000-00000000000c'),
('39100000-0000-4000-8000-00000000000b', 'Other Team', '39000000-0000-4000-8000-00000000000b');
INSERT INTO public.team_members (team_id, user_id, role) VALUES
('39100000-0000-4000-8000-00000000000a', '39000000-0000-4000-8000-00000000000c', 'owner'),
('39100000-0000-4000-8000-00000000000a', '39000000-0000-4000-8000-00000000000a', 'member'),
('39100000-0000-4000-8000-00000000000b', '39000000-0000-4000-8000-00000000000b', 'owner');
INSERT INTO public.knowledge_documents (id, user_id, team_id, title) VALUES
-- visible to the searcher
('39200000-0000-4000-8000-00000000000a', '39000000-0000-4000-8000-00000000000a', NULL,
'Searcher personal doc'),
('39200000-0000-4000-8000-00000000000c', '39000000-0000-4000-8000-00000000000c',
'39100000-0000-4000-8000-00000000000a', 'Teammate shared doc'),
-- invisible to the searcher
('39200000-0000-4000-8000-00000000000b', '39000000-0000-4000-8000-00000000000b', NULL,
'Other tenant personal doc'),
('39200000-0000-4000-8000-0000000000bb', '39000000-0000-4000-8000-00000000000b',
'39100000-0000-4000-8000-00000000000b', 'Other tenant team doc');
CREATE TEMP TABLE fixture_query ON COMMIT DROP AS
SELECT pg_temp.rand_vec() AS q;
GRANT SELECT ON fixture_query TO authenticated;
-- Searcher: 60 random chunks + chunk 60 identical to the query.
INSERT INTO public.knowledge_chunks (document_id, chunk_index, content, embedding)
SELECT '39200000-0000-4000-8000-00000000000a', g, 'searcher chunk ' || g, pg_temp.rand_vec()
FROM generate_series(0, 59) AS g;
INSERT INTO public.knowledge_chunks (id, document_id, chunk_index, content, embedding)
SELECT '39300000-0000-4000-8000-00000000000a', '39200000-0000-4000-8000-00000000000a', 60,
'searcher exact match', q
FROM fixture_query;
-- Team doc: 4 random chunks + one close to the query.
INSERT INTO public.knowledge_chunks (document_id, chunk_index, content, embedding)
SELECT '39200000-0000-4000-8000-00000000000c', g, 'team chunk ' || g, pg_temp.rand_vec()
FROM generate_series(0, 3) AS g;
INSERT INTO public.knowledge_chunks (id, document_id, chunk_index, content, embedding)
SELECT '39300000-0000-4000-8000-00000000000c', '39200000-0000-4000-8000-00000000000c', 4,
'team near match', pg_temp.near_vec(q, 0.05)
FROM fixture_query;
-- Other tenant owns almost the whole table, including an exact match of its
-- own and near matches in a team the searcher is not in.
INSERT INTO public.knowledge_chunks (document_id, chunk_index, content, embedding)
SELECT '39200000-0000-4000-8000-00000000000b', g, 'other chunk ' || g, pg_temp.rand_vec()
FROM generate_series(0, 1999) AS g;
INSERT INTO public.knowledge_chunks (id, document_id, chunk_index, content, embedding)
SELECT '39300000-0000-4000-8000-00000000000b', '39200000-0000-4000-8000-00000000000b', 2000,
'other exact match', q
FROM fixture_query;
INSERT INTO public.knowledge_chunks (document_id, chunk_index, content, embedding)
SELECT '39200000-0000-4000-8000-0000000000bb', g, 'other team near ' || g, pg_temp.near_vec(q, 0.02)
FROM fixture_query, generate_series(0, 9) AS g;
-- A chunk without an embedding must never be returned.
INSERT INTO public.knowledge_chunks (document_id, chunk_index, content)
VALUES ('39200000-0000-4000-8000-00000000000a', 61, 'searcher unembedded');
ANALYZE public.knowledge_chunks;
ANALYZE public.knowledge_documents;
-- Exact brute-force ranking over the searcher's visible chunks.
CREATE TEMP TABLE fixture_expected ON COMMIT DROP AS
SELECT
(SELECT array_agg(r.id ORDER BY r.distance, r.id) FROM (
SELECT kc.id, kc.embedding <=> f.q AS distance
FROM public.knowledge_chunks kc, fixture_query f
WHERE kc.embedding IS NOT NULL
AND kc.document_id IN ('39200000-0000-4000-8000-00000000000a',
'39200000-0000-4000-8000-00000000000c')
ORDER BY 2, 1
LIMIT 5
) r) AS top5,
(SELECT array_agg(r.id ORDER BY r.distance, r.id) FROM (
SELECT kc.id, kc.embedding <=> f.q AS distance
FROM public.knowledge_chunks kc, fixture_query f
WHERE kc.embedding IS NOT NULL
AND kc.document_id IN ('39200000-0000-4000-8000-00000000000a',
'39200000-0000-4000-8000-00000000000c')
ORDER BY 2, 1
LIMIT 20
) r) AS top20;
GRANT SELECT ON fixture_expected TO authenticated;
SELECT pg_temp.assert_true(
(SELECT top5[1:2] FROM fixture_expected)
= ARRAY['39300000-0000-4000-8000-00000000000a',
'39300000-0000-4000-8000-00000000000c']::uuid[],
'fixture sanity: exact match then team near match rank first'
);
-- ── 1) searcher gets the exact top-k of their visible chunks ─────────────
CREATE OR REPLACE FUNCTION pg_temp.assert_searcher_results(label text)
RETURNS void
LANGUAGE plpgsql
AS $$
DECLARE
q public.vector := (SELECT f.q FROM fixture_query f);
got uuid[];
BEGIN
got := pg_temp.match_ids(q, 5, -1);
PERFORM pg_temp.assert_true(
got = (SELECT top5 FROM fixture_expected),
format('%s: top-5 equals exact ranking (got %s)', label, got)
);
got := pg_temp.match_ids(q, 20, -1);
PERFORM pg_temp.assert_true(
got = (SELECT top20 FROM fixture_expected),
format('%s: top-20 equals exact ranking (got %s rows)', label, cardinality(got))
);
-- default threshold (0.5) as used by search-knowledge: only the two
-- planted matches qualify; the other tenant's exact/near matches never leak.
got := pg_temp.match_ids(q, 20, 0.5);
PERFORM pg_temp.assert_true(
got = ARRAY['39300000-0000-4000-8000-00000000000a',
'39300000-0000-4000-8000-00000000000c']::uuid[],
format('%s: threshold keeps only the caller''s planted matches (got %s)', label, got)
);
PERFORM pg_temp.assert_true(
NOT EXISTS (
SELECT 1 FROM public.match_knowledge_chunks(q, 50, -1) m
WHERE m.document_id NOT IN ('39200000-0000-4000-8000-00000000000a',
'39200000-0000-4000-8000-00000000000c')
OR m.content = 'searcher unembedded'
),
format('%s: only visible, embedded chunks are returned', label)
);
-- match_count is clamped: 66 visible embedded chunks, cap 50.
PERFORM pg_temp.assert_true(
cardinality(pg_temp.match_ids(q, 1000, -1)) = 50,
format('%s: match_count is capped at 50', label)
);
PERFORM pg_temp.assert_true(
cardinality(pg_temp.match_ids(q, NULL, -1)) = 5,
format('%s: NULL match_count falls back to 5 instead of unlimited', label)
);
PERFORM pg_temp.assert_true(
cardinality(pg_temp.match_ids(q, 0, -1)) = 0
AND cardinality(pg_temp.match_ids(q, -3, -1)) = 0,
format('%s: non-positive match_count returns nothing', label)
);
END;
$$;
SET LOCAL ROLE authenticated;
SELECT pg_temp.act_as('39000000-0000-4000-8000-00000000000a');
-- Push the planner towards index-ordered scans, the worst case for recall:
-- with seq scans and explicit sorts penalised, an ORDER BY distance LIMIT k
-- query is planned as an ANN index scan whenever one is available (what
-- happens in production once knowledge_chunks is large).
SET LOCAL enable_seqscan = off;
SET LOCAL enable_sort = off;
SELECT pg_temp.assert_searcher_results('no ANN index');
-- ── 2) still exact when an ANN index exists and is attractive ────────────
-- A properly trained IVFFlat index scanned with probes = 1 visits ~2% of all
-- rows across tenants. The function must not let the planner use it for the
-- ranking (the pre-fix shape did).
RESET ROLE;
CREATE INDEX knowledge_chunks_embedding_probe_test
ON public.knowledge_chunks
USING ivfflat (embedding public.vector_cosine_ops)
WITH (lists = 50);
SET LOCAL ivfflat.probes = 1;
SET LOCAL ROLE authenticated;
SELECT pg_temp.act_as('39000000-0000-4000-8000-00000000000a');
SELECT pg_temp.assert_searcher_results('trained IVFFlat index present');
-- ── 3) the other tenant sees only their own chunks ───────────────────────
SELECT pg_temp.act_as('39000000-0000-4000-8000-00000000000b');
SELECT pg_temp.assert_true(
(SELECT pg_temp.match_ids(f.q, 1, 0.5) FROM fixture_query f)
= ARRAY['39300000-0000-4000-8000-00000000000b']::uuid[],
'other tenant gets their own exact match first'
);
SELECT pg_temp.assert_true(
NOT EXISTS (
SELECT 1 FROM fixture_query f, public.match_knowledge_chunks(f.q, 50, -1) m
WHERE m.document_id NOT IN ('39200000-0000-4000-8000-00000000000b',
'39200000-0000-4000-8000-0000000000bb')
),
'other tenant never sees the searcher''s or team T''s chunks'
);
-- ── 4) anonymous callers get nothing ─────────────────────────────────────
SELECT set_config('request.jwt.claims', '', true);
SELECT pg_temp.assert_true(
(SELECT cardinality(pg_temp.match_ids(f.q, 50, -1)) FROM fixture_query f) = 0,
'caller without a user id sees no chunks'
);
ROLLBACK;

View file

@ -6,6 +6,13 @@
-- provider call before commit rejected N-1 of them. A 'processing' request now
-- holds one unit of the allowance until it is failed, committed or its lease
-- expires.
--
-- Regression (red-team r3-13, 20260929020000): the held unit lived in a second
-- ledger ('processing' rows) under a second advisory-lock key, so llm-proxy's
-- reserve_llm_quota could take the same last unit while a document was being
-- generated, and commit then threw the paid generation away with
-- generation_quota_exceeded. The claim now reserves through
-- reserve_llm_quota; commit/fail settle that reservation.
BEGIN;
@ -34,6 +41,26 @@ EXCEPTION WHEN OTHERS THEN
END;
$$;
-- Returns the commit payload, or {"error": SQLERRM} when the commit raises.
CREATE OR REPLACE FUNCTION pg_temp.try_commit(p_actor uuid, p_key uuid)
RETURNS jsonb
LANGUAGE plpgsql
AS $$
BEGIN
RETURN public.commit_meeting_document_generation_v1(p_actor, p_key, 'Generated body', 10, 1, 1);
EXCEPTION WHEN OTHERS THEN
RETURN jsonb_build_object('error', SQLERRM);
END;
$$;
CREATE OR REPLACE FUNCTION pg_temp.usage_today(p_actor uuid, p_feature text)
RETURNS integer
LANGUAGE sql
AS $$
SELECT coalesce(sum(count), 0)::integer FROM public.daily_usage
WHERE user_id = p_actor AND date = CURRENT_DATE AND feature = p_feature;
$$;
INSERT INTO auth.users (
id, aud, role, email, encrypted_password, email_confirmed_at,
raw_app_meta_data, raw_user_meta_data, created_at, updated_at
@ -47,19 +74,28 @@ INSERT INTO auth.users (
'37000000-0000-4000-8000-000000000002', 'authenticated', 'authenticated',
'meeting-doc-quota-unlimited@example.invalid', crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{}'::jsonb, now(), now()
),
(
'37000000-0000-4000-8000-000000000003', 'authenticated', 'authenticated',
'meeting-doc-quota-pro@example.invalid', crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{}'::jsonb, now(), now()
);
UPDATE public.subscriptions SET tier = 'free', status = 'active', overage_credits = 0
WHERE user_id = '37000000-0000-4000-8000-000000000001';
UPDATE public.subscriptions SET tier = 'pro_plus', status = 'active', overage_credits = 0
WHERE user_id = '37000000-0000-4000-8000-000000000002';
UPDATE public.subscriptions SET tier = 'pro', status = 'active', overage_credits = 0
WHERE user_id = '37000000-0000-4000-8000-000000000003';
INSERT INTO public.meetings (id, user_id, title, status, raw_transcript)
VALUES
('37100000-0000-4000-8000-000000000001', '37000000-0000-4000-8000-000000000001',
'Quota fixture meeting', 'completed', 'Speaker one talked about the roadmap.'),
('37100000-0000-4000-8000-000000000002', '37000000-0000-4000-8000-000000000002',
'Unlimited fixture meeting', 'completed', 'Speaker two talked about hiring.');
'Unlimited fixture meeting', 'completed', 'Speaker two talked about hiring.'),
('37100000-0000-4000-8000-000000000003', '37000000-0000-4000-8000-000000000003',
'Pro fixture meeting', 'completed', 'Speaker three talked about the launch.');
INSERT INTO public.user_templates (
id, user_id, template_kind, name, template_type, system_prompt, is_builtin
@ -67,7 +103,9 @@ INSERT INTO public.user_templates (
('37200000-0000-4000-8000-000000000001', '37000000-0000-4000-8000-000000000001',
'meeting_document', 'Quota fixture template', 'custom', 'Summarize the meeting.', false),
('37200000-0000-4000-8000-000000000002', '37000000-0000-4000-8000-000000000002',
'meeting_document', 'Unlimited fixture template', 'custom', 'Summarize the meeting.', false);
'meeting_document', 'Unlimited fixture template', 'custom', 'Summarize the meeting.', false),
('37200000-0000-4000-8000-000000000003', '37000000-0000-4000-8000-000000000003',
'meeting_document', 'Pro fixture template', 'custom', 'Summarize the meeting.', false);
-- One weekly Haiku unit left for the free user.
INSERT INTO public.daily_usage (user_id, date, feature, count)
@ -83,6 +121,7 @@ DECLARE
parallel jsonb;
replay jsonb;
after_release jsonb;
committed jsonb;
after_commit jsonb;
overage_claim jsonb;
overage_parallel jsonb;
@ -105,17 +144,21 @@ BEGIN
replay->>'error' IS NULL AND NOT (replay->>'claimed')::boolean AND replay->>'status' = 'processing',
'replaying the in-flight key reports processing: ' || replay::text
);
PERFORM pg_temp.assert_true(pg_temp.usage_today(actor, 'llm_haiku') = 250,
'a replay takes no additional unit');
-- A failed request releases the unit it held.
PERFORM public.fail_meeting_document_generation_v1(actor, '37300000-0000-4000-8000-000000000001', 'provider_timeout');
PERFORM pg_temp.assert_true(pg_temp.usage_today(actor, 'llm_haiku') = 249,
'failure gives the held unit back to the ledger');
after_release := pg_temp.try_claim(actor, '37300000-0000-4000-8000-000000000003', meeting, template, haiku);
PERFORM pg_temp.assert_true((after_release->>'claimed')::boolean,
'failure releases the in-flight unit: ' || after_release::text);
-- Commit converts the held unit into recorded usage; the allowance is spent.
PERFORM public.commit_meeting_document_generation_v1(
actor, '37300000-0000-4000-8000-000000000003', 'Generated body', 10, 1, 1
);
committed := pg_temp.try_commit(actor, '37300000-0000-4000-8000-000000000003');
PERFORM pg_temp.assert_true(committed->>'consumedFrom' = 'base',
'commit reports the unit the claim held: ' || committed::text);
SELECT count INTO usage_count FROM public.daily_usage
WHERE user_id = actor AND date = CURRENT_DATE AND feature = 'llm_haiku';
PERFORM pg_temp.assert_true(usage_count = 250, 'commit records exactly one unit');
@ -132,10 +175,13 @@ BEGIN
PERFORM pg_temp.assert_true(overage_parallel->>'error' = 'generation_quota_exceeded',
'a single overage credit is not spent twice by parallel claims: ' || overage_parallel::text);
-- A crashed request stops holding its unit once its lease expires.
UPDATE public.meeting_document_generation_requests
SET created_at = now() - interval '11 minutes'
WHERE user_id = actor AND idempotency_key = '37300000-0000-4000-8000-000000000005';
-- A crashed request stops holding its unit once its reservation lease expires.
UPDATE public.llm_quota_reservations AS reservation
SET lease_expires_at = now() - interval '1 minute'
FROM public.meeting_document_generation_requests AS request
WHERE request.user_id = actor
AND request.idempotency_key = '37300000-0000-4000-8000-000000000005'
AND reservation.id = request.llm_reservation_id;
after_lease := pg_temp.try_claim(actor, '37300000-0000-4000-8000-000000000007', meeting, template, haiku);
PERFORM pg_temp.assert_true((after_lease->>'claimed')::boolean,
'an expired in-flight lease no longer holds a unit: ' || after_lease::text);
@ -159,4 +205,146 @@ BEGIN
END;
$$;
-- Cross-path (r3-13): a meeting document and llm-proxy share one ledger.
DO $$
DECLARE
actor constant uuid := '37000000-0000-4000-8000-000000000003';
meeting constant uuid := '37100000-0000-4000-8000-000000000003';
template constant uuid := '37200000-0000-4000-8000-000000000003';
opus constant text := 'claude-opus-4-6';
claim jsonb;
proxy jsonb;
committed jsonb;
blocked jsonb;
legacy jsonb;
proxy_reservation constant uuid := '37600000-0000-4000-8000-000000000001';
credits integer;
BEGIN
-- One Opus unit left today (Pro: 50/day).
INSERT INTO public.daily_usage (user_id, date, feature, count)
VALUES (actor, CURRENT_DATE, 'llm_opus', 49);
-- 1) Document first, then a Talk/command request through llm-proxy.
claim := pg_temp.try_claim(actor, '37500000-0000-4000-8000-000000000001', meeting, template, opus);
PERFORM pg_temp.assert_true((claim->>'claimed')::boolean,
'the document claim takes the last Opus unit: ' || claim::text);
PERFORM pg_temp.assert_true(pg_temp.usage_today(actor, 'llm_opus') = 50,
'the claimed unit is visible in daily_usage while the provider call runs');
proxy := public.reserve_llm_quota(actor, gen_random_uuid(), 'llm_opus', 50, 'daily');
PERFORM pg_temp.assert_true((proxy->>'allowed')::boolean IS FALSE,
'llm-proxy cannot take the unit held by an in-flight document: ' || proxy::text);
PERFORM pg_temp.assert_true(
(SELECT count(*) FROM public.meeting_documents WHERE user_id = actor) = 0,
'no document exists before commit'
);
committed := pg_temp.try_commit(actor, '37500000-0000-4000-8000-000000000001');
PERFORM pg_temp.assert_true(
committed->>'error' IS NULL AND committed->>'consumedFrom' = 'base',
'the paid Opus generation is committed with the base unit the claim held: ' || committed::text
);
PERFORM pg_temp.assert_true(pg_temp.usage_today(actor, 'llm_opus') = 50,
'commit does not count the unit a second time');
-- consume_quota sees the same ledger.
PERFORM pg_temp.assert_true(
(public.consume_quota(actor, 'llm_opus', 50, 'daily')->>'allowed')::boolean IS FALSE,
'consume_quota counts document units'
);
-- 2) llm-proxy first, then a document: the claim sees the proxy's unit.
UPDATE public.daily_usage SET count = 49
WHERE user_id = actor AND date = CURRENT_DATE AND feature = 'llm_opus';
proxy := public.reserve_llm_quota(actor, proxy_reservation, 'llm_opus', 50, 'daily');
PERFORM pg_temp.assert_true((proxy->>'allowed')::boolean, 'llm-proxy takes the last unit');
blocked := pg_temp.try_claim(actor, '37500000-0000-4000-8000-000000000002', meeting, template, opus);
PERFORM pg_temp.assert_true(blocked->>'error' = 'generation_quota_exceeded',
'a document claim cannot take the unit held by llm-proxy: ' || blocked::text);
PERFORM public.finalize_llm_quota(proxy_reservation, false);
-- 3) Overage is taken at claim and refunded when the generation fails.
UPDATE public.daily_usage SET count = 50
WHERE user_id = actor AND date = CURRENT_DATE AND feature = 'llm_opus';
UPDATE public.subscriptions SET overage_credits = 1 WHERE user_id = actor;
claim := pg_temp.try_claim(actor, '37500000-0000-4000-8000-000000000003', meeting, template, opus);
PERFORM pg_temp.assert_true((claim->>'claimed')::boolean, 'an overage credit covers the claim');
SELECT overage_credits INTO credits FROM public.subscriptions WHERE user_id = actor;
PERFORM pg_temp.assert_true(credits = 0, 'the credit is held at claim time');
proxy := public.reserve_llm_quota(actor, gen_random_uuid(), 'llm_opus', 50, 'daily');
PERFORM pg_temp.assert_true((proxy->>'allowed')::boolean IS FALSE,
'llm-proxy cannot spend the credit held by an in-flight document');
PERFORM public.fail_meeting_document_generation_v1(actor, '37500000-0000-4000-8000-000000000003', 'provider_timeout');
SELECT overage_credits INTO credits FROM public.subscriptions WHERE user_id = actor;
PERFORM pg_temp.assert_true(credits = 1, 'a failed generation refunds the overage credit');
PERFORM pg_temp.assert_true(pg_temp.usage_today(actor, 'llm_opus') = 50,
'a failed generation gives its unit back');
-- 4) A row claimed before this migration (no reservation) is still charged
-- once, at commit, through the same ledger.
UPDATE public.daily_usage SET count = 49
WHERE user_id = actor AND date = CURRENT_DATE AND feature = 'llm_opus';
UPDATE public.subscriptions SET overage_credits = 0 WHERE user_id = actor;
claim := pg_temp.try_claim(actor, '37500000-0000-4000-8000-000000000004', meeting, template, opus);
PERFORM pg_temp.assert_true((claim->>'claimed')::boolean, 'legacy fixture claim');
-- Simulate the pre-migration shape: no reservation, unit not in daily_usage.
PERFORM public.finalize_llm_quota(
(SELECT llm_reservation_id FROM public.meeting_document_generation_requests
WHERE user_id = actor AND idempotency_key = '37500000-0000-4000-8000-000000000004'),
false
);
UPDATE public.meeting_document_generation_requests SET llm_reservation_id = NULL
WHERE user_id = actor AND idempotency_key = '37500000-0000-4000-8000-000000000004';
legacy := pg_temp.try_commit(actor, '37500000-0000-4000-8000-000000000004');
PERFORM pg_temp.assert_true(legacy->>'consumedFrom' = 'base',
'a legacy in-flight row is charged at commit: ' || legacy::text);
PERFORM pg_temp.assert_true(pg_temp.usage_today(actor, 'llm_opus') = 50,
'a legacy commit charges exactly one unit');
PERFORM pg_temp.assert_true(
(SELECT llm_reservation_id IS NOT NULL FROM public.meeting_document_generation_requests
WHERE user_id = actor AND idempotency_key = '37500000-0000-4000-8000-000000000004'),
'the legacy commit records the reservation that charged it'
);
END;
$$;
-- One lock key for the whole ledger: every quota path takes it through
-- daily_usage_lock_v1 and no quota function hardcodes an advisory-lock key.
-- (fail_meeting_document_generation_v1 locks inside finalize_llm_quota.)
DO $$
DECLARE
offenders text;
BEGIN
SELECT string_agg(p.proname, ', ' ORDER BY p.proname)
INTO offenders
FROM pg_proc AS p
JOIN pg_namespace AS n ON n.oid = p.pronamespace
WHERE n.nspname = 'public'
AND p.proname IN (
'reserve_llm_quota', 'finalize_llm_quota', 'consume_quota',
'claim_meeting_document_generation_v1', 'commit_meeting_document_generation_v1',
'fail_meeting_document_generation_v1'
)
AND (
p.prosrc LIKE '%pg_advisory%'
OR (
p.proname <> 'fail_meeting_document_generation_v1'
AND p.prosrc NOT LIKE '%daily_usage_lock_v1%'
)
OR (
p.proname = 'fail_meeting_document_generation_v1'
AND p.prosrc NOT LIKE '%finalize_llm_quota%'
)
);
PERFORM pg_temp.assert_true(offenders IS NULL,
'quota functions must lock only through daily_usage_lock_v1: ' || coalesce(offenders, ''));
PERFORM pg_temp.assert_true(
NOT has_function_privilege('anon', 'public.daily_usage_lock_v1(uuid, text)', 'EXECUTE')
AND NOT has_function_privilege('authenticated', 'public.daily_usage_lock_v1(uuid, text)', 'EXECUTE'),
'the ledger lock is not callable by clients'
);
END;
$$;
ROLLBACK;

View file

@ -0,0 +1,341 @@
\set ON_ERROR_STOP on
-- Regression (red-team r3-10): meeting-document claims and llm-proxy
-- reservations used two separate quota ledgers. A claim held its unit only as
-- a 'processing' row in meeting_document_generation_requests (advisory lock
-- seed 0), while reserve_llm_quota counted only daily_usage (seed 20260928).
-- An llm-proxy request could therefore take the unit a running document
-- generation already held; the document was paid for and then rejected by
-- commit with generation_quota_exceeded.
--
-- Since 20260929020000_unify_llm_quota_inflight a claim takes a
-- reserve_llm_quota lease, so both paths share one ledger (daily_usage +
-- llm_quota_reservations) and one lock (daily_usage_lock_v1). This file covers
-- the cross-path interleavings (document <-> llm-proxy in both orders, a mixed
-- burst at the limit, late commit after lease reclaim, legacy claims);
-- meeting-document-generation-quota.integration.sql covers the single path.
--
-- Local only: psql against the local Supabase stack. Runs in a transaction and
-- rolls back.
BEGIN;
CREATE OR REPLACE FUNCTION pg_temp.assert_true(condition boolean, message text)
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
IF condition IS NOT TRUE THEN
RAISE EXCEPTION 'assertion_failed: %', message;
END IF;
END;
$$;
-- Returns the claim payload, or {"error": SQLERRM} when the claim raises.
CREATE OR REPLACE FUNCTION pg_temp.try_claim(p_actor uuid, p_key uuid, p_meeting uuid, p_template uuid, p_model text)
RETURNS jsonb
LANGUAGE plpgsql
AS $$
BEGIN
RETURN public.claim_meeting_document_generation_v1(
p_actor, p_key, p_meeting, p_template, 'Lease fixture document', p_model
);
EXCEPTION WHEN OTHERS THEN
RETURN jsonb_build_object('error', SQLERRM);
END;
$$;
-- Returns the commit payload, or {"error": SQLERRM} when the commit raises.
CREATE OR REPLACE FUNCTION pg_temp.try_commit(p_actor uuid, p_key uuid)
RETURNS jsonb
LANGUAGE plpgsql
AS $$
BEGIN
RETURN public.commit_meeting_document_generation_v1(p_actor, p_key, 'Generated body', 10, 1, 1);
EXCEPTION WHEN OTHERS THEN
RETURN jsonb_build_object('error', SQLERRM);
END;
$$;
CREATE OR REPLACE FUNCTION pg_temp.usage_of(p_actor uuid, p_feature text)
RETURNS integer
LANGUAGE sql
AS $$
SELECT coalesce(sum(count), 0)::integer FROM public.daily_usage
WHERE user_id = p_actor AND feature = p_feature AND date = CURRENT_DATE;
$$;
INSERT INTO auth.users (
id, aud, role, email, encrypted_password, email_confirmed_at,
raw_app_meta_data, raw_user_meta_data, created_at, updated_at
) VALUES
(
'38000000-0000-4000-8000-000000000001', 'authenticated', 'authenticated',
'meeting-doc-lease-pro@example.invalid', crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{}'::jsonb, now(), now()
),
(
'38000000-0000-4000-8000-000000000002', 'authenticated', 'authenticated',
'meeting-doc-lease-free@example.invalid', crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{}'::jsonb, now(), now()
),
(
'38000000-0000-4000-8000-000000000003', 'authenticated', 'authenticated',
'meeting-doc-lease-unlimited@example.invalid', crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{}'::jsonb, now(), now()
);
UPDATE public.subscriptions SET tier = 'pro', status = 'active', overage_credits = 0
WHERE user_id = '38000000-0000-4000-8000-000000000001';
UPDATE public.subscriptions SET tier = 'free', status = 'active', overage_credits = 0
WHERE user_id = '38000000-0000-4000-8000-000000000002';
UPDATE public.subscriptions SET tier = 'pro_plus', status = 'active', overage_credits = 0
WHERE user_id = '38000000-0000-4000-8000-000000000003';
INSERT INTO public.meetings (id, user_id, title, status, raw_transcript)
VALUES
('38100000-0000-4000-8000-000000000001', '38000000-0000-4000-8000-000000000001',
'Lease fixture meeting', 'completed', 'Speaker one talked about the roadmap.'),
('38100000-0000-4000-8000-000000000002', '38000000-0000-4000-8000-000000000002',
'Lease fixture meeting', 'completed', 'Speaker two talked about hiring.'),
('38100000-0000-4000-8000-000000000003', '38000000-0000-4000-8000-000000000003',
'Lease fixture meeting', 'completed', 'Speaker three talked about budgets.');
INSERT INTO public.user_templates (
id, user_id, template_kind, name, template_type, system_prompt, is_builtin
) VALUES
('38200000-0000-4000-8000-000000000001', '38000000-0000-4000-8000-000000000001',
'meeting_document', 'Lease fixture template', 'custom', 'Summarize the meeting.', false),
('38200000-0000-4000-8000-000000000002', '38000000-0000-4000-8000-000000000002',
'meeting_document', 'Lease fixture template', 'custom', 'Summarize the meeting.', false),
('38200000-0000-4000-8000-000000000003', '38000000-0000-4000-8000-000000000003',
'meeting_document', 'Lease fixture template', 'custom', 'Summarize the meeting.', false);
-- Pro user, one daily Opus unit left (49/50).
INSERT INTO public.daily_usage (user_id, date, feature, count)
VALUES ('38000000-0000-4000-8000-000000000001', CURRENT_DATE, 'llm_opus', 49);
-- 1. A running document holds the last unit against llm-proxy, and its commit
-- is not thrown away afterwards (the reported bug).
DO $$
DECLARE
actor constant uuid := '38000000-0000-4000-8000-000000000001';
meeting constant uuid := '38100000-0000-4000-8000-000000000001';
template constant uuid := '38200000-0000-4000-8000-000000000001';
opus constant text := 'claude-opus-4-6';
claim jsonb;
proxy jsonb;
committed jsonb;
request_row public.meeting_document_generation_requests;
BEGIN
claim := pg_temp.try_claim(actor, '38300000-0000-4000-8000-000000000001', meeting, template, opus);
PERFORM pg_temp.assert_true((claim->>'claimed')::boolean, 'last Opus unit can be claimed: ' || claim::text);
SELECT * INTO request_row FROM public.meeting_document_generation_requests
WHERE user_id = actor AND idempotency_key = '38300000-0000-4000-8000-000000000001';
PERFORM pg_temp.assert_true(request_row.llm_reservation_id IS NOT NULL,
'the claim records the LLM quota lease it holds');
PERFORM pg_temp.assert_true(pg_temp.usage_of(actor, 'llm_opus') = 50,
'the in-flight claim is visible in the shared ledger');
-- The bug: llm-proxy used to see 49/50 here and reserve a second paid call.
proxy := public.reserve_llm_quota(actor, gen_random_uuid(), 'llm_opus', 50, 'daily');
PERFORM pg_temp.assert_true(NOT (proxy->>'allowed')::boolean,
'llm-proxy cannot take the unit a running document holds: ' || proxy::text);
committed := pg_temp.try_commit(actor, '38300000-0000-4000-8000-000000000001');
PERFORM pg_temp.assert_true(committed->>'error' IS NULL AND committed->'document' IS NOT NULL,
'the paid document is committed, not rejected: ' || committed::text);
PERFORM pg_temp.assert_true(committed->>'consumedFrom' = 'base', 'commit reports the base allowance');
PERFORM pg_temp.assert_true(pg_temp.usage_of(actor, 'llm_opus') = 50,
'commit completes the lease without charging a second unit');
PERFORM pg_temp.assert_true(
(SELECT status FROM public.llm_quota_reservations WHERE id = request_row.llm_reservation_id) = 'completed',
'commit completes the lease');
-- Idempotent commit replay does not charge again.
committed := pg_temp.try_commit(actor, '38300000-0000-4000-8000-000000000001');
PERFORM pg_temp.assert_true((committed->>'idempotent')::boolean, 'commit replay is idempotent');
PERFORM pg_temp.assert_true(pg_temp.usage_of(actor, 'llm_opus') = 50, 'commit replay charges nothing');
END;
$$;
-- 2. The reverse order: an llm-proxy reservation holds the last unit, so the
-- document claim is rejected before any provider work.
UPDATE public.daily_usage SET count = 49
WHERE user_id = '38000000-0000-4000-8000-000000000001' AND date = CURRENT_DATE AND feature = 'llm_opus';
DO $$
DECLARE
actor constant uuid := '38000000-0000-4000-8000-000000000001';
meeting constant uuid := '38100000-0000-4000-8000-000000000001';
template constant uuid := '38200000-0000-4000-8000-000000000001';
proxy_id constant uuid := '38500000-0000-4000-8000-000000000001';
proxy jsonb;
claim jsonb;
BEGIN
proxy := public.reserve_llm_quota(actor, proxy_id, 'llm_opus', 50, 'daily');
PERFORM pg_temp.assert_true((proxy->>'allowed')::boolean, 'llm-proxy takes the last unit');
claim := pg_temp.try_claim(actor, '38300000-0000-4000-8000-000000000002', meeting, template, 'claude-opus-4-6');
PERFORM pg_temp.assert_true(claim->>'error' = 'generation_quota_exceeded',
'a document claim cannot take the unit llm-proxy holds: ' || claim::text);
PERFORM pg_temp.assert_true(NOT EXISTS (
SELECT 1 FROM public.meeting_document_generation_requests
WHERE user_id = actor AND idempotency_key = '38300000-0000-4000-8000-000000000002'
), 'a rejected claim leaves no request row');
-- Once llm-proxy releases its lease, the document can be claimed.
PERFORM public.finalize_llm_quota(proxy_id, false);
claim := pg_temp.try_claim(actor, '38300000-0000-4000-8000-000000000002', meeting, template, 'claude-opus-4-6');
PERFORM pg_temp.assert_true((claim->>'claimed')::boolean, 'released unit can be claimed: ' || claim::text);
-- Replaying the in-flight key neither reserves again nor errors.
claim := pg_temp.try_claim(actor, '38300000-0000-4000-8000-000000000002', meeting, template, 'claude-opus-4-6');
PERFORM pg_temp.assert_true(
claim->>'error' IS NULL AND NOT (claim->>'claimed')::boolean AND claim->>'status' = 'processing',
'replaying the in-flight key reports processing: ' || claim::text);
PERFORM pg_temp.assert_true(pg_temp.usage_of(actor, 'llm_opus') = 50, 'a replay holds no extra unit');
-- Failure releases the unit back to the shared ledger, once.
PERFORM public.fail_meeting_document_generation_v1(actor, '38300000-0000-4000-8000-000000000002', 'provider_timeout');
PERFORM public.fail_meeting_document_generation_v1(actor, '38300000-0000-4000-8000-000000000002', 'provider_timeout');
PERFORM pg_temp.assert_true(pg_temp.usage_of(actor, 'llm_opus') = 49,
'failing a claim releases exactly one unit');
proxy := public.reserve_llm_quota(actor, gen_random_uuid(), 'llm_opus', 50, 'daily');
PERFORM pg_temp.assert_true((proxy->>'allowed')::boolean, 'the released unit is usable by llm-proxy');
END;
$$;
-- 3. Interleaved burst: document claims and llm-proxy reservations together
-- never exceed the remaining allowance, and one overage credit is spent once.
UPDATE public.daily_usage SET count = 45
WHERE user_id = '38000000-0000-4000-8000-000000000001' AND date = CURRENT_DATE AND feature = 'llm_opus';
UPDATE public.llm_quota_reservations SET status = 'completed'
WHERE user_id = '38000000-0000-4000-8000-000000000001' AND status = 'reserved';
UPDATE public.subscriptions SET overage_credits = 1
WHERE user_id = '38000000-0000-4000-8000-000000000001';
DO $$
DECLARE
actor constant uuid := '38000000-0000-4000-8000-000000000001';
meeting constant uuid := '38100000-0000-4000-8000-000000000001';
template constant uuid := '38200000-0000-4000-8000-000000000001';
granted integer := 0;
outcome jsonb;
i integer;
BEGIN
FOR i IN 1..10 LOOP
IF i % 2 = 0 THEN
outcome := public.reserve_llm_quota(actor, gen_random_uuid(), 'llm_opus', 50, 'daily');
IF (outcome->>'allowed')::boolean THEN granted := granted + 1; END IF;
ELSE
outcome := pg_temp.try_claim(actor, gen_random_uuid(), meeting, template, 'claude-opus-4-6');
IF coalesce((outcome->>'claimed')::boolean, false) THEN granted := granted + 1; END IF;
END IF;
END LOOP;
PERFORM pg_temp.assert_true(granted = 6,
'5 base units + 1 overage credit admit exactly 6 paid calls, got ' || granted);
PERFORM pg_temp.assert_true(pg_temp.usage_of(actor, 'llm_opus') = 51, 'shared ledger records every admitted call');
PERFORM pg_temp.assert_true(
(SELECT overage_credits FROM public.subscriptions WHERE user_id = actor) = 0,
'the overage credit is spent once');
END;
$$;
-- 4. Lease handling: an expired claim lease stops holding its unit, and a late
-- commit re-checks the allowance instead of charging past it.
DO $$
DECLARE
actor constant uuid := '38000000-0000-4000-8000-000000000002';
meeting constant uuid := '38100000-0000-4000-8000-000000000002';
template constant uuid := '38200000-0000-4000-8000-000000000002';
haiku constant text := 'claude-haiku-4-5-20251001';
claim jsonb;
proxy jsonb;
committed jsonb;
late_id uuid;
BEGIN
INSERT INTO public.daily_usage (user_id, date, feature, count)
VALUES (actor, CURRENT_DATE - 3, 'llm_haiku', 249);
claim := pg_temp.try_claim(actor, '38300000-0000-4000-8000-000000000010', meeting, template, haiku);
PERFORM pg_temp.assert_true((claim->>'claimed')::boolean, 'last weekly Haiku unit can be claimed');
-- Crashed worker: its lease expires, and the next reservation reclaims it.
SELECT llm_reservation_id INTO late_id FROM public.meeting_document_generation_requests
WHERE user_id = actor AND idempotency_key = '38300000-0000-4000-8000-000000000010';
UPDATE public.llm_quota_reservations SET lease_expires_at = now() - interval '1 minute' WHERE id = late_id;
proxy := public.reserve_llm_quota(actor, gen_random_uuid(), 'llm_haiku', 250, 'weekly');
PERFORM pg_temp.assert_true((proxy->>'allowed')::boolean,
'an expired document lease no longer holds a unit: ' || proxy::text);
-- The late commit finds its lease released and the allowance spent: reject
-- rather than charge a unit that is no longer there.
committed := pg_temp.try_commit(actor, '38300000-0000-4000-8000-000000000010');
PERFORM pg_temp.assert_true(committed->>'error' = 'generation_quota_exceeded',
'a late commit past the allowance is rejected: ' || committed::text);
-- With an overage credit the late commit is charged again and succeeds.
UPDATE public.subscriptions SET overage_credits = 1 WHERE user_id = actor;
committed := pg_temp.try_commit(actor, '38300000-0000-4000-8000-000000000010');
PERFORM pg_temp.assert_true(committed->>'error' IS NULL AND committed->>'consumedFrom' = 'overage',
'a late commit re-charges through the shared ledger: ' || committed::text);
PERFORM pg_temp.assert_true(
(SELECT overage_credits FROM public.subscriptions WHERE user_id = actor) = 0,
'the late commit spent the overage credit');
PERFORM pg_temp.assert_true(
(SELECT sum(count) FROM public.daily_usage WHERE user_id = actor AND feature = 'llm_haiku') = 251,
'the late commit is recorded once');
END;
$$;
-- 5. Claims made before this migration (no lease) still commit through the
-- shared ledger, and fail without touching it.
DO $$
DECLARE
actor constant uuid := '38000000-0000-4000-8000-000000000003';
meeting constant uuid := '38100000-0000-4000-8000-000000000003';
template constant uuid := '38200000-0000-4000-8000-000000000003';
lease uuid;
claim jsonb;
committed jsonb;
BEGIN
claim := pg_temp.try_claim(actor, '38300000-0000-4000-8000-000000000020', meeting, template, 'claude-sonnet-4-6');
PERFORM pg_temp.assert_true((claim->>'claimed')::boolean, 'pro_plus Sonnet claim');
-- Turn it into a legacy claim: no lease, nothing recorded yet.
SELECT llm_reservation_id INTO lease FROM public.meeting_document_generation_requests
WHERE user_id = actor AND idempotency_key = '38300000-0000-4000-8000-000000000020';
UPDATE public.meeting_document_generation_requests SET llm_reservation_id = NULL
WHERE user_id = actor AND idempotency_key = '38300000-0000-4000-8000-000000000020';
PERFORM public.finalize_llm_quota(lease, false);
PERFORM pg_temp.assert_true(pg_temp.usage_of(actor, 'llm_sonnet') = 0, 'legacy claim holds nothing');
committed := pg_temp.try_commit(actor, '38300000-0000-4000-8000-000000000020');
PERFORM pg_temp.assert_true(committed->>'error' IS NULL AND committed->>'consumedFrom' = 'base',
'a legacy claim commits: ' || committed::text);
PERFORM pg_temp.assert_true(pg_temp.usage_of(actor, 'llm_sonnet') = 1, 'a legacy commit records one unit');
-- Legacy failure is a no-op on the ledger.
claim := pg_temp.try_claim(actor, '38300000-0000-4000-8000-000000000021', meeting, template, 'claude-sonnet-4-6');
SELECT llm_reservation_id INTO lease FROM public.meeting_document_generation_requests
WHERE user_id = actor AND idempotency_key = '38300000-0000-4000-8000-000000000021';
UPDATE public.meeting_document_generation_requests SET llm_reservation_id = NULL
WHERE user_id = actor AND idempotency_key = '38300000-0000-4000-8000-000000000021';
PERFORM public.finalize_llm_quota(lease, false);
PERFORM public.fail_meeting_document_generation_v1(actor, '38300000-0000-4000-8000-000000000021', 'provider_timeout');
PERFORM pg_temp.assert_true(pg_temp.usage_of(actor, 'llm_sonnet') = 1, 'a legacy failure changes nothing');
-- Unlimited allowances are never throttled and still release on failure.
claim := pg_temp.try_claim(actor, '38300000-0000-4000-8000-000000000022', meeting, template, 'claude-haiku-4-5-20251001');
PERFORM pg_temp.assert_true((claim->>'claimed')::boolean, 'unlimited Haiku claim');
claim := pg_temp.try_claim(actor, '38300000-0000-4000-8000-000000000023', meeting, template, 'claude-haiku-4-5-20251001');
PERFORM pg_temp.assert_true((claim->>'claimed')::boolean, 'unlimited allowances are not throttled');
PERFORM public.fail_meeting_document_generation_v1(actor, '38300000-0000-4000-8000-000000000023', 'provider_timeout');
PERFORM pg_temp.assert_true(pg_temp.usage_of(actor, 'llm_haiku') = 1, 'unlimited failure releases its unit');
END;
$$;
ROLLBACK;

View file

@ -0,0 +1,341 @@
\set ON_ERROR_STOP on
-- A re-record that fails after upload restores the meeting it re-records
-- (migration 20260929040000). Local only: psql against the local Supabase
-- stack. Runs in a transaction and rolls back.
BEGIN;
CREATE OR REPLACE FUNCTION pg_temp.assert_true(condition boolean, message text)
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
IF condition IS NOT TRUE THEN
RAISE EXCEPTION 'assertion_failed: %', message;
END IF;
END;
$$;
INSERT INTO auth.users (
id, aud, role, email, encrypted_password, email_confirmed_at,
raw_app_meta_data, raw_user_meta_data, created_at, updated_at
) VALUES (
'91000000-0000-4000-8000-000000000001', 'authenticated', 'authenticated',
'rerecord-failure-owner@example.invalid', crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{}'::jsonb, now(), now()
);
-- M1: completed by a mobile capture (A1, job J1).
-- M2: first recording, no content yet.
-- M3: content from elsewhere (desktop): transcript rows, no mobile job, no audio row.
INSERT INTO public.meetings (
id, user_id, title, status, raw_transcript, minutes_markdown,
duration_ms, audio_storage_key
) VALUES
(
'92000000-0000-4000-8000-000000000001',
'91000000-0000-4000-8000-000000000001',
'Completed meeting', 'completed', 'old transcript', 'old minutes',
1000, '91000000-0000-4000-8000-000000000001/imports/a1.wav'
),
(
'92000000-0000-4000-8000-000000000002',
'91000000-0000-4000-8000-000000000001',
'First recording', 'recording', NULL, NULL, NULL, NULL
),
(
'92000000-0000-4000-8000-000000000003',
'91000000-0000-4000-8000-000000000001',
'Desktop meeting', 'completed', 'desktop transcript', NULL,
5000, 'desktop/original.wav'
);
INSERT INTO public.transcripts (meeting_id, segment_index, timestamp_ms, duration_ms, text)
VALUES
('92000000-0000-4000-8000-000000000001', 0, 0, 1000, 'old transcript'),
('92000000-0000-4000-8000-000000000003', 0, 0, 2000, 'desktop segment 0'),
('92000000-0000-4000-8000-000000000003', 1, 2000, 3000, 'desktop segment 1');
INSERT INTO public.audio_files (
id, user_id, meeting_id, source, original_name, storage_key, mime_type,
size_bytes, duration_ms, sha256, upload_status
) VALUES
(
'93000000-0000-4000-8000-000000000001',
'91000000-0000-4000-8000-000000000001',
'92000000-0000-4000-8000-000000000001',
'recording', 'a1.wav',
'91000000-0000-4000-8000-000000000001/imports/a1.wav',
'audio/wav', 32044, 1000, repeat('1', 64), 'uploaded'
),
(
'93000000-0000-4000-8000-000000000002',
'91000000-0000-4000-8000-000000000001',
'92000000-0000-4000-8000-000000000001',
'recording', 'a2.wav',
'91000000-0000-4000-8000-000000000001/imports/a2.wav',
'audio/wav', 64044, 2000, repeat('2', 64), 'uploaded'
),
(
'93000000-0000-4000-8000-000000000003',
'91000000-0000-4000-8000-000000000001',
'92000000-0000-4000-8000-000000000001',
'recording', 'a3.wav',
'91000000-0000-4000-8000-000000000001/imports/a3.wav',
'audio/wav', 96044, 3000, repeat('3', 64), 'uploaded'
),
(
'93000000-0000-4000-8000-000000000004',
'91000000-0000-4000-8000-000000000001',
'92000000-0000-4000-8000-000000000002',
'recording', 'first.wav',
'91000000-0000-4000-8000-000000000001/imports/first.wav',
'audio/wav', 32044, 1000, repeat('4', 64), 'uploaded'
),
(
'93000000-0000-4000-8000-000000000005',
'91000000-0000-4000-8000-000000000001',
'92000000-0000-4000-8000-000000000003',
'recording', 'desktop-rerecord.wav',
'91000000-0000-4000-8000-000000000001/imports/desktop-rerecord.wav',
'audio/wav', 32044, 9000, repeat('5', 64), 'failed'
);
INSERT INTO public.processing_jobs (
user_id, audio_file_id, meeting_id, kind, status, progress, attempt_count,
idempotency_key, result, started_at, completed_at
) VALUES (
'91000000-0000-4000-8000-000000000001',
'93000000-0000-4000-8000-000000000001',
'92000000-0000-4000-8000-000000000001',
'transcription', 'succeeded', 100, 1,
'mobile-meeting:m1:' || repeat('1', 64),
jsonb_build_object('audio_file_id', '93000000-0000-4000-8000-000000000001', 'duration_ms', 1000),
now() - interval '1 day', now() - interval '1 day'
);
SET LOCAL ROLE authenticated;
SELECT set_config(
'request.jwt.claims',
'{"sub":"91000000-0000-4000-8000-000000000001","role":"authenticated"}',
true
);
-- 1) Re-record M1 with A2; STT fails terminally after upload.
SELECT public.mobile_begin_meeting_recording('92000000-0000-4000-8000-000000000001');
SELECT public.mobile_queue_meeting_recording('92000000-0000-4000-8000-000000000001', 2000);
SELECT public.mobile_begin_meeting_processing(
'92000000-0000-4000-8000-000000000001',
'93000000-0000-4000-8000-000000000002',
'mobile-meeting:m1:' || repeat('2', 64)
);
SELECT pg_temp.assert_true(
(SELECT audio_storage_key FROM public.meetings
WHERE id = '92000000-0000-4000-8000-000000000001')
= '91000000-0000-4000-8000-000000000001/imports/a2.wav',
'precondition: processing points the meeting at the new capture'
);
SELECT public.mobile_mark_meeting_processing_failure(
'92000000-0000-4000-8000-000000000001',
'mobile-meeting:m1:' || repeat('2', 64),
'transcription', 'STT failed', true
);
SELECT pg_temp.assert_true(
EXISTS (
SELECT 1 FROM public.meetings
WHERE id = '92000000-0000-4000-8000-000000000001'
AND status = 'completed'
AND error_message IS NULL
AND raw_transcript = 'old transcript'
AND minutes_markdown = 'old minutes'
AND duration_ms = 1000
AND audio_storage_key = '91000000-0000-4000-8000-000000000001/imports/a1.wav'
),
'terminal failure of a re-record restores the completed meeting and its audio'
);
SELECT pg_temp.assert_true(
EXISTS (
SELECT 1 FROM public.processing_jobs
WHERE idempotency_key = 'mobile-meeting:m1:' || repeat('2', 64)
AND status = 'failed' AND error_message = 'STT failed'
),
'the failed job still records the failure'
);
RESET ROLE;
SELECT pg_temp.assert_true(
EXISTS (
SELECT 1 FROM public.audio_files
WHERE id = '93000000-0000-4000-8000-000000000002'
AND meeting_id IS NULL AND upload_status = 'deleted'
),
'the failed capture audio is detached'
);
SELECT pg_temp.assert_true(
EXISTS (
SELECT 1 FROM public.audio_purge_queue
WHERE user_id = '91000000-0000-4000-8000-000000000001'
AND storage_key = '91000000-0000-4000-8000-000000000001/imports/a2.wav'
),
'the failed capture audio is queued for purge'
);
SELECT pg_temp.assert_true(
EXISTS (
SELECT 1 FROM public.audio_files
WHERE id = '93000000-0000-4000-8000-000000000001'
AND meeting_id = '92000000-0000-4000-8000-000000000001'
AND upload_status = 'uploaded'
),
'the audio behind the kept transcript stays linked'
);
SELECT pg_temp.assert_true(
(SELECT meeting_id FROM public.audio_files
WHERE id = '93000000-0000-4000-8000-000000000003')
= '92000000-0000-4000-8000-000000000001',
'uploaded audio no failed job owns is not detached by an unrelated failure'
);
-- 2) Re-record M1 with A3; the user discards the queued item.
SET LOCAL ROLE authenticated;
SELECT set_config(
'request.jwt.claims',
'{"sub":"91000000-0000-4000-8000-000000000001","role":"authenticated"}',
true
);
SELECT public.mobile_begin_meeting_recording('92000000-0000-4000-8000-000000000001');
SELECT public.mobile_queue_meeting_recording('92000000-0000-4000-8000-000000000001', 3000);
SELECT public.mobile_begin_meeting_processing(
'92000000-0000-4000-8000-000000000001',
'93000000-0000-4000-8000-000000000003',
'mobile-meeting:m1:' || repeat('3', 64)
);
SELECT pg_temp.assert_true(
(SELECT status FROM public.mobile_fail_meeting_recording(
'92000000-0000-4000-8000-000000000001', 'Queued audio processing was cancelled'
)) = 'completed',
'fail_recording reports the restored status'
);
SELECT pg_temp.assert_true(
EXISTS (
SELECT 1 FROM public.meetings
WHERE id = '92000000-0000-4000-8000-000000000001'
AND status = 'completed'
AND error_message IS NULL
AND duration_ms = 1000
AND audio_storage_key = '91000000-0000-4000-8000-000000000001/imports/a1.wav'
),
'a discarded re-record restores the completed meeting and its audio'
);
RESET ROLE;
SELECT pg_temp.assert_true(
(SELECT meeting_id FROM public.audio_files
WHERE id = '93000000-0000-4000-8000-000000000003') IS NULL,
'the discarded capture audio is detached'
);
-- 3) A first recording keeps the error outcome and its audio for retry.
SET LOCAL ROLE authenticated;
SELECT set_config(
'request.jwt.claims',
'{"sub":"91000000-0000-4000-8000-000000000001","role":"authenticated"}',
true
);
SELECT public.mobile_queue_meeting_recording('92000000-0000-4000-8000-000000000002', 1000);
SELECT public.mobile_begin_meeting_processing(
'92000000-0000-4000-8000-000000000002',
'93000000-0000-4000-8000-000000000004',
'mobile-meeting:m2:' || repeat('4', 64)
);
SELECT public.mobile_mark_meeting_processing_failure(
'92000000-0000-4000-8000-000000000002',
'mobile-meeting:m2:' || repeat('4', 64),
'transcription', 'STT failed', true
);
SELECT pg_temp.assert_true(
EXISTS (
SELECT 1 FROM public.meetings
WHERE id = '92000000-0000-4000-8000-000000000002'
AND status = 'error'
AND error_message = 'STT failed'
),
'terminal failure of a first recording still reports an error'
);
SELECT pg_temp.assert_true(
(SELECT status FROM public.mobile_fail_meeting_recording(
'92000000-0000-4000-8000-000000000002', 'Recording failed'
)) = 'error',
'fail_recording of a first recording still reports an error'
);
RESET ROLE;
SELECT pg_temp.assert_true(
EXISTS (
SELECT 1 FROM public.audio_files
WHERE id = '93000000-0000-4000-8000-000000000004'
AND meeting_id = '92000000-0000-4000-8000-000000000002'
AND upload_status = 'uploaded'
),
'a failed first recording keeps its audio linked for retry'
);
-- 4) Content from elsewhere: a re-record whose upload failed (no job) keeps the
-- original playback key and restores the duration from the transcript span.
SET LOCAL ROLE authenticated;
SELECT set_config(
'request.jwt.claims',
'{"sub":"91000000-0000-4000-8000-000000000001","role":"authenticated"}',
true
);
SELECT public.mobile_begin_meeting_recording('92000000-0000-4000-8000-000000000003');
SELECT public.mobile_queue_meeting_recording('92000000-0000-4000-8000-000000000003', 9000);
SELECT public.mobile_fail_meeting_recording(
'92000000-0000-4000-8000-000000000003', 'Audio upload failed'
);
SELECT pg_temp.assert_true(
EXISTS (
SELECT 1 FROM public.meetings
WHERE id = '92000000-0000-4000-8000-000000000003'
AND status = 'completed'
AND error_message IS NULL
AND raw_transcript = 'desktop transcript'
AND duration_ms = 5000
AND audio_storage_key = 'desktop/original.wav'
),
'a failed re-record of foreign content keeps its key and transcript duration'
);
RESET ROLE;
SELECT pg_temp.assert_true(
(SELECT meeting_id FROM public.audio_files
WHERE id = '93000000-0000-4000-8000-000000000005') IS NULL,
'the failed upload row of the re-record is detached'
);
-- 5) Cancel before processing keeps the 20260929002700 behavior.
SET LOCAL ROLE authenticated;
SELECT set_config(
'request.jwt.claims',
'{"sub":"91000000-0000-4000-8000-000000000001","role":"authenticated"}',
true
);
SELECT public.mobile_begin_meeting_recording('92000000-0000-4000-8000-000000000001');
SELECT pg_temp.assert_true(
(SELECT status FROM public.mobile_cancel_meeting_recording(
'92000000-0000-4000-8000-000000000001'
)) = 'completed',
'cancel of a re-record still returns to completed'
);
-- 6) The helpers are not reachable through the API roles.
RESET ROLE;
SELECT pg_temp.assert_true(
NOT has_function_privilege('authenticated', 'public.mobile_meeting_has_content_v1(uuid)', 'EXECUTE')
AND NOT has_function_privilege('anon', 'public.mobile_meeting_has_content_v1(uuid)', 'EXECUTE')
AND NOT has_function_privilege(
'authenticated', 'public.mobile_restore_meeting_after_failed_capture_v1(uuid, uuid, uuid)', 'EXECUTE'
)
AND NOT has_function_privilege(
'anon', 'public.mobile_restore_meeting_after_failed_capture_v1(uuid, uuid, uuid)', 'EXECUTE'
),
'restore helpers are internal'
);
ROLLBACK;

View file

@ -0,0 +1,207 @@
\set ON_ERROR_STOP on
-- Regression: a confirmed refund of an older Payple order (same billing key)
-- must not revoke the period funded by the current order.
-- Covers apply_payment_provider_event from
-- 20260929100011_payple_cancellation_order_scope.sql.
BEGIN;
CREATE OR REPLACE FUNCTION pg_temp.assert_true(condition boolean, message text)
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
IF condition IS NOT TRUE THEN
RAISE EXCEPTION 'assertion_failed: %', message;
END IF;
END;
$$;
INSERT INTO auth.users (
id, aud, role, email, encrypted_password, email_confirmed_at,
raw_app_meta_data, raw_user_meta_data, created_at, updated_at
) VALUES (
'20000000-0000-4000-8000-000000000031', 'authenticated', 'authenticated',
'payple-order-scope@example.invalid', crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{}'::jsonb, now(), now()
);
DO $$
DECLARE
c_user constant uuid := '20000000-0000-4000-8000-000000000031';
c_payer constant text := 'payer-order-scope';
c_oid1 constant text := 'D3RO-20260801090000-scope01';
c_oid2 constant text := 'D3RO-20260901090000-scope02';
v_result jsonb;
v_period_end timestamptz;
v_cursor_before timestamptz;
v_cursor_after timestamptz;
v_sub public.subscriptions%ROWTYPE;
v_disposition text;
BEGIN
-- Month 1: checkout order oid1.
v_result := public.apply_payment_provider_event(
p_user_id => c_user,
p_provider => 'payple',
p_event_id => 'payment:' || c_oid1,
p_event_created_at => now() - interval '40 days',
p_event_type => 'payment.completed',
p_payload_digest => repeat('a', 64),
p_provider_resource_id => c_payer,
p_tier => 'pro',
p_status => 'active',
p_entitled => true,
p_current_period_start => now() - interval '40 days',
p_current_period_end => now() - interval '10 days',
p_auto_renewing => true,
p_provider_customer_id => c_payer,
p_provider_order_id => c_oid1
);
PERFORM pg_temp.assert_true((v_result->>'applied')::boolean, 'month 1 applied');
-- Month 2: renewal order oid2 on the same billing key.
v_period_end := now() + interval '20 days';
v_result := public.apply_payment_provider_event(
p_user_id => c_user,
p_provider => 'payple',
p_event_id => 'payment:' || c_oid2,
p_event_created_at => now() - interval '10 days',
p_event_type => 'payment.completed',
p_payload_digest => repeat('b', 64),
p_provider_resource_id => c_payer,
p_tier => 'pro',
p_status => 'active',
p_entitled => true,
p_current_period_start => now() - interval '10 days',
p_current_period_end => v_period_end,
p_auto_renewing => true,
p_provider_customer_id => c_payer,
p_provider_order_id => c_oid2
);
PERFORM pg_temp.assert_true((v_result->>'applied')::boolean, 'month 2 applied');
SELECT last_event_created_at INTO v_cursor_before
FROM public.payment_provider_cursors
WHERE user_id = c_user AND provider = 'payple';
-- Support refunds oid1; Payple confirms the cancellation webhook.
v_result := public.apply_payment_provider_event(
p_user_id => c_user,
p_provider => 'payple',
p_event_id => 'cancel:' || c_oid1 || ':승인취소완료',
p_event_created_at => now(),
p_event_type => 'webhook.payment_canceled',
p_payload_digest => repeat('c', 64),
p_provider_resource_id => c_payer,
p_tier => 'free',
p_status => 'canceled',
p_entitled => false,
p_current_period_start => NULL,
p_current_period_end => now(),
p_cancel_at => now(),
p_auto_renewing => false,
p_provider_customer_id => c_payer,
p_provider_order_id => c_oid1
);
PERFORM pg_temp.assert_true(
NOT (v_result->>'applied')::boolean
AND v_result->>'reason' = 'canceled_order_not_current',
'refund of an older order is ignored, got ' || v_result::text
);
SELECT * INTO v_sub FROM public.subscriptions WHERE user_id = c_user;
PERFORM pg_temp.assert_true(
v_sub.tier = 'pro'
AND v_sub.provider = 'payple'
AND v_sub.auto_renewing
AND v_sub.payple_pay_oid = c_oid2
AND v_sub.current_period_end = v_period_end
AND v_sub.provider_resource_id = c_payer,
'current paid period and renewals are preserved'
);
SELECT disposition INTO v_disposition
FROM public.payment_provider_events
WHERE provider = 'payple' AND event_id = 'cancel:' || c_oid1 || ':승인취소완료';
PERFORM pg_temp.assert_true(v_disposition = 'ignored', 'ignored event is recorded');
SELECT last_event_created_at INTO v_cursor_after
FROM public.payment_provider_cursors
WHERE user_id = c_user AND provider = 'payple';
PERFORM pg_temp.assert_true(
v_cursor_after = v_cursor_before,
'ignored refund does not advance the ordering cursor'
);
-- Refunding the current order still revokes entitlement.
v_result := public.apply_payment_provider_event(
p_user_id => c_user,
p_provider => 'payple',
p_event_id => 'cancel:' || c_oid2 || ':승인취소완료',
p_event_created_at => now(),
p_event_type => 'webhook.payment_canceled',
p_payload_digest => repeat('d', 64),
p_provider_resource_id => c_payer,
p_tier => 'free',
p_status => 'canceled',
p_entitled => false,
p_current_period_start => NULL,
p_current_period_end => now(),
p_cancel_at => now(),
p_auto_renewing => false,
p_provider_customer_id => c_payer,
p_provider_order_id => c_oid2
);
PERFORM pg_temp.assert_true(
(v_result->>'applied')::boolean,
'refund of the current order is applied, got ' || v_result::text
);
SELECT * INTO v_sub FROM public.subscriptions WHERE user_id = c_user;
PERFORM pg_temp.assert_true(
v_sub.tier = 'free' AND v_sub.provider = 'none' AND NOT v_sub.auto_renewing,
'current order refund revokes the subscription'
);
-- Revocations that name no order (scheduled expiry, manage) are unaffected.
v_result := public.apply_payment_provider_event(
p_user_id => c_user,
p_provider => 'payple',
p_event_id => 'payment:D3RO-20260910090000-scope03',
p_event_created_at => now() + interval '1 second',
p_event_type => 'payment.completed',
p_payload_digest => repeat('e', 64),
p_provider_resource_id => c_payer,
p_tier => 'pro',
p_status => 'active',
p_entitled => true,
p_current_period_start => now(),
p_current_period_end => now() + interval '1 month',
p_auto_renewing => false,
p_provider_customer_id => c_payer,
p_provider_order_id => 'D3RO-20260910090000-scope03'
);
PERFORM pg_temp.assert_true((v_result->>'applied')::boolean, 're-entitled');
v_result := public.apply_payment_provider_event(
p_user_id => c_user,
p_provider => 'payple',
p_event_id => 'scheduled-expire:order-scope',
p_event_created_at => now() + interval '2 seconds',
p_event_type => 'subscription.scheduled_expiry',
p_payload_digest => repeat('f', 64),
p_provider_resource_id => c_payer,
p_tier => 'free',
p_status => 'expired',
p_entitled => false,
p_provider_order_id => NULL
);
PERFORM pg_temp.assert_true(
(v_result->>'applied')::boolean,
'order-less revocation still applies, got ' || v_result::text
);
END;
$$;
ROLLBACK;
SELECT 'payple_cancellation_order_scope_ok' AS result;

View file

@ -0,0 +1,338 @@
\set ON_ERROR_STOP on
-- Regression: team management RPCs must reject callers that hold no membership
-- row in the target team (see migrations/20260929010000_team_rpc_null_role_guard.sql).
--
-- Before that migration each RPC read the caller role with
-- SELECT role INTO caller_role FROM team_members WHERE ... user_id = auth.uid()
-- and compared it with `<>` / `NOT IN`. For a non-member caller_role is NULL,
-- every guard evaluated to NULL, plpgsql skipped the RAISE, and any signed-in
-- user who knew a team id could mint an admin invite for a second account,
-- change member roles, remove members and cancel invites.
--
-- Local only: psql against the local Supabase stack. Runs in a transaction and
-- rolls back.
BEGIN;
CREATE OR REPLACE FUNCTION pg_temp.assert_true(condition boolean, message text)
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
IF condition IS NOT TRUE THEN
RAISE EXCEPTION 'assertion_failed: %', message;
END IF;
END;
$$;
CREATE OR REPLACE FUNCTION pg_temp.act_as(user_id uuid)
RETURNS void
LANGUAGE sql
AS $$
SELECT set_config(
'request.jwt.claims',
pg_catalog.json_build_object('sub', user_id, 'role', 'authenticated')::text,
true
);
$$;
-- Runs `statement` and requires it to fail with SQLSTATE 42501 and the given
-- error message. Anything else (success, another error) fails the test.
CREATE OR REPLACE FUNCTION pg_temp.expect_forbidden(
statement text,
expected_message text,
label text
)
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
BEGIN
EXECUTE statement;
EXCEPTION
WHEN insufficient_privilege THEN
IF SQLERRM <> expected_message THEN
RAISE EXCEPTION 'assertion_failed: % raised % instead of %',
label, SQLERRM, expected_message;
END IF;
RETURN;
END;
RAISE EXCEPTION 'assertion_failed: % was allowed', label;
END;
$$;
-- ---------------------------------------------------------------------------
-- 1. Pure role policy: a missing role (NULL) never satisfies any requirement.
-- ---------------------------------------------------------------------------
SELECT pg_temp.assert_true(
public.team_role_at_least_v1(NULL, 'member') IS FALSE,
'no membership does not satisfy member'
);
SELECT pg_temp.assert_true(
public.team_role_at_least_v1(NULL, 'owner') IS FALSE,
'no membership does not satisfy owner'
);
SELECT pg_temp.assert_true(
public.team_role_at_least_v1('owner', NULL) IS FALSE,
'an unknown requirement is never satisfied'
);
SELECT pg_temp.assert_true(
public.team_role_at_least_v1('superuser', 'member') IS FALSE,
'an unknown role does not satisfy member'
);
SELECT pg_temp.assert_true(
public.team_role_at_least_v1('owner', 'admin')
AND public.team_role_at_least_v1('owner', 'owner')
AND public.team_role_at_least_v1('admin', 'admin')
AND public.team_role_at_least_v1('admin', 'member')
AND public.team_role_at_least_v1('member', 'member'),
'role hierarchy owner > admin > member is honoured'
);
SELECT pg_temp.assert_true(
NOT public.team_role_at_least_v1('admin', 'owner')
AND NOT public.team_role_at_least_v1('member', 'admin'),
'lower roles do not satisfy higher requirements'
);
SELECT pg_temp.assert_true(
NOT has_function_privilege('authenticated', 'public.require_team_role_v1(uuid, text)', 'EXECUTE')
AND NOT has_function_privilege('anon', 'public.require_team_role_v1(uuid, text)', 'EXECUTE'),
'role guard helper is internal to the team RPCs'
);
-- ---------------------------------------------------------------------------
-- 2. Fixtures: team T with owner O, admin A, member M; outsider X with a second
-- account X2; a pending invite for I.
-- ---------------------------------------------------------------------------
INSERT INTO auth.users (
id, aud, role, email, encrypted_password, email_confirmed_at,
raw_app_meta_data, raw_user_meta_data, created_at, updated_at
)
SELECT
fixture.id, 'authenticated', 'authenticated', fixture.email,
crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{}'::jsonb, now(), now()
FROM (VALUES
('43100000-0000-4000-8000-000000000001'::uuid, 'null-guard-owner@example.invalid'),
('43100000-0000-4000-8000-000000000002'::uuid, 'null-guard-admin@example.invalid'),
('43100000-0000-4000-8000-000000000003'::uuid, 'null-guard-member@example.invalid'),
('43100000-0000-4000-8000-000000000004'::uuid, 'null-guard-outsider@example.invalid'),
('43100000-0000-4000-8000-000000000005'::uuid, 'null-guard-outsider-2@example.invalid'),
('43100000-0000-4000-8000-000000000006'::uuid, 'null-guard-invitee@example.invalid')
) AS fixture(id, email);
SET LOCAL ROLE authenticated;
SELECT pg_temp.act_as('43100000-0000-4000-8000-000000000001');
SELECT (public.create_team('Null Role Guard Team')->>'id')::uuid AS team_id \gset
SELECT set_config('test.team_id', :'team_id', true);
SELECT public.create_team_invite(:'team_id', 'null-guard-admin@example.invalid', 'admin')
->>'token' AS admin_token \gset
SELECT public.create_team_invite(:'team_id', 'null-guard-member@example.invalid', 'member')
->>'token' AS member_token \gset
SELECT (public.create_team_invite(:'team_id', 'null-guard-invitee@example.invalid', 'member')
->>'id')::uuid AS pending_invite_id \gset
SELECT set_config('test.pending_invite_id', :'pending_invite_id', true);
SELECT pg_temp.act_as('43100000-0000-4000-8000-000000000002');
SELECT public.accept_team_invite(:'admin_token');
SELECT pg_temp.act_as('43100000-0000-4000-8000-000000000003');
SELECT public.accept_team_invite(:'member_token');
-- ---------------------------------------------------------------------------
-- 3. Non-member X: every management RPC is refused.
-- ---------------------------------------------------------------------------
SELECT pg_temp.act_as('43100000-0000-4000-8000-000000000004');
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.create_team_invite(%L::uuid, %L, %L)',
:'team_id', 'null-guard-outsider-2@example.invalid', 'admin'
),
'team_admin_required',
'non-member minting an admin invite'
);
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.create_team_invite(%L::uuid, %L, %L)',
:'team_id', 'null-guard-outsider-2@example.invalid', 'member'
),
'team_admin_required',
'non-member minting a member invite'
);
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.update_team_member_role(%L::uuid, %L::uuid, %L)',
:'team_id', '43100000-0000-4000-8000-000000000003', 'admin'
),
'team_owner_required',
'non-member promoting a member'
);
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.update_team_member_role(%L::uuid, %L::uuid, %L)',
:'team_id', '43100000-0000-4000-8000-000000000002', 'member'
),
'team_owner_required',
'non-member demoting an admin'
);
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.remove_team_member(%L::uuid, %L::uuid)',
:'team_id', '43100000-0000-4000-8000-000000000003'
),
'team_admin_required',
'non-member removing a member'
);
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.remove_team_member(%L::uuid, %L::uuid)',
:'team_id', '43100000-0000-4000-8000-000000000002'
),
'team_admin_required',
'non-member removing an admin'
);
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.remove_team_member(%L::uuid, %L::uuid)',
:'team_id', '43100000-0000-4000-8000-000000000099'
),
'team_admin_required',
'non-member probing membership of an unknown user'
);
SELECT pg_temp.expect_forbidden(
format('SELECT public.cancel_team_invite(%L::uuid)', :'pending_invite_id'),
'team_admin_required',
'non-member cancelling a pending invite'
);
-- The second attacker account has nothing to accept.
SELECT pg_temp.act_as('43100000-0000-4000-8000-000000000005');
SELECT pg_temp.assert_true(
(SELECT count(*) FROM public.list_team_members(:'team_id')) = 0,
'second outsider account sees no team members'
);
-- ---------------------------------------------------------------------------
-- 4. Existing role rules still hold for members.
-- ---------------------------------------------------------------------------
SELECT pg_temp.act_as('43100000-0000-4000-8000-000000000003');
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.create_team_invite(%L::uuid, %L, %L)',
:'team_id', 'null-guard-outsider-2@example.invalid', 'member'
),
'team_admin_required',
'regular member inviting'
);
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.update_team_member_role(%L::uuid, %L::uuid, %L)',
:'team_id', '43100000-0000-4000-8000-000000000002', 'member'
),
'team_owner_required',
'regular member demoting an admin'
);
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.remove_team_member(%L::uuid, %L::uuid)',
:'team_id', '43100000-0000-4000-8000-000000000002'
),
'team_admin_required',
'regular member removing an admin'
);
SELECT pg_temp.expect_forbidden(
format('SELECT public.cancel_team_invite(%L::uuid)', :'pending_invite_id'),
'team_admin_required',
'regular member cancelling another user''s invite'
);
SELECT pg_temp.act_as('43100000-0000-4000-8000-000000000002');
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.create_team_invite(%L::uuid, %L, %L)',
:'team_id', 'null-guard-outsider-2@example.invalid', 'admin'
),
'owner_required_for_admin_invite',
'admin minting another admin invite'
);
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.update_team_member_role(%L::uuid, %L::uuid, %L)',
:'team_id', '43100000-0000-4000-8000-000000000003', 'admin'
),
'team_owner_required',
'admin changing roles'
);
SELECT pg_temp.assert_true(
(public.create_team_invite(:'team_id', 'null-guard-outsider-2@example.invalid', 'member')
->>'role') = 'member',
'admin can still invite a member'
);
SELECT pg_temp.act_as('43100000-0000-4000-8000-000000000001');
SELECT pg_temp.assert_true(
public.update_team_member_role(
:'team_id', '43100000-0000-4000-8000-000000000003', 'admin'
)->>'role' = 'admin'
AND public.update_team_member_role(
:'team_id', '43100000-0000-4000-8000-000000000003', 'member'
)->>'role' = 'member',
'owner can still change roles'
);
SELECT pg_temp.assert_true(
(public.cancel_team_invite(:'pending_invite_id')->>'cancelled')::boolean,
'owner can still cancel an invite'
);
-- A member can still leave on their own; leaving twice reports not found.
SELECT pg_temp.act_as('43100000-0000-4000-8000-000000000003');
SELECT pg_temp.assert_true(
(public.remove_team_member(:'team_id', '43100000-0000-4000-8000-000000000003')
->>'removed')::boolean,
'member can leave the team'
);
DO $$
BEGIN
PERFORM public.remove_team_member(
current_setting('test.team_id')::uuid,
'43100000-0000-4000-8000-000000000003'
);
RAISE EXCEPTION 'assertion_failed: leaving twice succeeded';
EXCEPTION
WHEN no_data_found THEN NULL;
END;
$$;
RESET ROLE;
-- ---------------------------------------------------------------------------
-- 5. State: the outsider changed nothing.
-- ---------------------------------------------------------------------------
SELECT pg_temp.assert_true(
NOT EXISTS (
SELECT 1 FROM public.team_invites
WHERE invited_by = '43100000-0000-4000-8000-000000000004'
),
'outsider created no invite'
);
SELECT pg_temp.assert_true(
(SELECT role FROM public.team_members
WHERE team_id = :'team_id'
AND user_id = '43100000-0000-4000-8000-000000000002') = 'admin',
'admin role is unchanged'
);
SELECT pg_temp.assert_true(
NOT EXISTS (
SELECT 1 FROM public.team_members
WHERE team_id = :'team_id'
AND user_id IN (
'43100000-0000-4000-8000-000000000004',
'43100000-0000-4000-8000-000000000005'
)
),
'neither outsider account joined the team'
);
ROLLBACK;