Files
accounted/tests/pg/api-key-unattended-commit-limit.pg.test.ts
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

136 lines
5.8 KiB
TypeScript

import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { insertAuthUser, insertCompany } from './fixtures'
import { getPool } from './setup'
/**
* api_keys.unattended_commit_limit (migration 20260831111519).
*
* The column is the storage half of the approval-authority envelope; the
* enforcement half is TypeScript (lib/pending-operations/unattended-limit.ts),
* deliberately, because a RAISE inside commit_journal_entry is swallowed into
* a retryable 500 and burns the staged operation.
*
* What must hold in the database, and is what these tests pin:
* 1. the column exists, is nullable, and defaults to NULL (unlimited), so
* every key that existed before this migration keeps its behaviour;
* 2. the CHECK rejects 0 and negatives, so "limit = 0" can never be stored
* and silently read back as falsy-therefore-unlimited;
* 3. validate_and_increment_api_key returns it, with exactly ONE signature
* (adding a parameter or return column to a Postgres function creates an
* overload rather than replacing it, and PostgREST then 300s on the
* ambiguity: see migration 20260421140000);
* 4. writing it produces an audit_log row, since changing how much an agent
* may post without a human is a change to who approves the company's
* bookkeeping (BFL 5 kap. 11 paragraf).
*/
describe('api_keys.unattended_commit_limit (pg)', () => {
async function seedKey(limit: number | null = null) {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
const apiKeyId = randomUUID()
const keyHash = randomUUID().replaceAll('-', '')
await getPool().query(
`INSERT INTO public.api_keys
(id, user_id, company_id, key_hash, key_prefix, name, scopes, unattended_commit_limit)
VALUES ($1, $2, $3, $4, 'gnubok_sk_test', 'Envelope test key', $5, $6)`,
[apiKeyId, userId, companyId, keyHash, ['reports:read'], limit],
)
return { userId, companyId, apiKeyId, keyHash }
}
it('defaults to NULL so pre-existing keys stay unlimited', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
// Deliberately omits the column instead of storing an explicit NULL: this
// test exists to pin the DATABASE DEFAULT, and passing NULL in would keep
// it green even if the default changed to a positive ceiling, which is the
// one change that would silently start blocking every existing key.
const { rows } = await getPool().query<{ unattended_commit_limit: string | null }>(
`INSERT INTO public.api_keys
(user_id, company_id, key_hash, key_prefix, name, scopes)
VALUES ($1, $2, $3, 'gnubok_sk_test', 'Default test key', $4)
RETURNING unattended_commit_limit`,
[userId, companyId, randomUUID().replaceAll('-', ''), ['reports:read']],
)
expect(rows[0]!.unattended_commit_limit).toBeNull()
})
it('rejects a zero or negative ceiling with the CHECK constraint', async () => {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
for (const bad of [0, -1]) {
await expect(
getPool().query(
`INSERT INTO public.api_keys
(user_id, company_id, key_hash, key_prefix, name, scopes, unattended_commit_limit)
VALUES ($1, $2, $3, 'gnubok_sk_test', 'Bad ceiling', $4, $5)`,
[userId, companyId, randomUUID().replaceAll('-', ''), ['reports:read'], bad],
),
).rejects.toMatchObject({
code: '23514',
constraint: 'api_keys_unattended_commit_limit_positive',
})
}
})
it('validate_and_increment_api_key returns the ceiling, and has exactly one signature', async () => {
const { keyHash } = await seedKey(2500)
const overloads = await getPool().query<{ n: number }>(
`SELECT count(*)::int AS n
FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace
WHERE n.nspname = 'public' AND p.proname = 'validate_and_increment_api_key'`,
)
expect(overloads.rows[0]!.n).toBe(1)
const { rows } = await getPool().query<{
unattended_commit_limit: string | null
rate_limited: boolean
}>(`SELECT * FROM public.validate_and_increment_api_key($1)`, [keyHash])
expect(rows).toHaveLength(1)
expect(rows[0]!.rate_limited).toBe(false)
// numeric comes back as a string from node-postgres; compare numerically.
expect(Number(rows[0]!.unattended_commit_limit)).toBe(2500)
})
it('returns NULL for a key with no ceiling, not 0', async () => {
const { keyHash } = await seedKey(null)
const { rows } = await getPool().query<{ unattended_commit_limit: string | null }>(
`SELECT * FROM public.validate_and_increment_api_key($1)`,
[keyHash],
)
// The whole guard is written NULL-first. A 0 here would read as a real
// ceiling on the way in and block every commit the key attempts.
expect(rows[0]!.unattended_commit_limit).toBeNull()
})
it('records a ceiling change in audit_log', async () => {
const { apiKeyId } = await seedKey(null)
await getPool().query(
`UPDATE public.api_keys SET unattended_commit_limit = 10000 WHERE id = $1`,
[apiKeyId],
)
const { rows } = await getPool().query<{
action: string
old_limit: string | null
new_limit: string | null
}>(
`SELECT action,
old_state ->> 'unattended_commit_limit' AS old_limit,
new_state ->> 'unattended_commit_limit' AS new_limit
FROM public.audit_log
WHERE table_name = 'api_keys' AND record_id = $1 AND action = 'UPDATE'
ORDER BY created_at, id`,
[apiKeyId],
)
expect(rows).toHaveLength(1)
expect(rows[0]!.old_limit).toBeNull()
expect(Number(rows[0]!.new_limit)).toBe(10000)
})
})