Files
accounted/app/api/agent/__tests__/invoke.test.ts
T
Jakob WennbergandClaude Opus 5 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

225 lines
7.3 KiB
TypeScript

/**
* Tests for POST /api/agent/invoke, focused on conversation ownership.
*
* RLS on agent_conversations/agent_messages is company-scoped, not user-scoped
* (migration 20260517204000), so the route itself has to prove that a resumed
* conversation_id belongs to the caller. Without that check, a member could
* post a colleague's conversation id and have their history loaded into the
* prompt (and their own turns appended to it).
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const checkRateMock = vi.fn()
vi.mock('@/lib/rate-limits/agent', () => ({
checkAgentRateLimit: (...args: unknown[]) => checkRateMock(...args),
agentRateLimitResponseBody: () => ({ error: 'För många förfrågningar.' }),
}))
vi.mock('@/lib/sandbox/guard', () => ({
guardSandbox: vi.fn().mockResolvedValue(null),
}))
vi.mock('@/lib/entitlements/has-capability', () => ({
requireCapability: vi.fn().mockResolvedValue(null),
}))
vi.mock('@/lib/entitlements/keys', () => ({
CAPABILITY: { ai: 'ai' },
}))
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
const getIntentMock = vi.fn()
vi.mock('@/lib/agent/intents/registry', () => ({
getIntent: (...args: unknown[]) => getIntentMock(...args),
}))
const runChatTurnMock = vi.fn()
vi.mock('@/lib/agent/chat/run-turn', () => ({
runChatTurn: (...args: unknown[]) => runChatTurnMock(...args),
friendlyModelError: () => 'Något gick fel hos assistenten.',
}))
import { POST } from '../invoke/route'
const CONVERSATION_ID = '11111111-1111-4111-8111-111111111111'
function body(overrides: Record<string, unknown> = {}) {
return {
intent_id: 'general.help',
user_message: 'Hur gick juli?',
...overrides,
}
}
/**
* Queue the reads the route performs before it resolves the conversation.
*
* Ownership is validated ahead of every side effect and of the company/profile
* reads, so a rejected request costs exactly one membership read plus the
* conversation lookup.
*/
function enqueuePreamble() {
enqueue({ data: { role: 'owner' } }) // company_members
}
/** The company + profile reads that only happen once a request is accepted. */
function enqueueAcceptedTail() {
enqueue({ data: { name: 'Nordvik Bygg AB' } }) // companies
enqueue({ data: { full_name: 'Johan Nordvik' } }) // profiles
}
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
checkRateMock.mockResolvedValue({ ok: true })
getIntentMock.mockReturnValue({ id: 'general.help', sheetTitle: 'Assistenten' })
runChatTurnMock.mockResolvedValue(undefined)
})
describe('POST /api/agent/invoke', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: body() }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(401)
})
it('returns 400 on an invalid body', async () => {
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: { intent_id: '' } }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(400)
})
it('returns 400 for an unknown intent', async () => {
getIntentMock.mockReturnValue(undefined)
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: body() }))
const { status } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(400)
})
it('returns 403 when the user is not a member of the company', async () => {
enqueue({ data: null }) // company_members: no row
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: body() }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(403)
})
it('returns 404 when resuming a conversation owned by another user', async () => {
enqueuePreamble()
enqueue({
data: {
id: CONVERSATION_ID,
user_id: 'user-2', // someone else in the same company
company_id: 'company-1',
intent_id: 'general.help',
},
})
const res = await POST(
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
)
const { status, body: json } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(404)
expect(json.error).toBe('Konversationen hittades inte.')
expect(runChatTurnMock).not.toHaveBeenCalled()
})
it('returns 404 when resuming a conversation from another company', async () => {
enqueuePreamble()
enqueue({
data: {
id: CONVERSATION_ID,
user_id: 'user-1', // same user...
company_id: 'company-2', // ...but a company other than the active one
intent_id: 'general.help',
},
})
const res = await POST(
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
)
const { status } = await parseJsonResponse(res)
expect(status).toBe(404)
expect(runChatTurnMock).not.toHaveBeenCalled()
})
it('returns 404 when the conversation does not exist', async () => {
enqueuePreamble()
enqueue({ data: null })
const res = await POST(
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
)
const { status } = await parseJsonResponse(res)
expect(status).toBe(404)
expect(runChatTurnMock).not.toHaveBeenCalled()
})
it('returns 400 when the conversation belongs to a different intent', async () => {
enqueuePreamble()
enqueue({
data: {
id: CONVERSATION_ID,
user_id: 'user-1',
company_id: 'company-1',
intent_id: 'vat.review', // tool loadout differs from general.help
},
})
const res = await POST(
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
)
const { status } = await parseJsonResponse(res)
expect(status).toBe(400)
expect(runChatTurnMock).not.toHaveBeenCalled()
})
it('runs the turn when the caller owns the conversation', async () => {
enqueuePreamble()
enqueue({
data: {
id: CONVERSATION_ID,
user_id: 'user-1',
company_id: 'company-1',
intent_id: 'general.help',
},
})
enqueueAcceptedTail()
const res = await POST(
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
)
expect(res.status).toBe(200)
// The route streams NDJSON; draining it is enough to know the turn ran.
await res.text()
expect(runChatTurnMock).toHaveBeenCalledTimes(1)
})
})