Files
accounted/supabase/migrations/20260831111519_api_key_unattended_commit_limit.sql
T
Jakob Wennberg 9fe37b85b5 feat(agents): per-key approval authority, the amount an agent may post unattended (#2079)
* feat(agents): per-key approval authority, the amount an agent may post unattended

An API key gets an optional ceiling in SEK. Above it the agent may still stage
the work, it just may not finish it alone: a human approves the same verifikat
in the app. Default is NULL, so every existing key keeps its behaviour and
turning this on is entirely opt-in.

Enforced at the two places an API key reaches the ledger, and at both the
refusal happens BEFORE the point of no return:

- MCP: in commitPendingOperation, before the atomic claim, so the operation
  stays 'pending'. Behind the claim it would be caught by the generic handler,
  marked terminal 'rejected', and the staged verifikat would be gone.
- REST: in journal-entries.commit, before commitEntry, so the draft stays a
  draft and the voucher sequence never advances (BFL 5 kap. 7 §). The dry run
  refuses too, rather than promising a voucher number the key cannot deliver.

Not enforced inside commit_journal_entry: a RAISE there is swallowed by
engine.ts into a retryable 500, and it would cost a DROP+CREATE on the function
that issues every voucher number.

Operations whose amount is only known during dispatch (batch allocation, bulk
booking, the settlement link paths) fail OPEN behind an explicit allowlist.
Pricing them ahead of dispatch would be a guess, and a wrong guess silently
breaks batch allocation the day someone sets a limit. The allowlist is derived
from what production actually stores: create_voucher carries total_debit on
1389 of 1389 rows, categorize_transaction carries amount on 2002 of 2003,
create_supplier_invoice_from_inbox carries total on 208 of 228.

This is a blast-radius cap, not a security boundary. A per-entry ceiling is
defeated by splitting one entry into several, and an LLM will find that, so
UNATTENDED_COMMIT_LIMIT_EXCEEDED forbids splitting first: one affärshändelse is
one verifikat (BFL 5 kap. 6 §). A cumulative rolling-window limit is the
primitive that actually bounds exposure and is left to a separate change.

The guard is written NULL-first everywhere. An absent, unparseable or
non-positive ceiling always means unlimited, never "block everything".

Agents read their own ceiling from gnubok_get_agent_briefing instead of
discovering it by burning a staged verifikat on a 403.

Changing a ceiling is auditable: it now renders in behandlingshistorik
(BFL 5 kap. 11 §). The audit trigger already fired on the column, but the
report dropped the event because the field was not in its diff map.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(skill): regenerate accounted-api skill for the new commit pitfall

apiskill:check is a ratchet: the generated reference must match the endpoint
registry. Never hand-edited.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(agents): pin the DB default itself, and declare the briefing field required

Two review findings, both real:

- the default test stored an explicit NULL, so it stayed green even if the
  column default changed to a positive ceiling: the one change that would
  silently start blocking every existing key. It now omits the column.
- gnubok_get_agent_briefing documents unattended_commit_limit as always
  present and emits it unconditionally, so it belongs in the output schema's
  required list.

Declined the NOT VALID constraint suggestion, with the reason recorded in the
migration: api_keys is 388 rows / 768 kB in production.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(agents): name the TOCTOU window in the REST ceiling check

A security scan flagged that the line sum is read before commitEntry, so a
concurrent write to the draft's lines can post over the ceiling. Real, and
accepted: closing it means enforcing inside commit_journal_entry, where a RAISE
becomes a retryable 500 and destroys the staged operation on the MCP path.

Recorded in the code rather than left implicit, so nobody later mistakes this
for a hard control. A per-entry ceiling is already defeated by splitting, which
needs no race; the cumulative rolling-window limit is the primitive that bounds
exposure.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(agents): price the settlement and batch paths that were bypassing the ceiling

A security scan flagged that known money-posting operations fail open, and it
was right. The first cut priced only create_voucher, categorize_transaction and
create_supplier_invoice_from_inbox, on the belief that the batch and settlement
paths computed their totals only inside SQL at dispatch. Production says
otherwise: the staged preview already carries the amount, because it is the
number a human is shown when approving the operation.

Over the last 120 days each of these is present and numeric on 100% of that
type's staged rows:

  link_transaction_journal_entry  transaction_amount  1369 rows
  bulk_book_transactions          tx_sum               273 rows
  link_supplier_invoice_voucher   payment_amount        55 rows
  match_batch_allocate            total_allocated       24 rows
  mark_invoice_paid               total                  3 rows

So a key with a ceiling could post any amount through the four largest
settlement paths. Now priced, and the ceiling applies.

Only reconciliation_match stays unpriced: it carries pair_count, which is a
COUNT. Pricing off that would compare pairs against kronor, which is worse than
not enforcing. link_document_to_voucher and attach_document_to_transaction move
no money at all; the transaction_amount they carry is context, not a posting.

Genuinely unpriceable types still fail OPEN. This control can only ever narrow
what a key does, and a wrong guess at an amount blocks a legitimate commit, so
guessing high would leave an agent unable to work.

Adds a test that walks the whole allowlist, so a typo'd field name cannot
silently make a type unpriceable again: that is exactly the hole this closes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(mcp): drop the ceiling from the agent briefing, the payload budget has no room

The tools/list context-budget bench sits at 65 000 tokens and main now leaves
roughly 20 tokens of headroom. An always-present field on the briefing's output
schema costs about 85, so this addition alone pushed the bench red.

The bench's own note is explicit that the answer is to demote a tool rather than
raise the ceiling, so raising it here would be the wrong trade for a
nice-to-have.

Nothing is lost that matters: the operation is never destroyed when it is
refused, so discovering the ceiling from UNATTENDED_COMMIT_LIMIT_EXCEEDED costs
one round trip and no work. That error already carries both attempted and limit,
and GET /api/settings/api-keys returns the value. Re-exposing it on the briefing
is worth doing once there is budget to spend.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(api): spell affärshändelse correctly in the commit pitfall

Fixed in the route's registerEndpoint pitfalls, which is the source; the skill
reference is regenerated from it and never hand-edited.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-31 15:53:53 +01:00

142 lines
6.0 KiB
PL/PgSQL

-- Approval-authority limit per API key: what an agent may finish WITHOUT a human.
--
-- This is deliberately NOT a write limit and deliberately NOT enforced inside
-- commit_journal_entry. Over the ceiling the agent may still stage a
-- pending_operation; it just may not commit it unattended, so a human approves
-- it in /pending. Nothing is destroyed, no voucher number is burned, and no
-- löpnummer gap is created (BFL 5 kap. 7 §).
--
-- ## Why the limit lives on api_keys and never on company_settings
--
-- company_settings.agent_auto_commit_max_amount existed once
-- (20260501120000) and was dropped four days later (20260505190027). A
-- company-scoped money threshold catches HUMANS too, which is the opposite of
-- the intent. Keyed on the credential, the check can only ever fire for an
-- agent: the gate reads actor.type = 'api_key' plus a non-null limit on that
-- key, and human approvals ({type:'user'}), cron, and every cookie-session
-- route commit with a different actor or none at all.
--
-- ## Why validate_and_increment_api_key returns it
--
-- That function is the one place the database itself verifies which credential
-- is acting: it matches the key hash. A limit returned from there is bound to a
-- DB-verified key rather than asserted by the caller. Passing a key id into
-- commit_journal_entry would have been caller-asserted and unverifiable (the
-- pending-op path runs as service_role, where the tenant guard bypasses by
-- design), while costing a DROP+CREATE on the function that issues every
-- voucher number. Two of that function's seven redefinitions were emergency
-- fixes for PostgREST overload ambiguity; there is no upside left to pay that.
--
-- pg-test: tests/pg/api-key-unattended-commit-limit.pg.test.ts
ALTER TABLE public.api_keys
ADD COLUMN IF NOT EXISTS unattended_commit_limit numeric(14, 2);
-- The single most important line in this migration.
--
-- A stored 0 would block every commit for that key, and NULL-read-as-0 is the
-- catastrophic failure mode of the whole feature. Making zero unrepresentable
-- at the storage layer means that state cannot be reached even by a bad UI
-- write, a bad PATCH body, or a bad backfill. Absence of a limit is expressed
-- ONLY as NULL, never as 0.
ALTER TABLE public.api_keys
DROP CONSTRAINT IF EXISTS api_keys_unattended_commit_limit_positive;
-- Added VALIDATED, not NOT VALID: api_keys is 388 rows / 768 kB in production,
-- so the validating scan is sub-millisecond. The NOT VALID + VALIDATE dance
-- buys nothing at this size and can leave the constraint permanently unenforced
-- if the second statement is ever skipped.
ALTER TABLE public.api_keys
ADD CONSTRAINT api_keys_unattended_commit_limit_positive
CHECK (unattended_commit_limit IS NULL OR unattended_commit_limit > 0);
COMMENT ON COLUMN public.api_keys.unattended_commit_limit IS
'SEK ceiling on what this key may commit without human approval. NULL = no limit, and NULL is the only representation of "no limit": zero is forbidden by CHECK because a stored 0 would block every commit. Over the ceiling the agent still stages the operation for a human to approve.';
-- Surface the limit on the one call that already verifies the credential.
--
-- The body below is copied VERBATIM from 20260621130000_api_keys_rotation_grace.sql
-- (the latest definition, which added previous_key_hash rotation grace) with
-- exactly two changes: unattended_commit_limit joins the RETURNS TABLE, and it
-- is selected into a variable and returned in all three RETURN QUERY branches.
-- Copying an older body would silently revert key rotation and lock out every
-- rotating integration.
DROP FUNCTION IF EXISTS public.validate_and_increment_api_key(text);
CREATE FUNCTION public.validate_and_increment_api_key(p_key_hash text)
RETURNS TABLE(
user_id uuid,
company_id uuid,
api_key_id uuid,
api_key_name text,
rate_limited boolean,
scopes text[],
mode text,
unattended_commit_limit numeric
)
LANGUAGE plpgsql SECURITY DEFINER AS $$
DECLARE
v_id uuid;
v_user_id uuid;
v_company_id uuid;
v_api_key_name text;
v_rate_limit_rpm integer;
v_request_count integer;
v_window_start timestamptz;
v_scopes text[];
v_mode text;
v_unattended_commit_limit numeric;
BEGIN
-- Match the live key_hash, OR a previous (just-rotated) key_hash that is still
-- inside its grace window. Both gated by revoked_at IS NULL.
SELECT ak.id, ak.user_id, ak.company_id, ak.name,
ak.rate_limit_rpm, ak.request_count, ak.rate_limit_window_start, ak.scopes, ak.mode,
ak.unattended_commit_limit
INTO v_id, v_user_id, v_company_id, v_api_key_name,
v_rate_limit_rpm, v_request_count, v_window_start, v_scopes, v_mode,
v_unattended_commit_limit
FROM public.api_keys ak
WHERE ak.revoked_at IS NULL
AND (
ak.key_hash = p_key_hash
OR (
ak.previous_key_hash = p_key_hash
AND ak.previous_key_expires_at IS NOT NULL
AND ak.previous_key_expires_at > now()
)
)
FOR UPDATE;
IF v_id IS NULL THEN
RETURN; -- no live match (incl. expired grace) → caller returns 401, as before
END IF;
-- Reset the rate-limit window if it is unset or older than one minute.
IF v_window_start IS NULL OR v_window_start < now() - interval '1 minute' THEN
UPDATE public.api_keys
SET request_count = 1,
rate_limit_window_start = now(),
last_used_at = now()
WHERE id = v_id;
RETURN QUERY SELECT v_user_id, v_company_id, v_id, v_api_key_name, false, v_scopes, v_mode,
v_unattended_commit_limit;
RETURN;
END IF;
IF v_request_count >= v_rate_limit_rpm THEN
RETURN QUERY SELECT v_user_id, v_company_id, v_id, v_api_key_name, true, v_scopes, v_mode,
v_unattended_commit_limit;
RETURN;
END IF;
UPDATE public.api_keys
SET request_count = request_count + 1,
last_used_at = now()
WHERE id = v_id;
RETURN QUERY SELECT v_user_id, v_company_id, v_id, v_api_key_name, false, v_scopes, v_mode,
v_unattended_commit_limit;
END;
$$;
NOTIFY pgrst, 'reload schema';