Files
accounted/supabase/migrations/20260726090000_agent_quota_rpc_caller_guard.sql
Jakob Wennberg ee8ddb3849 fix(assistant): stop cross-user conversation access, bricked threads and lost sessions (#1209)
* fix(assistant): stop cross-user conversation access, bricked threads and lost sessions

Hotfix batch (PR1 of the assistant UI makeover, dev_docs/assistant_redesign_plan.md
section 7). No visual change; each of these is wrong today regardless of which
design lands, and three are unrecoverable per incident.

/api/agent/invoke never checked who owns a resumed conversation_id. RLS on
agent_conversations/agent_messages is company-scoped, not user-scoped
(20260517204000), so a member could post a colleague's conversation id, have
their history loaded into the prompt and read it back, while their own turns
were appended to that thread. The conversations list route filters on user_id
for exactly this reason. Also pins company and intent: resuming a thread from
another company would mix ledgers, and resuming under a different intent would
swap the tool whitelist under history the model has already seen.

A turn persists the assistant message carrying tool_use blocks before the tools
run, and their results only after the batch finishes. Dying in between (client
disconnect terminating the function, a deploy, a slow tool) left history ending
on an unanswered tool_use, which the Messages API rejects on replay: every later
turn 400s, and agent_messages is append-only for the BFL trail, so nothing could
repair it. History is now patched on read by synthesizing is_error tool_results,
leaving the stored trail untouched.

check_and_increment_agent_quota is SECURITY DEFINER in public with a
caller-chosen p_user_id, so any authenticated user could drain a colleague's
minute/day budget and lock them out of every agent endpoint. A plain REVOKE
would break the limiter (all three callers use the user's RLS client) and, as it
fails open, silently remove the spend cap: the function now refuses to act for
anyone but the caller, while service-role connections keep passing an explicit
id.

The single reject route re-read status and then wrote unguarded, so losing the
race with commit's atomic pending -> committing claim stamped `rejected` over an
operation that had already posted a verifikat, invisible to the committing-state
recovery sweep. Guarded on status like bulk-reject already is; a lost race is
now a 409.

The sheet's Escape handler listened on window with no defaultPrevented or target
check while the sheet is deliberately non-modal, so pressing Esc to dismiss the
reject-reason Select inside an approval card, the command palette or any dialog
unmounted the sheet and discarded the conversation, the streaming turn and the
un-actioned proposal. It now yields to open overlays and to focus outside the
sheet.

Verified: 9526 unit tests pass, lint clean on touched files, guards pass, and
the new pg-real test proves the quota guard against real Postgres (attacker
raises 42501, victim counters stay at 0). The four unrelated pg-real failures on
this machine reproduce identically with these changes stashed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(assistant): close anon path on the quota RPC, order the ownership check ahead of writes

Review follow-ups on the hotfix batch.

The caller guard used auth.uid() alone, which is NULL for the `anon` role just
as it is for backend roles, so an unauthenticated caller holding the public anon
key (it ships in the browser bundle) could still pick any p_user_id and drain
that user's quota. The guard now keys on the request role: anon and
authenticated may only ever spend their own quota, backend roles keep passing an
explicit id. The default PUBLIC execute grant is revoked as a second layer, with
execute granted only to authenticated and service_role. Covered by a new pg test
for the anon path.

The ownership check ran after the onboarding.intake stamp, so a request that was
about to be rejected could still write intake_completed_at. It now sits directly
after the capability gate, ahead of every side effect and ahead of the company
and profile reads, which also makes a rejected request cheaper.

The tool-result repair matched ids anywhere in the history, but the API needs
results in the message IMMEDIATELY after the tool_use. A result persisted after
an intervening turn (two turns racing on one conversation) left a shape that
still 400s. The repair is now positional, and orphaned or late-duplicate
tool_results are dropped, since an unmatched tool_result is rejected just as an
unanswered tool_use is.

The Escape guard matched the Radix popper wrapper, which stays mounted when a
popper is force-mounted; it now requires data-state="open" so a closed popper
cannot block Escape for the rest of the session.

Both new route errors are Swedish, per the user-facing error rule.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 17:48:18 +02:00

101 lines
4.7 KiB
PL/PgSQL

-- Harden check_and_increment_agent_quota against caller-chosen p_user_id.
--
-- The function is SECURITY DEFINER and lives in `public`, so PostgREST exposes
-- it at /rest/v1/rpc/check_and_increment_agent_quota with the default
-- EXECUTE-to-PUBLIC grant. p_user_id is a plain argument, and user ids are
-- discoverable through company_members, so any caller could burn down a
-- targeted user's minute/day budget and lock them out of every agent endpoint
-- for the rest of the day.
--
-- A plain REVOKE FROM PUBLIC alone is not the fix: all three callers (agent
-- invoke, onboarding stream, composer) call this with the user's own RLS
-- client, i.e. as `authenticated`, so revoking everything would break the
-- limiter and, because it fails open on error, silently remove the spend cap it
-- exists to enforce.
--
-- So: two layers.
-- 1) Grants. Only `authenticated` and `service_role` may execute it at all.
-- `anon` is explicitly excluded: the anon key ships in the browser bundle,
-- so an unauthenticated caller could otherwise reach this RPC directly.
-- 2) A caller guard in the body. An end-user role may only ever spend its own
-- quota. Roles that are not PostgREST end users (service_role, and the
-- migration/superuser role used by cron, jobs and tests) keep passing an
-- explicit user id, which they need in order to act on someone's behalf.
--
-- auth.uid() alone is NOT sufficient as the guard: it is NULL for `anon` as
-- well as for backend roles, so an unauthenticated caller would pass it.
--
-- Function body is otherwise byte-identical to 20260526140000.
CREATE OR REPLACE FUNCTION public.check_and_increment_agent_quota(
p_user_id uuid,
p_minute_max integer,
p_day_max integer
) RETURNS jsonb
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
v_minute_key text := to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI');
v_day_key text := to_char(now() AT TIME ZONE 'Europe/Stockholm', 'YYYY-MM-DD');
v_minute_count integer;
v_day_count integer;
v_role text := coalesce(
nullif(current_setting('request.jwt.claim.role', true), ''),
nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'role',
''
);
BEGIN
-- Caller guard: anything arriving through PostgREST as an end user (anon or
-- authenticated) may only spend the quota of the user it is authenticated as.
IF v_role IN ('anon', 'authenticated') THEN
IF auth.uid() IS NULL OR p_user_id IS DISTINCT FROM auth.uid() THEN
RAISE EXCEPTION 'check_and_increment_agent_quota: p_user_id must be the calling user'
USING ERRCODE = '42501';
END IF;
END IF;
-- 1) Minute window — burst guard.
INSERT INTO public.agent_rate_counters (user_id, window_kind, window_key, count)
VALUES (p_user_id, 'minute', v_minute_key, 1)
ON CONFLICT (user_id, window_kind, window_key)
DO UPDATE SET count = agent_rate_counters.count + 1, updated_at = now()
RETURNING count INTO v_minute_count;
IF v_minute_count > p_minute_max THEN
UPDATE public.agent_rate_counters SET count = count - 1
WHERE user_id = p_user_id AND window_kind = 'minute' AND window_key = v_minute_key;
RETURN jsonb_build_object('ok', false, 'scope', 'minute', 'retry_after_sec', 60);
END IF;
-- 2) Day window — slow-drip backstop (only checked once minute passes).
INSERT INTO public.agent_rate_counters (user_id, window_kind, window_key, count)
VALUES (p_user_id, 'day', v_day_key, 1)
ON CONFLICT (user_id, window_kind, window_key)
DO UPDATE SET count = agent_rate_counters.count + 1, updated_at = now()
RETURNING count INTO v_day_count;
IF v_day_count > p_day_max THEN
-- Roll both counters back: the request didn't go through.
UPDATE public.agent_rate_counters SET count = count - 1
WHERE user_id = p_user_id AND window_kind = 'day' AND window_key = v_day_key;
UPDATE public.agent_rate_counters SET count = count - 1
WHERE user_id = p_user_id AND window_kind = 'minute' AND window_key = v_minute_key;
RETURN jsonb_build_object('ok', false, 'scope', 'day', 'retry_after_sec', 3600);
END IF;
RETURN jsonb_build_object('ok', true);
END;
$$;
-- Close the default PUBLIC grant and hand execute rights only to the roles that
-- legitimately call this: the three agent endpoints (as `authenticated`) and
-- backend/service contexts.
REVOKE ALL ON FUNCTION public.check_and_increment_agent_quota(uuid, integer, integer) FROM PUBLIC;
REVOKE ALL ON FUNCTION public.check_and_increment_agent_quota(uuid, integer, integer) FROM anon;
GRANT EXECUTE ON FUNCTION public.check_and_increment_agent_quota(uuid, integer, integer) TO authenticated;
GRANT EXECUTE ON FUNCTION public.check_and_increment_agent_quota(uuid, integer, integer) TO service_role;
NOTIFY pgrst, 'reload schema';