c31933b15b
* perf(api): write routes stop re-resolving the active company
withRouteContext resolves the active company (one resolve_active_company
RPC, ~40 ms p50 on prod) and then, for the 256 routes that pass
requireWrite: true, called requireWritePermission(), which resolved it a
second time before its role select. Two sequential round trips repeating
work the wrapper had just done, on every mutating request.
requireWritePermission() and getCompanyRole() now accept an optional
`known` context; the wrapper passes { companyId }, so the helper goes
straight to the membership select. Callers that pass nothing behave
exactly as before, and the shared selectRole() keeps both helpers on the
same query. The role is still looked up, never trusted from the caller.
Tests: known companyId skips resolution, known role skips the select, a
known viewer is still 403, a known company without a membership row is
still 403, legacy calls unchanged; new lib/api/__tests__/with-route-
context.test.ts pins that the wrapper resolves the company exactly once,
hands it to the guard, never calls the guard on read routes, passes the
guard's 403 through with a request id, and emits Server-Timing.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* test(customers): viewer gate expects the wrapper to hand over the resolved company
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
92 lines
2.8 KiB
TypeScript
92 lines
2.8 KiB
TypeScript
/**
|
|
* Representative viewer-403 test.
|
|
*
|
|
* Verifies that POST /api/customers returns 403 when the caller's
|
|
* requireWritePermission check returns an error response. This is a
|
|
* canary test: if it breaks, the wiring between mutating routes and
|
|
* requireWritePermission has drifted.
|
|
*
|
|
* The full per-role behavior of requireWritePermission itself is
|
|
* covered in lib/auth/__tests__/require-write.test.ts.
|
|
*/
|
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
import { NextResponse } from 'next/server'
|
|
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
|
|
|
const mockAuthGetUser = vi.fn()
|
|
const mockFrom = vi.fn()
|
|
const mockSupabase = {
|
|
auth: { getUser: mockAuthGetUser },
|
|
from: mockFrom,
|
|
}
|
|
|
|
vi.mock('@/lib/supabase/server', () => ({
|
|
createClient: () => Promise.resolve(mockSupabase),
|
|
}))
|
|
|
|
vi.mock('@/lib/init', () => ({
|
|
ensureInitialized: vi.fn(),
|
|
}))
|
|
|
|
vi.mock('@/lib/company/context', () => ({
|
|
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
|
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
|
}))
|
|
|
|
const requireWritePermissionMock = vi.fn()
|
|
vi.mock('@/lib/auth/require-write', () => ({
|
|
requireWritePermission: (...args: unknown[]) => requireWritePermissionMock(...args),
|
|
}))
|
|
|
|
import { POST } from '../route'
|
|
|
|
describe('POST /api/customers: viewer role gate', () => {
|
|
const mockUser = { id: 'user-1', email: 'viewer@test.se' }
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
mockAuthGetUser.mockResolvedValue({ data: { user: mockUser } })
|
|
})
|
|
|
|
it('returns 403 with Swedish message when requireWritePermission rejects', async () => {
|
|
requireWritePermissionMock.mockResolvedValue({
|
|
ok: false,
|
|
response: NextResponse.json(
|
|
{ error: 'Du har endast läsbehörighet i detta företag.' },
|
|
{ status: 403 },
|
|
),
|
|
})
|
|
|
|
const request = createMockRequest('/api/customers', {
|
|
method: 'POST',
|
|
body: { name: 'Test customer', customer_type: 'company' },
|
|
})
|
|
|
|
const response = await POST(request)
|
|
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
|
|
|
expect(status).toBe(403)
|
|
expect(body.error).toContain('läsbehörighet')
|
|
})
|
|
|
|
it('calls requireWritePermission with the authenticated user id', async () => {
|
|
requireWritePermissionMock.mockResolvedValue({
|
|
ok: false,
|
|
response: NextResponse.json({ error: 'blocked' }, { status: 403 }),
|
|
})
|
|
|
|
const request = createMockRequest('/api/customers', {
|
|
method: 'POST',
|
|
body: { name: 'Test customer', customer_type: 'company' },
|
|
})
|
|
|
|
await POST(request)
|
|
|
|
// The wrapper hands over the company it already resolved so the guard
|
|
// does not repeat the resolve_active_company round trip.
|
|
expect(requireWritePermissionMock).toHaveBeenCalledWith(mockSupabase, 'user-1', {
|
|
companyId: 'company-1',
|
|
})
|
|
})
|
|
})
|