Files
accounted/lib/agent/chat/__tests__/run-turn-dangling-tools.test.ts
T
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

170 lines
5.9 KiB
TypeScript

import { describe, it, expect } from 'vitest'
import { repairDanglingToolUse } from '../run-turn'
/**
* A turn persists the assistant message carrying tool_use blocks BEFORE the
* tools run, and their tool_result blocks only after the whole batch finishes.
* If the process dies in between (client disconnect terminating the function,
* a deploy, a tool outliving the request), the stored history ends on an
* unanswered tool_use. The Messages API rejects that shape, so every later turn
* 400s, and agent_messages is append-only (BFL audit trail) so nothing can
* repair the row: the conversation is bricked permanently.
*
* repairDanglingToolUse patches the shape on READ only, leaving the stored
* trail untouched.
*/
const textBlock = (text: string) => [{ type: 'text', text }]
describe('repairDanglingToolUse', () => {
it('leaves a well-formed conversation untouched', () => {
const messages = [
{ role: 'user' as const, content: textBlock('Boka om Circle K') },
{
role: 'assistant' as const,
content: [
{ type: 'tool_use', id: 'tu_1', name: 'gnubok_query_journal', input: {} },
],
},
{
role: 'user' as const,
content: [{ type: 'tool_result', tool_use_id: 'tu_1', content: 'A-207' }],
},
{ role: 'assistant' as const, content: textBlock('Klart att godkänna.') },
]
expect(repairDanglingToolUse(messages)).toEqual(messages)
})
it('synthesizes an error tool_result for an unanswered tool_use', () => {
const messages = [
{ role: 'user' as const, content: textBlock('Gör klart juli') },
{
role: 'assistant' as const,
content: [{ type: 'tool_use', id: 'tu_dead', name: 'gnubok_list_transactions', input: {} }],
},
]
const repaired = repairDanglingToolUse(messages)
expect(repaired).toHaveLength(3)
expect(repaired[2]).toEqual({
role: 'user',
content: [
{
type: 'tool_result',
tool_use_id: 'tu_dead',
content: expect.stringContaining('Avbröts'),
is_error: true,
},
],
})
})
it('repairs only the unanswered call in a mixed batch', () => {
const messages = [
{
role: 'assistant' as const,
content: [
{ type: 'tool_use', id: 'tu_ok', name: 'a', input: {} },
{ type: 'tool_use', id: 'tu_dead', name: 'b', input: {} },
],
},
{
role: 'user' as const,
content: [{ type: 'tool_result', tool_use_id: 'tu_ok', content: 'fine' }],
},
]
const repaired = repairDanglingToolUse(messages)
const synthesized = repaired.filter(
(m) =>
Array.isArray(m.content) &&
m.content.some((b: { is_error?: boolean }) => b.is_error === true),
)
expect(synthesized).toHaveLength(1)
expect(synthesized[0]!.content).toHaveLength(1)
expect(synthesized[0]!.content[0].tool_use_id).toBe('tu_dead')
})
it('inserts the stub immediately after the assistant turn that opened it', () => {
const messages = [
{
role: 'assistant' as const,
content: [{ type: 'tool_use', id: 'tu_dead', name: 'a', input: {} }],
},
{ role: 'user' as const, content: textBlock('är du kvar?') },
]
const repaired = repairDanglingToolUse(messages)
// The stub must sit between the tool_use and the next user turn, otherwise
// the API still sees an unanswered tool_use followed by a user message.
expect(repaired.map((m) => m.role)).toEqual(['assistant', 'user', 'user'])
expect(repaired[1]!.content[0].tool_use_id).toBe('tu_dead')
expect(repaired[2]!.content[0].text).toBe('är du kvar?')
})
it('repairs a result that arrived after an intervening turn', () => {
// Two turns racing on one conversation can persist a user message between
// the tool_use and its results. The id IS answered somewhere, but not in
// the message immediately following the tool_use, which the API still
// rejects: the stub has to go in the gap and the late copy has to go.
const messages = [
{
role: 'assistant' as const,
content: [{ type: 'tool_use', id: 'tu_late', name: 'a', input: {} }],
},
{ role: 'user' as const, content: textBlock('hallå?') },
{
role: 'user' as const,
content: [{ type: 'tool_result', tool_use_id: 'tu_late', content: 'sent too late' }],
},
]
const repaired = repairDanglingToolUse(messages)
// Stub sits directly after the tool_use...
expect(repaired[1]!.content[0]).toMatchObject({
type: 'tool_result',
tool_use_id: 'tu_late',
is_error: true,
})
// ...the intervening user text survives...
expect(repaired[2]!.content[0].text).toBe('hallå?')
// ...and the orphaned late result is gone, along with its emptied message.
const lateResults = repaired
.flatMap((m) => (Array.isArray(m.content) ? m.content : []))
.filter((b: { content?: string }) => b?.content === 'sent too late')
expect(lateResults).toHaveLength(0)
})
it('drops a tool_result whose tool_use never preceded it', () => {
const messages = [
{ role: 'user' as const, content: textBlock('hej') },
{
role: 'user' as const,
content: [{ type: 'tool_result', tool_use_id: 'tu_ghost', content: 'orphan' }],
},
]
const repaired = repairDanglingToolUse(messages)
// An unmatched tool_result is rejected by the API just as an unanswered
// tool_use is, so the emptied message is dropped entirely.
expect(repaired).toHaveLength(1)
expect(repaired[0]!.content[0].text).toBe('hej')
})
it('tolerates string and non-array content without throwing', () => {
const messages = [
{ role: 'user' as const, content: 'plain string content' as unknown as [] },
{ role: 'assistant' as const, content: null as unknown as [] },
]
expect(() => repairDanglingToolUse(messages)).not.toThrow()
expect(repairDanglingToolUse(messages)).toHaveLength(2)
})
})