Skip to content

Commit 2fa6b59

Browse files
committed
fix(web): address CodeRabbit review findings on tRPC setup
- protectedProcedure: reject empty Bearer tokens and match __session cookie by exact key (prevents substring-in-value spoofing) - health router: add 5 s AbortSignal timeout to backend fetch - health.test.ts: unstub global fetch in afterAll to prevent leakage; update fetch assertion to include options argument - auth.test.ts: add edge-case tests for empty Bearer, empty cookie value, and __session= appearing inside another cookie's value - Extract getBaseUrl to lib/trpc/utils.ts; add @vitest-environment node unit tests covering browser, Vercel, and localhost branches - Add lib/trpc/__tests__/server.test.ts: unit tests for createServerCaller with mocked next/headers and react.cache - backend: pin testcontainers postgres image to postgres:16
1 parent 2c30572 commit 2fa6b59

9 files changed

Lines changed: 102 additions & 15 deletions

File tree

‎backend/internal/infrastructure/database/postgres/health_repository_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ func mustStartPostgresContainer() (func(context.Context, ...testcontainers.Termi
2323

2424
container, err := tcpostgres.Run(
2525
context.Background(),
26-
"postgres:latest",
26+
"postgres:16",
2727
tcpostgres.WithDatabase(dbName),
2828
tcpostgres.WithUsername(dbUser),
2929
tcpostgres.WithPassword(dbPwd),
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { describe, it, expect, vi } from 'vitest'
2+
3+
vi.mock('next/headers', () => ({
4+
headers: vi.fn(async () => new Headers({ 'x-test': 'true' })),
5+
}))
6+
7+
vi.mock('react', async (importOriginal) => {
8+
const actual = await importOriginal<typeof import('react')>()
9+
return { ...actual, cache: (fn: unknown) => fn }
10+
})
11+
12+
const { createServerCaller } = await import('../server')
13+
14+
describe('createServerCaller', () => {
15+
it('returns a caller with the expected router shape', async () => {
16+
const caller = await createServerCaller()
17+
expect(typeof caller.health.query).toBe('function')
18+
expect(typeof caller.auth.session).toBe('function')
19+
expect(typeof caller.auth.signOut).toBe('function')
20+
expect(typeof caller.notifications.list).toBe('function')
21+
})
22+
23+
it('propagates request headers into the tRPC context', async () => {
24+
const { headers } = await import('next/headers')
25+
const mockHeaders = new Headers({ authorization: 'Bearer test-token' })
26+
vi.mocked(headers).mockResolvedValueOnce(mockHeaders as Awaited<ReturnType<typeof headers>>)
27+
const caller = await createServerCaller()
28+
expect(caller).toBeDefined()
29+
})
30+
})
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// @vitest-environment node
2+
import { describe, it, expect, afterEach } from 'vitest'
3+
import { getBaseUrl } from '../utils'
4+
5+
afterEach(() => {
6+
delete process.env.VERCEL_URL
7+
})
8+
9+
describe('getBaseUrl', () => {
10+
it('returns empty string when window is defined (browser)', () => {
11+
// In jsdom/browser environments window is defined; here we simulate it in node
12+
const g = global as Record<string, unknown>
13+
g.window = {}
14+
try {
15+
expect(getBaseUrl()).toBe('')
16+
} finally {
17+
delete g.window
18+
}
19+
})
20+
21+
it('returns Vercel URL when VERCEL_URL env var is set', () => {
22+
process.env.VERCEL_URL = 'my-app.vercel.app'
23+
expect(getBaseUrl()).toBe('https://my-app.vercel.app')
24+
})
25+
26+
it('falls back to localhost:3000', () => {
27+
expect(getBaseUrl()).toBe('http://localhost:3000')
28+
})
29+
})

‎web/lib/trpc/client.tsx‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,10 @@ import { useState } from 'react'
55
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
66
import { httpBatchLink } from '@trpc/client'
77
import type { AppRouter } from '@/server/routers/_app'
8+
import { getBaseUrl } from './utils'
89

910
export const trpc = createTRPCReact<AppRouter>()
1011

11-
function getBaseUrl() {
12-
if (typeof window !== 'undefined') return ''
13-
if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`
14-
return 'http://localhost:3000'
15-
}
16-
1712
export function TRPCProvider({ children }: { children: React.ReactNode }) {
1813
const [queryClient] = useState(() => new QueryClient())
1914
const [trpcClient] = useState(() =>

‎web/lib/trpc/utils.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export function getBaseUrl() {
2+
if (typeof window !== 'undefined') return ''
3+
if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`
4+
return 'http://localhost:3000'
5+
}

‎web/server/routers/__tests__/auth.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,22 @@ describe('protectedProcedure', () => {
2929
const result = await caller.auth.session()
3030
expect(result).toEqual({ authenticated: true })
3131
})
32+
33+
it('throws UNAUTHORIZED for empty Bearer token', async () => {
34+
const ctx = await makeContext({ authorization: 'Bearer ' })
35+
const caller = appRouter.createCaller(ctx)
36+
await expect(caller.auth.session()).rejects.toMatchObject({ code: 'UNAUTHORIZED' })
37+
})
38+
39+
it('throws UNAUTHORIZED for __session cookie with empty value', async () => {
40+
const ctx = await makeContext({ cookie: '__session=' })
41+
const caller = appRouter.createCaller(ctx)
42+
await expect(caller.auth.session()).rejects.toMatchObject({ code: 'UNAUTHORIZED' })
43+
})
44+
45+
it('throws UNAUTHORIZED when __session= appears only in another cookie value', async () => {
46+
const ctx = await makeContext({ cookie: 'other=__session=abc' })
47+
const caller = appRouter.createCaller(ctx)
48+
await expect(caller.auth.session()).rejects.toMatchObject({ code: 'UNAUTHORIZED' })
49+
})
3250
})

‎web/server/routers/__tests__/health.test.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
import { describe, it, expect, vi, beforeEach } from 'vitest'
1+
import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest'
22
import { appRouter } from '../_app'
33
import { createTRPCContext } from '../../trpc'
44

5-
// mock fetch
65
const mockFetch = vi.fn()
76
vi.stubGlobal('fetch', mockFetch)
7+
afterAll(() => vi.unstubAllGlobals())
88

99
function makeContext(reqHeaders: Record<string, string> = {}) {
1010
const req = new Request('http://localhost/api/trpc', { headers: reqHeaders }) as import('next/server').NextRequest
@@ -24,7 +24,10 @@ describe('health router', () => {
2424
const caller = appRouter.createCaller(ctx)
2525
const result = await caller.health.query()
2626
expect(result).toEqual({ status: 'ok', database: 'ok' })
27-
expect(mockFetch).toHaveBeenCalledWith(expect.stringContaining('/health'))
27+
expect(mockFetch).toHaveBeenCalledWith(
28+
expect.stringContaining('/health'),
29+
expect.objectContaining({ signal: expect.any(AbortSignal) })
30+
)
2831
})
2932

3033
it('throws when backend is down', async () => {

‎web/server/routers/health.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ const BACKEND_URL = process.env.BACKEND_URL ?? 'http://localhost:8080'
44

55
export const healthRouter = router({
66
query: publicProcedure.query(async () => {
7-
const res = await fetch(`${BACKEND_URL}/health`)
7+
const res = await fetch(`${BACKEND_URL}/health`, { signal: AbortSignal.timeout(5000) })
88
if (!res.ok) throw new Error(`Backend health check failed: ${res.status}`)
99
return res.json() as Promise<{ status: string; database: string }>
1010
}),

‎web/server/trpc.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,21 @@ export const router = t.router
1616
export const createCallerFactory = t.createCallerFactory
1717
export const publicProcedure = t.procedure
1818
export const protectedProcedure = t.procedure.use(async ({ ctx, next }) => {
19-
// Read session token from Authorization header (Bearer) or __session cookie
2019
const authHeader = ctx.req.headers.get('authorization')
2120
const cookieHeader = ctx.req.headers.get('cookie')
2221

23-
const hasBearer = authHeader?.startsWith('Bearer ')
24-
const hasSessionCookie = cookieHeader?.includes('__session=')
22+
const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7).trim() : null
23+
const hasValidBearer = typeof bearerToken === 'string' && bearerToken.length > 0
2524

26-
if (!hasBearer && !hasSessionCookie) {
25+
const sessionValue = cookieHeader
26+
?.split(';')
27+
.map(c => c.trim())
28+
.find(c => c.startsWith('__session='))
29+
?.slice('__session='.length)
30+
.trim()
31+
const hasValidSessionCookie = typeof sessionValue === 'string' && sessionValue.length > 0
32+
33+
if (!hasValidBearer && !hasValidSessionCookie) {
2734
throw new TRPCError({ code: 'UNAUTHORIZED' })
2835
}
2936

0 commit comments

Comments
 (0)