fix(auth): route document integrity, transaction delete/list and agent categorize through withRouteContext (#1926)
Two handlers hand-rolled supabase.auth.getUser() and therefore skipped the MFA (AAL2) gate on hosted: DELETE /api/transactions/[id] and GET /api/transactions. Both sat next to a sibling handler that was already wrapped, and the raw-route-auth ratchet exempted a file as soon as any withRouteContext call appeared in it, so they were never flagged. GET /api/documents/[id]/integrity and POST /api/agent/categorize called requireAuth() directly (MFA enforced, but no request id, no completion log, no canonical error envelope). All four are now withRouteContext handlers with identical company scoping and responses; the transaction delete keeps its viewer rejection via requireWrite. The guard now judges each top-level export segment of a route file on its own, so a wrapped handler no longer exempts a hand-rolled sibling. Baseline is unchanged (mcp-oauth/authorize remains the one grandfathered file). Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Jakob Wennberg
Claude Fable 5
parent
d3869e6694
commit
1a27b5bd4a
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
import { createMockRequest, createMockRouteParams, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({ requireAuth: () => requireAuthMock() }))
|
||||
@@ -26,11 +26,12 @@ vi.mock('@/lib/agent/categorize/select-account', () => ({ selectAccount: (...a:
|
||||
import { POST } from '../route'
|
||||
|
||||
// supabase router: membership + transactions + companies + company_settings.
|
||||
function makeSupabase(opts: { tx?: unknown } = {}) {
|
||||
function makeSupabase(opts: { tx?: unknown; member?: boolean } = {}) {
|
||||
return {
|
||||
auth: { getUser: vi.fn() },
|
||||
from(table: string) {
|
||||
const rows: Record<string, unknown> = {
|
||||
company_members: { user_id: 'user-1' },
|
||||
company_members: opts.member === false ? null : { user_id: 'user-1' },
|
||||
transactions: opts.tx === undefined ? { id: 'tx-1' } : opts.tx,
|
||||
companies: { entity_type: 'aktiebolag' },
|
||||
company_settings: { vat_registered: true },
|
||||
@@ -67,23 +68,41 @@ beforeEach(() => {
|
||||
describe('POST /api/agent/categorize', () => {
|
||||
it('401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: null, supabase, error: NextResponse.json({ error: 'x' }, { status: 401 }) })
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }))).status).toBe(401)
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))).status).toBe(401)
|
||||
expect(selectAccount).not.toHaveBeenCalled()
|
||||
})
|
||||
it('resolves the session through requireAuth (withRouteContext), never a hand-rolled getUser()', async () => {
|
||||
await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
|
||||
expect(requireAuthMock).toHaveBeenCalledTimes(1)
|
||||
expect(supabase.auth.getUser).not.toHaveBeenCalled()
|
||||
})
|
||||
it('403 when the body names a company the caller is not a member of', async () => {
|
||||
const other = '22222222-2222-4222-8222-222222222222'
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: makeSupabase({ member: false }), error: null })
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ company_id: other }) }), createMockRouteParams({}))
|
||||
expect(res.status).toBe(403)
|
||||
expect(selectAccount).not.toHaveBeenCalled()
|
||||
})
|
||||
it('uses the active company without a membership round trip when no override is given', async () => {
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
|
||||
expect(res.status).toBe(200)
|
||||
expect(gatherCandidates).toHaveBeenCalledWith(expect.anything(), 'company-1', expect.anything())
|
||||
})
|
||||
it('429 when rate limited', async () => {
|
||||
checkRate.mockResolvedValue({ ok: false })
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }))).status).toBe(429)
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))).status).toBe(429)
|
||||
})
|
||||
it('400 on a missing/invalid transaction_id', async () => {
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: {} }))).status).toBe(400)
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: { transaction_id: 'nope' } }))).status).toBe(400)
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: {} }), createMockRouteParams({}))).status).toBe(400)
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: { transaction_id: 'nope' } }), createMockRouteParams({}))).status).toBe(400)
|
||||
})
|
||||
it('403 without the ai capability', async () => {
|
||||
requireCapability.mockResolvedValue(NextResponse.json({ error: 'pay' }, { status: 403 }))
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }))).status).toBe(403)
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))).status).toBe(403)
|
||||
})
|
||||
it('503 when no backend is configured', async () => {
|
||||
aiStatus.mockReturnValue({ configured: false })
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }))
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
|
||||
const { status, body: b } = await parseJsonResponse<{ code: string }>(res)
|
||||
expect(status).toBe(503)
|
||||
expect(b.code).toBe('ai_unconfigured')
|
||||
@@ -91,12 +110,12 @@ describe('POST /api/agent/categorize', () => {
|
||||
})
|
||||
it('404 when the transaction is not found / not this company', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: makeSupabase({ tx: null }), error: null })
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }))
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
|
||||
expect(res.status).toBe(404)
|
||||
expect(selectAccount).not.toHaveBeenCalled()
|
||||
})
|
||||
it('returns the selection + candidate slate on the happy path', async () => {
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ samples: 3, underlag: 'Biltema AB 499 kr' }) }))
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ samples: 3, underlag: 'Biltema AB 499 kr' }) }), createMockRouteParams({}))
|
||||
const { status, body: b } = await parseJsonResponse<{
|
||||
data: { account: string; confidence: number; candidates: { account: string }[] }
|
||||
}>(res)
|
||||
@@ -112,7 +131,7 @@ describe('POST /api/agent/categorize', () => {
|
||||
})
|
||||
|
||||
it('gathers underlag server-side when the caller did not supply it', async () => {
|
||||
await POST(createMockRequest('/x', { method: 'POST', body: body() }))
|
||||
await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
|
||||
expect(gatherUnderlag).toHaveBeenCalled()
|
||||
expect(selectAccount).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ underlag: 'Kvitto: Biltema, totalt 499 SEK.' }),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { checkAgentRateLimit, agentRateLimitResponseBody } from '@/lib/rate-limits/agent'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
import { requireCapability } from '@/lib/entitlements/has-capability'
|
||||
@@ -37,91 +36,96 @@ const Schema = z.object({
|
||||
samples: z.number().int().min(1).max(5).optional(),
|
||||
})
|
||||
|
||||
export async function POST(request: Request): Promise<Response> {
|
||||
const { user, supabase, error } = await requireAuth()
|
||||
if (error) return error
|
||||
// withRouteContext enforces auth (MFA on hosted) and resolves the active
|
||||
// company; the body may still name another company the caller belongs to.
|
||||
export const POST = withRouteContext(
|
||||
'agent.categorize',
|
||||
async (request, { user, supabase, companyId: activeCompanyId }) => {
|
||||
const rate = await checkAgentRateLimit(supabase, user.id)
|
||||
if (!rate.ok) return NextResponse.json(agentRateLimitResponseBody(rate), { status: 429 })
|
||||
|
||||
const rate = await checkAgentRateLimit(supabase, user.id)
|
||||
if (!rate.ok) return NextResponse.json(agentRateLimitResponseBody(rate), { status: 429 })
|
||||
let body: unknown
|
||||
try {
|
||||
body = await request.json()
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
|
||||
}
|
||||
const parsed = Schema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: 'Ogiltig förfrågan.', type: 'validation_error' }, { status: 400 })
|
||||
}
|
||||
|
||||
let body: unknown
|
||||
try {
|
||||
body = await request.json()
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
|
||||
}
|
||||
const parsed = Schema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: 'Ogiltig förfrågan.', type: 'validation_error' }, { status: 400 })
|
||||
}
|
||||
const companyId = parsed.data.company_id ?? activeCompanyId
|
||||
|
||||
const companyId = parsed.data.company_id ?? (await getActiveCompanyId(supabase, user.id))
|
||||
if (!companyId) return NextResponse.json({ error: 'No active company' }, { status: 400 })
|
||||
// The wrapper already guarantees membership of the active company; an
|
||||
// explicit company_id override must be verified the same way.
|
||||
if (companyId !== activeCompanyId) {
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('user_id')
|
||||
.eq('company_id', companyId)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
}
|
||||
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('user_id')
|
||||
.eq('company_id', companyId)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
const blocked = await guardSandbox(supabase, companyId)
|
||||
if (blocked) return blocked
|
||||
|
||||
const blocked = await guardSandbox(supabase, companyId)
|
||||
if (blocked) return blocked
|
||||
const capBlocked = await requireCapability(supabase, companyId, CAPABILITY.ai)
|
||||
if (capBlocked) return capBlocked
|
||||
|
||||
const capBlocked = await requireCapability(supabase, companyId, CAPABILITY.ai)
|
||||
if (capBlocked) return capBlocked
|
||||
if (!getAiStatus().configured) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Assistenten är inte konfigurerad på den här installationen.', code: 'ai_unconfigured' },
|
||||
{ status: 503 },
|
||||
)
|
||||
}
|
||||
|
||||
if (!getAiStatus().configured) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Assistenten är inte konfigurerad på den här installationen.', code: 'ai_unconfigured' },
|
||||
{ status: 503 },
|
||||
)
|
||||
}
|
||||
const { data: tx } = await supabase
|
||||
.from('transactions')
|
||||
.select('id, merchant_name, description, original_description, amount, date, currency, category, is_business, document_id')
|
||||
.eq('id', parsed.data.transaction_id)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
if (!tx) return NextResponse.json({ error: 'Transaktionen hittades inte.' }, { status: 404 })
|
||||
|
||||
const { data: tx } = await supabase
|
||||
.from('transactions')
|
||||
.select('id, merchant_name, description, original_description, amount, date, currency, category, is_business, document_id')
|
||||
.eq('id', parsed.data.transaction_id)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
if (!tx) return NextResponse.json({ error: 'Transaktionen hittades inte.' }, { status: 404 })
|
||||
const [{ data: company }, { data: settings }] = await Promise.all([
|
||||
supabase.from('companies').select('entity_type').eq('id', companyId).maybeSingle(),
|
||||
supabase.from('company_settings').select('vat_registered').eq('company_id', companyId).maybeSingle(),
|
||||
])
|
||||
|
||||
const [{ data: company }, { data: settings }] = await Promise.all([
|
||||
supabase.from('companies').select('entity_type').eq('id', companyId).maybeSingle(),
|
||||
supabase.from('company_settings').select('vat_registered').eq('company_id', companyId).maybeSingle(),
|
||||
])
|
||||
try {
|
||||
// Gather the matched receipt/invoice text when the caller didn't supply it:
|
||||
// this is what lifts the cold-start case — the model reads the actual
|
||||
// supplier + line items, not just the bank line. Best-effort; '' if none.
|
||||
const underlag =
|
||||
parsed.data.underlag ??
|
||||
(await gatherUnderlag(
|
||||
supabase,
|
||||
companyId,
|
||||
(tx as Transaction).id,
|
||||
(tx as { document_id?: string | null }).document_id,
|
||||
))
|
||||
|
||||
try {
|
||||
// Gather the matched receipt/invoice text when the caller didn't supply it:
|
||||
// this is what lifts the cold-start case — the model reads the actual
|
||||
// supplier + line items, not just the bank line. Best-effort; '' if none.
|
||||
const underlag =
|
||||
parsed.data.underlag ??
|
||||
(await gatherUnderlag(
|
||||
supabase,
|
||||
companyId,
|
||||
(tx as Transaction).id,
|
||||
(tx as { document_id?: string | null }).document_id,
|
||||
))
|
||||
|
||||
const candidates = await gatherCandidates(supabase, companyId, tx as Transaction)
|
||||
const selection = await selectAccount({
|
||||
transaction: {
|
||||
merchantName: (tx as Transaction).merchant_name,
|
||||
description: (tx as Transaction).description,
|
||||
amount: (tx as Transaction).amount,
|
||||
date: (tx as Transaction).date,
|
||||
currency: (tx as Transaction).currency,
|
||||
},
|
||||
underlag,
|
||||
candidates,
|
||||
entityType: ((company?.entity_type as EntityType | undefined) ?? 'enskild_firma'),
|
||||
vatRegistered: settings?.vat_registered ?? false,
|
||||
samples: parsed.data.samples,
|
||||
})
|
||||
return NextResponse.json({ data: { ...selection, candidates } })
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: getUserErrorMessage(err) }, { status: 500 })
|
||||
}
|
||||
}
|
||||
const candidates = await gatherCandidates(supabase, companyId, tx as Transaction)
|
||||
const selection = await selectAccount({
|
||||
transaction: {
|
||||
merchantName: (tx as Transaction).merchant_name,
|
||||
description: (tx as Transaction).description,
|
||||
amount: (tx as Transaction).amount,
|
||||
date: (tx as Transaction).date,
|
||||
currency: (tx as Transaction).currency,
|
||||
},
|
||||
underlag,
|
||||
candidates,
|
||||
entityType: ((company?.entity_type as EntityType | undefined) ?? 'enskild_firma'),
|
||||
vatRegistered: settings?.vat_registered ?? false,
|
||||
samples: parsed.data.samples,
|
||||
})
|
||||
return NextResponse.json({ data: { ...selection, candidates } })
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: getUserErrorMessage(err) }, { status: 500 })
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user