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
@@ -20,7 +20,8 @@ vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
// PATCH (edit title) goes through withRouteContext → requireAuth.
|
||||
// Both handlers go through withRouteContext, which resolves the session via
|
||||
// requireAuth (the MFA-enforcing guard on hosted).
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: vi.fn(),
|
||||
}))
|
||||
@@ -31,6 +32,7 @@ vi.mock('@/lib/sandbox/guard', () => ({
|
||||
|
||||
import { DELETE, PATCH } from '../route'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
@@ -40,11 +42,20 @@ describe('DELETE /api/transactions/[id]', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
|
||||
vi.mocked(requireAuth).mockResolvedValue({
|
||||
user: mockUser as never,
|
||||
supabase: mockSupabase as never,
|
||||
error: null,
|
||||
})
|
||||
vi.mocked(requireWritePermission).mockResolvedValue({ ok: true } as never)
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
vi.mocked(requireAuth).mockResolvedValue({
|
||||
user: null as never,
|
||||
supabase: mockSupabase as never,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const request = new Request('http://localhost/api/transactions/tx-1', { method: 'DELETE' })
|
||||
const response = await DELETE(request, createMockRouteParams({ id: 'tx-1' }))
|
||||
@@ -54,6 +65,29 @@ describe('DELETE /api/transactions/[id]', () => {
|
||||
expect(body).toEqual({ error: 'Unauthorized' })
|
||||
})
|
||||
|
||||
it('never calls supabase.auth.getUser() directly (MFA is enforced by the wrapper)', async () => {
|
||||
const tx = makeTransaction({ journal_entry_id: null, bank_connection_id: null, import_source: null })
|
||||
enqueue({ data: tx, error: null }) // fetch
|
||||
enqueue({ data: null, error: null }) // delete
|
||||
|
||||
const request = new Request('http://localhost/api/transactions/tx-1', { method: 'DELETE' })
|
||||
await DELETE(request, createMockRouteParams({ id: 'tx-1' }))
|
||||
|
||||
expect(requireAuth).toHaveBeenCalledTimes(1)
|
||||
expect(mockSupabase.auth.getUser).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 403 for a viewer (requireWrite)', async () => {
|
||||
vi.mocked(requireWritePermission).mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
|
||||
} as never)
|
||||
|
||||
const request = new Request('http://localhost/api/transactions/tx-1', { method: 'DELETE' })
|
||||
const response = await DELETE(request, createMockRouteParams({ id: 'tx-1' }))
|
||||
expect(response.status).toBe(403)
|
||||
})
|
||||
|
||||
it('returns 404 when transaction not found', async () => {
|
||||
enqueue({ data: null, error: { message: 'Not found' } })
|
||||
|
||||
|
||||
+100
-110
@@ -1,7 +1,4 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
@@ -10,126 +7,119 @@ import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
import { isImportedTransaction } from '@/lib/transactions/origin'
|
||||
import type { Transaction } from '@/types'
|
||||
|
||||
export async function DELETE(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const supabase = await createClient()
|
||||
const { id } = await params
|
||||
// withRouteContext enforces auth (MFA on hosted), resolves the active
|
||||
// companyId and rejects viewers via requireWrite. The previous hand-rolled
|
||||
// session lookup in this handler skipped the MFA gate entirely.
|
||||
export const DELETE = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'transaction.delete',
|
||||
async (_request, { supabase, companyId }, { params }) => {
|
||||
const { id } = await params
|
||||
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
// Fetch the transaction with ownership check. `bank_connection_id` +
|
||||
// `import_source` tell us where the row came from (see the imported guard below).
|
||||
const { data: transaction, error: fetchError } = await supabase
|
||||
.from('transactions')
|
||||
.select('id, journal_entry_id, bank_connection_id, import_source')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
const writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
// Fetch the transaction with ownership check. `bank_connection_id` +
|
||||
// `import_source` tell us where the row came from (see the imported guard below).
|
||||
const { data: transaction, error: fetchError } = await supabase
|
||||
.from('transactions')
|
||||
.select('id, journal_entry_id, bank_connection_id, import_source')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (fetchError || !transaction) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'TRANSACTION_NOT_FOUND',
|
||||
message: 'Transaktionen hittades inte.',
|
||||
message_en: 'Transaction not found.',
|
||||
},
|
||||
},
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
// Guard: only unbooked transactions can be deleted. A booked/matched row is
|
||||
// räkenskapsinformation: the fix is to unlink (reconciliation) or storno, not
|
||||
// delete. Return a structured bilingual envelope so the UI shows this clear,
|
||||
// actionable message instead of the generic "Ladda om sidan" 409 fallback.
|
||||
if (transaction.journal_entry_id) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'TRANSACTION_DELETE_BOOKED',
|
||||
message:
|
||||
'Transaktionen är redan bokförd eller kopplad till en verifikation och kan inte raderas. Koppla bort den under Rapporter → Bankavstämning om kopplingen är fel, eller storna verifikationen.',
|
||||
message_en:
|
||||
'The transaction is already booked or linked to a journal entry and cannot be deleted. Unlink it under Reports → Bank reconciliation if the link is wrong, or reverse (storno) the voucher.',
|
||||
},
|
||||
},
|
||||
{ status: 409 }
|
||||
)
|
||||
}
|
||||
|
||||
// Guard: only transactions the user created in the app can be deleted. Rows
|
||||
// fetched via bank sync or uploaded via a bank-file import are an external
|
||||
// record of money that moved: deleting one would silently drop a real bank
|
||||
// line (and a re-sync would just bring it back). The user can *ignore* such a
|
||||
// row (POST /api/transactions/[id]/ignore) to take it off the to-book list,
|
||||
// but never delete it. See lib/transactions/origin.ts for the origin rule.
|
||||
if (isImportedTransaction(transaction)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'TRANSACTION_DELETE_IMPORTED',
|
||||
message:
|
||||
'Transaktionen har hämtats från banken eller importerats via fil och kan inte raderas. Du kan ignorera den så att den döljs från listan över transaktioner att bokföra.',
|
||||
message_en:
|
||||
'This transaction was fetched from your bank or imported from a file and cannot be deleted. You can ignore it to hide it from the list of transactions to book.',
|
||||
},
|
||||
},
|
||||
{ status: 409 }
|
||||
)
|
||||
}
|
||||
|
||||
const { error: deleteError } = await supabase
|
||||
.from('transactions')
|
||||
.delete()
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
|
||||
if (deleteError) {
|
||||
// An unbooked row can still carry payment_match_log rows (written at ingest
|
||||
// for every auto-suggested match). Their FK cascades on delete, but the
|
||||
// audit-immutability trigger raises P0001: surface that as an actionable
|
||||
// message (match or ignore instead) rather than a bare 500.
|
||||
const code = (deleteError as { code?: string }).code
|
||||
const message = (deleteError as { message?: string }).message ?? ''
|
||||
if (code === 'P0001' || /Audit log entries cannot be modified or deleted/i.test(message)) {
|
||||
if (fetchError || !transaction) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'TRANSACTION_DELETE_HAS_AUDIT_TRAIL',
|
||||
code: 'TRANSACTION_NOT_FOUND',
|
||||
message: 'Transaktionen hittades inte.',
|
||||
message_en: 'Transaction not found.',
|
||||
},
|
||||
},
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
// Guard: only unbooked transactions can be deleted. A booked/matched row is
|
||||
// räkenskapsinformation: the fix is to unlink (reconciliation) or storno, not
|
||||
// delete. Return a structured bilingual envelope so the UI shows this clear,
|
||||
// actionable message instead of the generic "Ladda om sidan" 409 fallback.
|
||||
if (transaction.journal_entry_id) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'TRANSACTION_DELETE_BOOKED',
|
||||
message:
|
||||
'Transaktionen kan inte raderas eftersom den har en kopplad matchningshistorik (räkenskapsinformation, BFL 7 kap.). Matcha den mot en befintlig verifikation, eller ignorera den under Rapporter → Bankavstämning om du inte vill bokföra den.',
|
||||
'Transaktionen är redan bokförd eller kopplad till en verifikation och kan inte raderas. Koppla bort den under Rapporter → Bankavstämning om kopplingen är fel, eller storna verifikationen.',
|
||||
message_en:
|
||||
'The transaction cannot be deleted because it has linked match-history records (accounting information, BFL ch. 7). Match it to an existing voucher, or ignore it under Reports → Bank reconciliation if you do not want to book it.',
|
||||
'The transaction is already booked or linked to a journal entry and cannot be deleted. Unlink it under Reports → Bank reconciliation if the link is wrong, or reverse (storno) the voucher.',
|
||||
},
|
||||
},
|
||||
{ status: 409 }
|
||||
)
|
||||
}
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'TRANSACTION_DELETE_FAILED',
|
||||
message: 'Kunde inte ta bort transaktionen. Försök igen.',
|
||||
message_en: 'Could not delete the transaction. Please try again.',
|
||||
},
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
}
|
||||
// Guard: only transactions the user created in the app can be deleted. Rows
|
||||
// fetched via bank sync or uploaded via a bank-file import are an external
|
||||
// record of money that moved: deleting one would silently drop a real bank
|
||||
// line (and a re-sync would just bring it back). The user can *ignore* such a
|
||||
// row (POST /api/transactions/[id]/ignore) to take it off the to-book list,
|
||||
// but never delete it. See lib/transactions/origin.ts for the origin rule.
|
||||
if (isImportedTransaction(transaction)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'TRANSACTION_DELETE_IMPORTED',
|
||||
message:
|
||||
'Transaktionen har hämtats från banken eller importerats via fil och kan inte raderas. Du kan ignorera den så att den döljs från listan över transaktioner att bokföra.',
|
||||
message_en:
|
||||
'This transaction was fetched from your bank or imported from a file and cannot be deleted. You can ignore it to hide it from the list of transactions to book.',
|
||||
},
|
||||
},
|
||||
{ status: 409 }
|
||||
)
|
||||
}
|
||||
|
||||
const { error: deleteError } = await supabase
|
||||
.from('transactions')
|
||||
.delete()
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
|
||||
if (deleteError) {
|
||||
// An unbooked row can still carry payment_match_log rows (written at ingest
|
||||
// for every auto-suggested match). Their FK cascades on delete, but the
|
||||
// audit-immutability trigger raises P0001: surface that as an actionable
|
||||
// message (match or ignore instead) rather than a bare 500.
|
||||
const code = (deleteError as { code?: string }).code
|
||||
const message = (deleteError as { message?: string }).message ?? ''
|
||||
if (code === 'P0001' || /Audit log entries cannot be modified or deleted/i.test(message)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'TRANSACTION_DELETE_HAS_AUDIT_TRAIL',
|
||||
message:
|
||||
'Transaktionen kan inte raderas eftersom den har en kopplad matchningshistorik (räkenskapsinformation, BFL 7 kap.). Matcha den mot en befintlig verifikation, eller ignorera den under Rapporter → Bankavstämning om du inte vill bokföra den.',
|
||||
message_en:
|
||||
'The transaction cannot be deleted because it has linked match-history records (accounting information, BFL ch. 7). Match it to an existing voucher, or ignore it under Reports → Bank reconciliation if you do not want to book it.',
|
||||
},
|
||||
},
|
||||
{ status: 409 }
|
||||
)
|
||||
}
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'TRANSACTION_DELETE_FAILED',
|
||||
message: 'Kunde inte ta bort transaktionen. Försök igen.',
|
||||
message_en: 'Could not delete the transaction. Please try again.',
|
||||
},
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
|
||||
/**
|
||||
* Edit a bank transaction's title (description).
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import {
|
||||
createMockRequest,
|
||||
createMockRouteParams,
|
||||
parseJsonResponse,
|
||||
createQueuedMockSupabase,
|
||||
makeTransaction,
|
||||
@@ -16,7 +17,14 @@ vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
// GET goes through withRouteContext, which resolves the session via requireAuth.
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: vi.fn(),
|
||||
}))
|
||||
|
||||
import { GET } from '../route'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
describe('GET /api/transactions', () => {
|
||||
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
||||
@@ -26,14 +34,22 @@ describe('GET /api/transactions', () => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
mockSupabase.from = originalFrom
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
|
||||
vi.mocked(requireAuth).mockResolvedValue({
|
||||
user: mockUser as never,
|
||||
supabase: mockSupabase as never,
|
||||
error: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
vi.mocked(requireAuth).mockResolvedValue({
|
||||
user: null as never,
|
||||
supabase: mockSupabase as never,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/transactions')
|
||||
const response = await GET(request)
|
||||
const response = await GET(request, createMockRouteParams({}))
|
||||
const { status, body } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(401)
|
||||
@@ -48,7 +64,7 @@ describe('GET /api/transactions', () => {
|
||||
enqueue({ data: txs, error: null })
|
||||
|
||||
const request = createMockRequest('/api/transactions')
|
||||
const response = await GET(request)
|
||||
const response = await GET(request, createMockRouteParams({}))
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: typeof txs
|
||||
has_more: boolean
|
||||
@@ -70,7 +86,7 @@ describe('GET /api/transactions', () => {
|
||||
enqueue({ data: txs, error: null })
|
||||
|
||||
const request = createMockRequest('/api/transactions')
|
||||
const response = await GET(request)
|
||||
const response = await GET(request, createMockRouteParams({}))
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: typeof txs
|
||||
has_more: boolean
|
||||
@@ -102,7 +118,7 @@ describe('GET /api/transactions', () => {
|
||||
mockSupabase.from = fromSpy as unknown as typeof mockSupabase.from
|
||||
|
||||
const request = createMockRequest('/api/transactions?unmatched=true')
|
||||
await GET(request)
|
||||
await GET(request, createMockRouteParams({}))
|
||||
|
||||
expect(fromSpy).toHaveBeenCalledWith('transactions')
|
||||
const chain = fromSpy.mock.results[0].value as { __calls: { method: string; args: unknown[] }[] }
|
||||
@@ -129,7 +145,7 @@ describe('GET /api/transactions', () => {
|
||||
mockSupabase.from = fromSpy as unknown as typeof mockSupabase.from
|
||||
|
||||
const request = createMockRequest('/api/transactions?reconciled=true')
|
||||
await GET(request)
|
||||
await GET(request, createMockRouteParams({}))
|
||||
|
||||
const chain = fromSpy.mock.results[0].value as { __calls: { method: string; args: unknown[] }[] }
|
||||
const notCall = chain.__calls.find((c) => c.method === 'not')
|
||||
@@ -160,7 +176,7 @@ describe('GET /api/transactions', () => {
|
||||
const request = createMockRequest(
|
||||
'/api/transactions?currency=SEK&date_from=2024-01-01&date_to=2024-12-31'
|
||||
)
|
||||
await GET(request)
|
||||
await GET(request, createMockRouteParams({}))
|
||||
|
||||
const chain = fromSpy.mock.results[0].value as { __calls: { method: string; args: unknown[] }[] }
|
||||
const eqCalls = chain.__calls.filter((c) => c.method === 'eq')
|
||||
@@ -183,7 +199,7 @@ describe('GET /api/transactions', () => {
|
||||
enqueue({ data: null, error: { message: 'boom' } })
|
||||
|
||||
const request = createMockRequest('/api/transactions')
|
||||
const response = await GET(request)
|
||||
const response = await GET(request, createMockRouteParams({}))
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(500)
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { scopeTransactionsToAccount } from '@/lib/reconciliation/bank-reconciliation'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
@@ -9,16 +7,9 @@ import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-m
|
||||
|
||||
const MAX_ROWS = 500
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
// withRouteContext enforces auth (MFA on hosted) and resolves companyId; the
|
||||
// previous hand-rolled session lookup in this handler skipped the MFA gate.
|
||||
export const GET = withRouteContext('transaction.list', async (request, { supabase, companyId }) => {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const unmatched = searchParams.get('unmatched') === 'true'
|
||||
const reconciled = searchParams.get('reconciled') === 'true'
|
||||
@@ -107,7 +98,7 @@ export async function GET(request: Request) {
|
||||
const truncated = hasMore ? rows.slice(0, MAX_ROWS) : rows
|
||||
|
||||
return NextResponse.json({ data: truncated, has_more: hasMore, limit: MAX_ROWS })
|
||||
}
|
||||
})
|
||||
|
||||
// Manual bank-transaction creation. This is the server-side boundary the form
|
||||
// now goes through (it used to insert straight into Supabase from the browser).
|
||||
|
||||
Reference in New Issue
Block a user