Skip to content

Commit 2d3fe87

Browse files
authored
fix(server): convert decode failures to BAD_REQUEST before interceptors see them (#2517)
## Problem `RethrowHandlerPlugin` runs as the outermost handler interceptor. `StandardHandler` ran `decodeInput` inside that chain, but it turned non-`ORPCError` decode failures into `ORPCError('BAD_REQUEST')` only in its catch block, after the chain had already thrown. So the rethrow `filter` got the raw `SyntaxError` or `TypeError` from parsing the body or query. With the filter the docs recommend, `!(error instanceof ORPCError)`, every malformed request was rethrown, and Express or Nest answered **500** instead of 400. Any anonymous client could trigger it: - `POST /ping` with `content-type: application/json` and body `{bad` - An RPC GET with `?data=%7Bbad` - A corrupt gzip body sent through `RequestCompressionHandlerPlugin` (a `TypeError`) ## Fix The BAD_REQUEST conversion now wraps the `decodeInput` call inside the innermost interceptor function. Every interceptor, the rethrow filter included, now sees the same error the client gets, with the original parse error kept as `cause`. Procedure errors are untouched and are still rethrown as documented. This is a change in the shared handler, not the plugin, so it covers every codec (RPC, OpenAPI, Nest, MCP). It also covers `decodeInput` replacements that interceptors pass through `next()`. ## Behavior changes for reviewers - An interceptor now sees `ORPCError('BAD_REQUEST')` for a malformed request instead of the raw `SyntaxError`/`TypeError`. As a result, `PinoHandlerPlugin` logs these at `warn` instead of `error`. - If an interceptor catches a decode error and throws a different non-ORPCError, the client now gets 500 instead of 400. That case is a bug in the interceptor. - An interceptor that calls `options.decodeInput()` itself, before `next()`, still gets the raw error. No interceptor in the repo does this. ## Tests - `rethrow.test.ts` (RPC): malformed body and query both return 400. The filter receives a `BAD_REQUEST` ORPCError. A procedure `TypeError` is still rethrown. - `openapi-handler.test.ts`: a malformed body returns 400 under `RethrowHandlerPlugin`. - `handler.test.ts`: interceptors receive the same `BAD_REQUEST` error that gets encoded. All of these fail on `main`. `pnpm check` passes. In `pnpm exec vitest run`, the only failure is the openapi-inference tsconfig test that also fails on `main`.
1 parent 77da9d6 commit 2d3fe87

4 files changed

Lines changed: 82 additions & 12 deletions

File tree

‎packages/openapi/src/adapters/fetch/openapi-handler.test.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
import { createORPCClient } from '@orpc/client'
1+
import { createORPCClient, ORPCError } from '@orpc/client'
22
import { os } from '@orpc/server'
3+
import { RethrowHandlerPlugin } from '@orpc/server/plugins'
34
import type { StandardHandlerPlugin } from '@orpc/server/standard'
45

56
import { openapi } from '../../meta'
@@ -114,3 +115,24 @@ describe('openapiHandler', () => {
114115
return expect(response!.text()).resolves.toBe('"intercepted"')
115116
})
116117
})
118+
119+
describe('openapiHandler with RethrowHandlerPlugin', () => {
120+
const ping = vi.fn()
121+
const handler = new OpenAPIHandler(
122+
{ ping: os.meta(openapi({ method: 'POST', path: '/ping' })).handler(ping) },
123+
{ plugins: [new RethrowHandlerPlugin({ filter: (error) => !(error instanceof ORPCError) })] },
124+
)
125+
126+
it('responds 400 to a malformed body instead of rethrowing it', async () => {
127+
const { response } = await handler.handle(
128+
new Request('http://localhost/ping', {
129+
method: 'POST',
130+
headers: { 'content-type': 'application/json' },
131+
body: '{bad',
132+
}),
133+
)
134+
135+
expect(response?.status).toBe(400)
136+
expect(ping).not.toHaveBeenCalled()
137+
})
138+
})

‎packages/server/src/adapters/standard/handler.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -380,8 +380,10 @@ describe('standardHandler', () => {
380380
})
381381

382382
describe('error handling', () => {
383-
it('wraps non-ORPCError decode failures as BAD_REQUEST', async () => {
383+
it('wraps non-ORPCError decode failures as BAD_REQUEST before interceptors see them', async () => {
384384
const cause = new Error('invalid body')
385+
const interceptor = vi.fn(({ next }) => next())
386+
handler = new StandardHandler(codec as any, { interceptors: [interceptor] })
385387
codec.resolveProcedure.mockResolvedValue(
386388
makeResolved({ decodeInput: vi.fn().mockRejectedValue(cause) }),
387389
)
@@ -399,6 +401,7 @@ describe('standardHandler', () => {
399401
expect(error).toBeInstanceOf(ORPCError)
400402
expect(error.code).toBe('BAD_REQUEST')
401403
expect(error.cause).toBe(cause)
404+
await expect(interceptor.mock.results[0]!.value).rejects.toBe(error)
402405
})
403406

404407
it('passes ORPCError decode failures through without wrapping', async () => {

‎packages/server/src/adapters/standard/handler.ts‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ export class StandardHandler<T extends Context> {
138138
async ({ context, prefix, request }) => {
139139
const span = getTracer()?.getActiveSpan()
140140

141-
let step: 'decode_input' | 'call_procedure' | undefined
141+
let step: 'call_procedure' | undefined
142142

143143
const matchedOrNot = await runWithSpan('find_procedure', () =>
144144
this.codec.resolveProcedure(request, { context, prefix }),
@@ -172,10 +172,21 @@ export class StandardHandler<T extends Context> {
172172
{ context, prefix, request, path, procedure, decodeInput },
173173

174174
async ({ context, prefix, request, path, procedure, decodeInput }) => {
175-
step = 'decode_input'
176-
let input = await runWithSpan('decode_input', decodeInput)
177175
step = undefined
178176

177+
let input: unknown
178+
try {
179+
input = await runWithSpan('decode_input', decodeInput)
180+
} catch (e) {
181+
// Convert here so interceptors see the same error the client gets.
182+
throw e instanceof ORPCError
183+
? e
184+
: new ORPCError('BAD_REQUEST', {
185+
message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
186+
cause: e,
187+
})
188+
}
189+
179190
if (getTracer() && isAsyncIteratorObject(input)) {
180191
input = traceAsyncIterator('consume_async_iterator_object_input', input)
181192
} else if (getTracer() && input instanceof ReadableStream) {
@@ -220,13 +231,7 @@ export class StandardHandler<T extends Context> {
220231
recordSpanError(span, e)
221232
}
222233

223-
const error =
224-
step === 'decode_input' && !(e instanceof ORPCError)
225-
? new ORPCError('BAD_REQUEST', {
226-
message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
227-
cause: e,
228-
})
229-
: toORPCError(e)
234+
const error = toORPCError(e)
230235

231236
/**
232237
* The procedure client already reconciles what it rejects with,

‎packages/server/src/plugins/rethrow.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,3 +102,43 @@ describe('rethrowHandlerPlugin', () => {
102102
)
103103
})
104104
})
105+
106+
describe('rethrowHandlerPlugin with malformed requests', () => {
107+
const procedure_handler = vi.fn()
108+
const filter = vi.fn((error: unknown) => !(error instanceof ORPCError))
109+
const handler = new RPCHandler(os.handler(procedure_handler), {
110+
allowMethods: ['GET', 'POST'],
111+
plugins: [new RethrowHandlerPlugin({ filter })],
112+
})
113+
114+
const post = (body: string) =>
115+
new Request('http://localhost', {
116+
method: 'POST',
117+
headers: { 'content-type': 'application/json' },
118+
body,
119+
})
120+
121+
it.each([
122+
['body', post('{bad')],
123+
['query', new Request('http://localhost?data=%7Bbad')],
124+
])(
125+
'passes %s decode failures to the filter as BAD_REQUEST and does not rethrow them',
126+
async (_, request) => {
127+
const { response } = await handler.handle(request)
128+
129+
expect(response?.status).toBe(400)
130+
expect(procedure_handler).not.toHaveBeenCalled()
131+
expect(filter).toHaveBeenCalledOnce()
132+
expect(filter.mock.calls[0]![0]).toSatisfy(
133+
(error) => error instanceof ORPCError && error.code === 'BAD_REQUEST',
134+
)
135+
},
136+
)
137+
138+
it('still rethrows procedure errors', async () => {
139+
const error = new TypeError('__TEST__')
140+
procedure_handler.mockRejectedValueOnce(error)
141+
142+
await expect(handler.handle(post('{}'))).rejects.toBe(error)
143+
})
144+
})

0 commit comments

Comments
 (0)