Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/content/blog/uploads-bigger-than-your-ram.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ Most body-limit middleware takes a single number. Once uploads spool to disk, a
- A byte of **upload** touches memory only as a passing chunk on its way to disk. You can afford about a thousand times more of these.
- A byte of an **event stream** is consumed on the fly and costs almost nothing to relay.

One limit prices all three at the highest rate, so the plugin takes three: `memory`, `file`, and `stream`. It even [subsumes a generic request-limit plugin](/docs/plugins/request-limit), sizing each kind of body to what it actually costs. Configuring one limit requires configuring all three, so nothing is left unbounded by accident; unlimited must be spelled `Number.POSITIVE_INFINITY`, on purpose.
One limit prices all three at the highest rate, so the plugin takes three: `memory`, `file`, and `stream`. It even [subsumes a generic request-limit plugin](/docs/plugins/request-limit), sizing each kind of body to what it actually costs. All three are required, so nothing is left unbounded by accident; unlimited must be spelled `Number.POSITIVE_INFINITY`, on purpose.

Enforcement has its own subtlety: `Content-Length` is a hint, not a fact. [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110#name-content-length) allows it to be absent, and a hostile client can lie. The plugin uses the declared length only to reject oversized requests early, then counts bytes as they arrive and cuts the request off mid-stream with `413 Payload Too Large` the moment it crosses the line. A multipart body is bounded by `memory + file` in total, framing included, so bulk hidden in part headers is caught too.

Expand Down
13 changes: 11 additions & 2 deletions apps/content/docs/plugins/tmp-file-upload.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ const handler = new RPCHandler(router, {
* @default os.tmpdir()
*/
tmpDir: './uploads',

// Required, see "Limiting Body Sizes" below
maxBodySize: {
memory: 1024 * 1024, // 1MB
file: 500 * 1024 * 1024, // 500MB
stream: 500 * 1024 * 1024, // 500MB
},
}),
],
})
Expand Down Expand Up @@ -68,7 +75,7 @@ Node's [`fs.openAsBlob`](https://nodejs.org/api/fs.html#fsopenasblobpath-options

## Limiting Body Sizes

Use `maxBodySize` to limit each kind of request body by what it actually costs. All three kinds are required together, so none is left unbounded by accident; set a kind to `Number.POSITIVE_INFINITY` to deliberately leave it unlimited. A body over its limit rejects with `PAYLOAD_TOO_LARGE`.
`maxBodySize` is required and limits each kind of request body by what it actually costs. All three kinds are required, so none is left unbounded by accident; set a kind to `Number.POSITIVE_INFINITY` to deliberately leave it unlimited. A body over its limit rejects with `PAYLOAD_TOO_LARGE`.

```ts
const handler = new RPCHandler(router, {
Expand Down Expand Up @@ -103,7 +110,7 @@ const handler = new RPCHandler(router, {

A multipart body splits across the first two limits, fields and part headers against `memory` and file parts against `file`, those held in memory against `memory` as well, and as a whole, framing included, it is bounded by the sum of both. An event stream counts against `stream` in total and each of its events against `memory`, since the decoder buffers an event until its blank line arrives. A raw binary stream reaches the procedure chunk by chunk, so only `stream` applies. A declared [Content-Length](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Length) over the applicable limit rejects immediately, and enforcement continues while the body streams in, so a lying length cannot bypass it.

With all three limits configured, the plugin subsumes the [Request Limit Plugin](/docs/plugins/request-limit). When the [Request Compression Plugin](/docs/plugins/request-compression) is present, limits apply to the decompressed payload rather than the compressed wire size.
The plugin subsumes the [Request Limit Plugin](/docs/plugins/request-limit). When the [Request Compression Plugin](/docs/plugins/request-compression) is present, limits apply to the decompressed payload rather than the compressed wire size.

To reject with your own error instead, use `error`. It is [defined](/docs/error-handling#orpcerror-compatibility) when its `code` and `data` match an error the matched procedure declares. A custom code responds with `400` unless you map it in [`errorStatusMap`](/docs/rpc/handler#custom-error-response).

Expand All @@ -122,6 +129,8 @@ Uploads up to `spoolThreshold` stay in memory as plain `File`s, so small and emp
const handler = new RPCHandler(router, {
plugins: [
new TmpFileUploadHandlerPlugin({
maxBodySize: { memory: 1024 * 1024, file: 500 * 1024 * 1024, stream: 500 * 1024 * 1024 },

/**
* The size in bytes an uploaded file must exceed before it is
* spooled to a temporary file. Set to `0` to spool every
Expand Down
17 changes: 17 additions & 0 deletions packages/node/src/tmp-file-upload-handler-plugin.test-d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { TmpFileUploadHandlerPlugin } from './tmp-file-upload-handler-plugin'

describe('TmpFileUploadHandlerPlugin', () => {
it('requires maxBodySize with every kind', () => {
void new TmpFileUploadHandlerPlugin({ maxBodySize: { memory: 1, file: 1, stream: 1 } })
void new TmpFileUploadHandlerPlugin({
maxBodySize: async () => ({ memory: 1, file: 1, stream: 1 }),
})

// @ts-expect-error - options are required
void new TmpFileUploadHandlerPlugin()
// @ts-expect-error - maxBodySize is required
void new TmpFileUploadHandlerPlugin({})
// @ts-expect-error - every kind is required
void new TmpFileUploadHandlerPlugin({ maxBodySize: { memory: 1, file: 1 } })
})
})
12 changes: 9 additions & 3 deletions packages/node/src/tmp-file-upload-handler-plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ import request from 'supertest'
import { TmpFile, TmpFileUploadHandlerPlugin } from './tmp-file-upload-handler-plugin'

describe('tmpFileUploadHandlerPlugin', () => {
const UNLIMITED = {
memory: Number.POSITIVE_INFINITY,
file: Number.POSITIVE_INFINITY,
stream: Number.POSITIVE_INFINITY,
}

let tmpDir: string

beforeEach(() => {
Expand Down Expand Up @@ -581,8 +587,8 @@ describe('tmpFileUploadHandlerPlugin', () => {
expect(readdirSync(tmpDir)).toHaveLength(0)
})

it('constructs without options and delegates bodiless requests untouched', async () => {
const plugin = new TmpFileUploadHandlerPlugin()
it('delegates bodiless requests untouched', async () => {
const plugin = new TmpFileUploadHandlerPlugin({ maxBodySize: UNLIMITED })
const interceptor = plugin.init({}).routingInterceptors![0]!
const resolved = Symbol('resolved')

Expand Down Expand Up @@ -1766,7 +1772,7 @@ describe('tmpFileUploadHandlerPlugin', () => {
})

it('defaults the threshold to 64 KiB', async () => {
const plugin = new TmpFileUploadHandlerPlugin({ tmpDir })
const plugin = new TmpFileUploadHandlerPlugin({ tmpDir, maxBodySize: UNLIMITED })

await expectFileBody(Buffer.alloc(64 * 1024, 7), false, { plugin, chunkSize: 16 * 1024 })
await expectFileBody(Buffer.alloc(64 * 1024 + 1, 7), true, { plugin, chunkSize: 16 * 1024 })
Expand Down
30 changes: 9 additions & 21 deletions packages/node/src/tmp-file-upload-handler-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,22 +79,17 @@ export interface TmpFileUploadHandlerPluginOptions<T extends Context> {
* The size limit for each kind of request body, either fixed or resolved
* per request, so limits can follow the request itself, such as a larger
* allowance for an authenticated user than for a guest. Every kind is
* required when the option is given, so none is left unbounded by accident;
* set a kind to `Number.POSITIVE_INFINITY` to deliberately leave it
* unlimited.
* required, so none is left unbounded by accident; set a kind to
* `Number.POSITIVE_INFINITY` to deliberately leave it unlimited.
*
* A resolver runs only when a body is parsed, so a request without one never
* pays for it, and it receives the request as it arrived, before this plugin
* wraps its body resolution.
*
* @default unlimited for every kind
*/
maxBodySize?:
| Value<
Promisable<TmpFileUploadHandlerPluginMaxBodySize>,
[options: StandardHandlerRoutingInterceptorOptions<T>]
>
| undefined
maxBodySize: Value<
Promisable<TmpFileUploadHandlerPluginMaxBodySize>,
[options: StandardHandlerRoutingInterceptorOptions<T>]
>

/**
* The size in bytes an uploaded file must exceed before it is spooled to a
Expand Down Expand Up @@ -178,20 +173,13 @@ export class TmpFileUploadHandlerPlugin<T extends Context> implements StandardHa
readonly before: readonly string[] = ['~request-limit', '~request-compression']

private readonly tmpDir: string
private readonly maxBodySize: Exclude<
TmpFileUploadHandlerPluginOptions<T>['maxBodySize'],
undefined
>
private readonly maxBodySize: TmpFileUploadHandlerPluginOptions<T>['maxBodySize']
private readonly spoolThreshold: number
private readonly error: Exclude<TmpFileUploadHandlerPluginOptions<T>['error'], undefined>

constructor(options: TmpFileUploadHandlerPluginOptions<T> = {}) {
constructor(options: TmpFileUploadHandlerPluginOptions<T>) {
this.tmpDir = options.tmpDir ?? tmpdir()
this.maxBodySize = options.maxBodySize ?? {
memory: Number.POSITIVE_INFINITY,
file: Number.POSITIVE_INFINITY,
stream: Number.POSITIVE_INFINITY,
}
this.maxBodySize = options.maxBodySize
this.spoolThreshold = options.spoolThreshold ?? 64 * 1024
this.error = options.error ?? (() => new ORPCError('PAYLOAD_TOO_LARGE'))
}
Expand Down
6 changes: 3 additions & 3 deletions packages/node/tests/uploads-large-files.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ describe('uploads large files through tmp files', () => {

const handler = new RPCHandler(router, {
plugins: [
new TmpFileUploadHandlerPlugin({ tmpDir }),
new TmpFileUploadHandlerPlugin({ tmpDir, maxBodySize: UNLIMITED }),
new RequestCompressionHandlerPlugin(),
new RequestLimitHandlerPlugin({ maxBodySize: 256 * 1024 * 1024 }),
],
Expand Down Expand Up @@ -180,7 +180,7 @@ describe('uploads large files through tmp files', () => {
const limitedTmpDir = mkdtempSync(path.join(tmpdir(), 'orpc-upload-e2e-limited-'))
const limitedHandler = new RPCHandler(router, {
plugins: [
new TmpFileUploadHandlerPlugin({ tmpDir: limitedTmpDir }),
new TmpFileUploadHandlerPlugin({ tmpDir: limitedTmpDir, maxBodySize: UNLIMITED }),
new RequestCompressionHandlerPlugin(),
// The compressed request carries no content-length, so the limit only trips while spooling
new RequestLimitHandlerPlugin({ maxBodySize: 64 * 1024 }),
Expand Down Expand Up @@ -271,7 +271,7 @@ describe('uploads large files through tmp files', () => {
}),
},
{
plugins: [new TmpFileUploadHandlerPlugin({ tmpDir: streamTmpDir })],
plugins: [new TmpFileUploadHandlerPlugin({ tmpDir: streamTmpDir, maxBodySize: UNLIMITED })],
},
)

Expand Down
Loading