* 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>
126 lines
5.3 KiB
TypeScript
126 lines
5.3 KiB
TypeScript
/**
|
|
* Approval-authority limit: what an API key may commit WITHOUT a human.
|
|
*
|
|
* This is not a write limit. Over the ceiling the operation stays staged and a
|
|
* person approves it in /pending, so nothing is destroyed, no voucher number is
|
|
* burned, and no löpnummer gap appears (BFL 5 kap. 7 §).
|
|
*
|
|
* ## What this control is, and is not
|
|
*
|
|
* It is a blast-radius cap on an agent that is looping, mis-prompted or
|
|
* prompt-injected. It is NOT a security boundary: a per-entry ceiling is
|
|
* defeated by splitting one large entry into several small ones, and an LLM
|
|
* will discover that on its own, because "reduce the amount and retry" is the
|
|
* obvious repair for "amount too large".
|
|
*
|
|
* That bypass is itself a compliance violation, since one affärshändelse is one
|
|
* verifikat (BFL 5 kap. 6 §), which is why the UNATTENDED_COMMIT_LIMIT_EXCEEDED
|
|
* remediation tells the agent not to split BEFORE it tells it anything else.
|
|
* A rolling-window cumulative limit is the primitive that actually bounds
|
|
* exposure; it is deliberately a separate change.
|
|
*/
|
|
|
|
/**
|
|
* Every operation type that posts money, with the preview_data field carrying
|
|
* the amount it will post.
|
|
*
|
|
* An explicit allowlist, and every entry is verified against production rather
|
|
* than guessed. Over the last 120 days each field below is present and numeric
|
|
* on 100% of that type's staged rows:
|
|
*
|
|
* create_voucher total_debit 1389 rows
|
|
* categorize_transaction amount 2003 rows
|
|
* create_supplier_invoice_from_inbox total 228 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
|
|
*
|
|
* The staged preview already carries the amount the operation intends to post,
|
|
* because that is the number a human is shown when approving it. An earlier
|
|
* draft of this file assumed the batch and settlement paths computed their
|
|
* totals only inside SQL at dispatch and therefore left them unpriced; that was
|
|
* wrong, and it left the four largest settlement paths able to post any amount
|
|
* on a key with a ceiling.
|
|
*
|
|
* Types deliberately absent, and why:
|
|
* - reconciliation_match carries pair_count, a COUNT, not an amount. Pricing
|
|
* it off that number would compare pairs against kronor. It stays unpriced.
|
|
* - link_document_to_voucher and attach_document_to_transaction move no
|
|
* money; they attach räkenskapsinformation to something already booked.
|
|
* - create_customer, create_transaction and the rest of the registry post
|
|
* nothing to the ledger.
|
|
*
|
|
* Anything not listed is unpriceable and FAILS OPEN. That is the safe direction
|
|
* for a control that can only ever narrow what a key does: a wrong guess at an
|
|
* amount blocks a legitimate commit, and the failure mode of guessing high is
|
|
* an agent that cannot work at all.
|
|
*/
|
|
const PRICEABLE_OPERATIONS: Readonly<Record<string, readonly string[]>> = {
|
|
create_voucher: ['total_debit'],
|
|
categorize_transaction: ['amount'],
|
|
create_supplier_invoice_from_inbox: ['total'],
|
|
link_transaction_journal_entry: ['transaction_amount'],
|
|
bulk_book_transactions: ['tx_sum'],
|
|
link_supplier_invoice_voucher: ['payment_amount'],
|
|
match_batch_allocate: ['total_allocated'],
|
|
mark_invoice_paid: ['total'],
|
|
}
|
|
|
|
/**
|
|
* The SEK amount this operation would post, or null when it cannot be priced
|
|
* before dispatch.
|
|
*
|
|
* Null always means "do not enforce". Every parse failure, missing field and
|
|
* unknown operation type lands here on purpose.
|
|
*/
|
|
export function priceOperation(
|
|
operationType: string,
|
|
previewData: unknown,
|
|
): number | null {
|
|
const fields = PRICEABLE_OPERATIONS[operationType]
|
|
if (!fields) return null
|
|
if (previewData === null || typeof previewData !== 'object') return null
|
|
|
|
const record = previewData as Record<string, unknown>
|
|
for (const field of fields) {
|
|
const raw = record[field]
|
|
if (raw === null || raw === undefined) continue
|
|
// jsonb numerics can arrive as strings; parse rather than trusting
|
|
// comparison coercion.
|
|
const parsed = typeof raw === 'number' ? raw : Number(raw)
|
|
if (Number.isFinite(parsed)) return Math.abs(parsed)
|
|
}
|
|
return null
|
|
}
|
|
|
|
/**
|
|
* True when this commit needs a human first.
|
|
*
|
|
* Written NULL-first in every clause. Absence of a limit, absence of a price,
|
|
* and any non-api_key actor all return false, so the control can only ever
|
|
* narrow what an API key does unattended and can never touch a human, a cron
|
|
* or an in-app approval.
|
|
*/
|
|
export function exceedsUnattendedLimit(params: {
|
|
actorType: string | undefined
|
|
limit: number | null | undefined
|
|
operationType: string
|
|
previewData: unknown
|
|
}): { exceeded: boolean; attempted: number | null; limit: number | null } {
|
|
const limit =
|
|
typeof params.limit === 'number' && Number.isFinite(params.limit) && params.limit > 0
|
|
? params.limit
|
|
: null
|
|
|
|
if (params.actorType !== 'api_key' || limit === null) {
|
|
return { exceeded: false, attempted: null, limit }
|
|
}
|
|
|
|
const attempted = priceOperation(params.operationType, params.previewData)
|
|
if (attempted === null) return { exceeded: false, attempted: null, limit }
|
|
|
|
return { exceeded: attempted > limit, attempted, limit }
|
|
}
|