Files
supabase/apps/studio/lib/api/createApiHandlers.test.ts
Alaister YoungandAlaister Young b6c391a058 [FE-5114] (part 1) – refactor(studio): add native API helpers & routes (#54028)
## Problem

Studio's `routes/api/**` server routes still run legacy Next Pages
Router handlers through the `toWebHandler` shim in `compat/next/api.ts`.
Part 1 of 7 for
[FE-5114](https://linear.app/supabase/issue/FE-5114/rewrite-api-routes-as-native-tanstack-start-handlers-and-remove-the)
adds native TanStack Start (`Request` → `Response`) helpers and migrates
the top-level utility routes so we can remove the adapter at the end of
the stack.

## Solution

**Added:**

- `createApiHandlers` in `lib/api/apiWrapper.ts`: wraps native TanStack
Start route handlers with optional platform JWT auth, JSON `400` (`{
error: { message: 'Invalid JSON' } }`) on `InvalidJsonError`, Sentry
capture + generic `500` on unexpected throws, and an `ANY` handler that
returns `405` with an `Allow` header derived from the registered
methods. Exports `ApiHandler` / `ApiHandlerContext` (`params` is
`Record<string, string>`)
- `authenticateRequest` in `lib/api/apiAuthenticate.ts` (Web `Request`
counterpart of `apiAuthenticate`, same error messages)
- `InvalidJsonError` and `parseJsonBody` in `lib/api/apiHelpers.ts`
- `callRoute(route, request, params)` test helper in
`tests/lib/server-route.ts`
- Unit tests for `createApiHandlers` (exercising real
`authenticateRequest` through MSW in
`lib/api/createApiHandlers.test.ts`), `authenticateRequest`,
`parseJsonBody`, `/api/generate-attachment-url`, and
`/api/integrations/stripe-sync`

**Changed:**

- Updated `getRouteHandler` in `tests/lib/server-route.ts` to mirror
TanStack Start's `HEAD` → `GET` → `ANY` dispatch order
- Migrated 11 top-level API routes (`check-cname`,
`cli-release-version`, `content/graphql`, `edge-functions/test`,
`enabled-features-overrides`, `generate-attachment-url`,
`get-deployment-commit`, `get-ip-address`, `get-s3-keys`,
`get-utc-time`, `integrations/stripe-sync`) to native handlers
- Added `withAuth: true` to `check-cname`, `content/graphql`, and
`integrations/stripe-sync`, and updated `check-cname-mutation.ts` and
`data/graphql/execute.ts` to attach `constructHeaders()`
- Reused `withAuth` `claims` in `generate-attachment-url` to avoid a
duplicate GoTrue lookup in platform mode
- Converted `tests/routes/api/get-deployment-commit.test.ts` to
`callRoute`

**Removed:**

- Removed 2 unused routes (`routes/api/connect/index.ts` and
`routes/api/parse-query.ts`), dropped `/parse-query` from
`lib/hosted-api-allowlist.ts`, removed Nitro's `traceDeps:
['libpg-query*']` in `vite.config.ts` (no server runtime route imports
`libpg-query` anymore), and regenerated `routeTree.gen.ts`

**Behavior changes vs master:**

- Methods a route doesn't register now get a JSON `405` with an `Allow`
header (previously they fell through to the SSR app). `HEAD` requests
that TanStack Start dispatches to a `GET` handler also get `405`,
matching master's method switches
- `InvalidJsonError` returns JSON `{ error: { message: 'Invalid JSON' }
}` (`400`) instead of plain text
- `check-cname`, `content/graphql`, and `integrations/stripe-sync` now
verify the platform JWT via `withAuth: true`
- Unexpected throws return a generic `500` with `{ error: { message:
'Internal Server Error' } }`
- Unused `/api/connect` and `/api/parse-query` routes have been removed

## Review instructions

1. Run `pnpm --filter studio exec vitest run
lib/api/apiAuthenticate.test.ts lib/api/apiHelpers.test.ts
lib/api/apiWrappers.test.ts lib/api/createApiHandlers.test.ts
tests/routes/api/ scripts/__tests__/server-source-maps.test.ts`.
2. Smoke-test `/api/get-deployment-commit`, `/api/check-cname`,
`/api/content/graphql`, `/api/generate-attachment-url`, and
`/api/edge-functions/test` in Studio and confirm unsupported HTTP
methods return `405` with an `Allow` header.

## Checklist

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [ ] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-01 20:53:57 +08:00

242 lines
7.7 KiB
TypeScript

import type { User } from '@supabase/auth-js'
import { http, HttpResponse } from 'msw'
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
import { mswServer } from '@/tests/lib/msw'
import { callRoute } from '@/tests/lib/server-route'
vi.mock('@sentry/react', () => ({
captureException: vi.fn(),
}))
type GoTrueErrorResponse = { msg: string }
const GOTRUE_URL = 'https://auth.example.test'
function createJwt(sub: string): string {
const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url')
const payload = Buffer.from(
JSON.stringify({
sub,
aud: 'authenticated',
role: 'authenticated',
exp: Math.floor(Date.now() / 1000) + 3600,
})
).toString('base64url')
const signature = Buffer.from('test-signature').toString('base64url')
return `${header}.${payload}.${signature}`
}
describe('createApiHandlers', () => {
let Sentry: typeof import('@sentry/react')
let InvalidJsonError: typeof import('./apiHelpers').InvalidJsonError
let createApiHandlers: typeof import('./apiWrapper').createApiHandlers
beforeAll(async () => {
vi.resetModules()
vi.stubEnv('NEXT_PUBLIC_IS_PLATFORM', 'true')
vi.stubEnv('NEXT_PUBLIC_GOTRUE_URL', GOTRUE_URL)
Sentry = await import('@sentry/react')
;({ InvalidJsonError } = await import('./apiHelpers'))
;({ createApiHandlers } = await import('./apiWrapper'))
})
afterEach(() => {
vi.mocked(Sentry.captureException).mockClear()
vi.restoreAllMocks()
})
afterAll(() => {
vi.unstubAllEnvs()
vi.resetModules()
})
it('calls the handler directly without auth when withAuth is omitted', async () => {
const goTrueCalls = vi.fn()
mswServer.use(
http.get(`${GOTRUE_URL}/user`, () => {
goTrueCalls()
return HttpResponse.json<GoTrueErrorResponse>(
{ msg: 'Should not be called' },
{ status: 500 }
)
})
)
const handler = vi.fn(({ params }) => Response.json({ id: params.id }))
const handlers = createApiHandlers({ GET: handler })
const request = new Request('http://localhost/api/test')
const response = await handlers.GET({ request, params: { id: 'abc' } })
expect(response.status).toBe(200)
expect(await response.json()).toEqual({ id: 'abc' })
expect(handler).toHaveBeenCalledWith({ request, params: { id: 'abc' }, claims: undefined })
expect(goTrueCalls).not.toHaveBeenCalled()
})
it('passes verified JWT claims to the handler when withAuth is true', async () => {
const token = createJwt('user-123')
mswServer.use(
http.get<never, never, User | GoTrueErrorResponse>(`${GOTRUE_URL}/user`, ({ request }) => {
if (request.headers.get('authorization') !== `Bearer ${token}`) {
return HttpResponse.json<GoTrueErrorResponse>({ msg: 'Invalid JWT' }, { status: 401 })
}
return HttpResponse.json<User>({
id: 'user-123',
aud: 'authenticated',
app_metadata: {},
user_metadata: {},
created_at: '2026-01-01T00:00:00Z',
})
})
)
const handler = vi.fn(({ claims }) => Response.json({ sub: claims?.sub }))
const handlers = createApiHandlers({ POST: handler }, { withAuth: true })
const request = new Request('http://localhost/api/test', {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
})
const response = await handlers.POST({ request })
expect(response.status).toBe(200)
expect(await response.json()).toEqual({ sub: 'user-123' })
})
it('returns 401 without calling GoTrue when the Authorization header is missing', async () => {
const goTrueCalls = vi.fn()
mswServer.use(
http.get(`${GOTRUE_URL}/user`, () => {
goTrueCalls()
return HttpResponse.json<GoTrueErrorResponse>(
{ msg: 'Should not be called' },
{ status: 500 }
)
})
)
const handler = vi.fn()
const handlers = createApiHandlers({ POST: handler }, { withAuth: true })
const response = await handlers.POST({
request: new Request('http://localhost/api/test', { method: 'POST' }),
})
expect(response.status).toBe(401)
expect(await response.json()).toEqual({
error: { message: 'Unauthorized: missing access token' },
})
expect(handler).not.toHaveBeenCalled()
expect(goTrueCalls).not.toHaveBeenCalled()
})
it('returns 401 when GoTrue rejects the token', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
const token = createJwt('user-123')
mswServer.use(
http.get(`${GOTRUE_URL}/user`, () =>
HttpResponse.json<GoTrueErrorResponse>({ msg: 'Invalid JWT' }, { status: 401 })
)
)
const handler = vi.fn()
const handlers = createApiHandlers({ POST: handler }, { withAuth: true })
const response = await handlers.POST({
request: new Request('http://localhost/api/test', {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
}),
})
expect(response.status).toBe(401)
expect(await response.json()).toEqual({
error: { message: 'Unauthorized: Invalid JWT' },
})
expect(handler).not.toHaveBeenCalled()
})
it('returns 400 without reporting to Sentry when InvalidJsonError is thrown', async () => {
const handlers = createApiHandlers({
POST: () => {
throw new InvalidJsonError()
},
})
const response = await handlers.POST({
request: new Request('http://localhost/api/test', { method: 'POST' }),
})
expect(response.status).toBe(400)
expect(await response.json()).toEqual({ error: { message: 'Invalid JSON' } })
expect(Sentry.captureException).not.toHaveBeenCalled()
})
it('reports to Sentry and returns generic 500 when the handler throws', async () => {
const error = new SyntaxError('Handler bug')
const handlers = createApiHandlers({
GET: () => {
throw error
},
})
const response = await handlers.GET({
request: new Request('http://localhost/api/test'),
})
expect(Sentry.captureException).toHaveBeenCalledWith(error)
expect(response.status).toBe(500)
expect(await response.json()).toEqual({ error: { message: 'Internal Server Error' } })
})
it('returns 405 with an Allow header matching registered methods via ANY', async () => {
const handlers = createApiHandlers({
PATCH: () => Response.json({ ok: true }),
DELETE: () => new Response(null, { status: 204 }),
})
const response = await handlers.ANY({
request: new Request('http://localhost/api/test', { method: 'GET' }),
})
expect(response.status).toBe(405)
expect(response.headers.get('Allow')).toBe('PATCH, DELETE')
expect(await response.json()).toEqual({
data: null,
error: { message: 'Method GET Not Allowed' },
})
})
it('returns 405 for a HEAD request dispatched to a GET-only handler', async () => {
const handler = vi.fn(() => Response.json({ ok: true }))
const route = { options: { server: { handlers: createApiHandlers({ GET: handler }) } } }
const response = await callRoute(
route,
new Request('http://localhost/api/test', { method: 'HEAD' })
)
expect(response.status).toBe(405)
expect(response.headers.get('Allow')).toBe('GET')
expect(handler).not.toHaveBeenCalled()
})
it('calls an explicitly registered HEAD handler', async () => {
const handlers = createApiHandlers({
GET: () => Response.json({ ok: true }),
HEAD: () => new Response(null),
})
const route = { options: { server: { handlers } } }
const response = await callRoute(
route,
new Request('http://localhost/api/test', { method: 'HEAD' })
)
expect(response.status).toBe(200)
})
})