diff --git a/.talismanrc b/.talismanrc index 68a2edd..c44539a 100644 --- a/.talismanrc +++ b/.talismanrc @@ -239,7 +239,7 @@ fileignoreconfig: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" - filename: AGENTS.md - checksum: 990c5f77386440b38417ad3277d8cf6afdff910a12d21884e8773b449f8f0ab7 + checksum: 5e00b7347fb405145f6b1059ef533ff5b58ef5b4e4f2af5fab3b5dd9424529c4 allowed_patterns: - "Do not add an exemption to a guard to make a new file pass" - "passes its own error wording to `client.request\\(req, MESSAGES\\)`" @@ -286,7 +286,7 @@ fileignoreconfig: - filename: test/integration/projects-list-command.test.ts checksum: 6709766943430b80aad2d7200102d936a92321e86c41f66d6a60a5baf82a81bf - filename: src/functions/cloud-functions.test.ts - checksum: b4ea493e2e58fae9bdd9a7d890eb6bfb0a66eaa20c3afbd2dea989e82cdb56a5 + checksum: ae6261584e816fb4839b8ae52b3d6b80db2ab26b12b6f0c3cc3f9f555a6cc521 - filename: src/functions/function.errors.ts checksum: cad477cf24c97bf3395427235ca1de0f305369d05d61c21a83435654df2269e3 - filename: src/transport/proxy.test.ts diff --git a/AGENTS.md b/AGENTS.md index 11af16a..ed255f9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -534,7 +534,14 @@ The approved differences from V1 are these, and only these: - **Requests match AWS deployed functions** (`lambda-node-bridge/cf-sv-with-helpers.ts` in `contentfly-deployment-agent`), as agreed with CL-8791's reporter. JSON and urlencoded bodies are parsed, `text/plain` arrives as the raw string, `application/octet-stream` as a - Buffer, all up to Lambda's 6mb cap. `request.cookies` is the parsed `Cookie` header, or `{}`. + Buffer, all up to Lambda's 6mb cap; a request with no body, or a body of any other type, leaves + `request.body` undefined (CL-8970). Serve reads the body once before the function runs and puts + it back into the request stream, so a function can still read the raw stream (`for await`, + `'data'`/`'end'`, `pipe`, a webhook signature check) as well as `request.body` (CL-8970). A + body the function leaves unread is drained once its response finishes, as Node does, so the + request still ends and closes; a client that hangs up mid-body is logged as a 400 + `request.aborted`, as body-parser logged it (CL-8970). + `request.cookies` is the parsed `Cookie` header, or `{}`. `request.query` also holds the path parameters, which win over a query value of the same name (`/items/abc?id=zzz` → `{ id: 'abc' }`), as on AWS (CL-8970); Azure and GCP (V1) keep them only in `request.params`. The query string and an urlencoded body are parsed flat with Node's @@ -545,8 +552,8 @@ The approved differences from V1 are these, and only these: instead of Express's HTML page. Deployed, such a request never reaches the function and nginx answers it with its own 404 page. The project `.env` is loaded before the functions are bundled. Azure and GCP still run the - vendored V1 server, which leaves text and octet-stream bodies unparsed; locally a handler - that reads the raw request stream for those two types gets an empty stream. + vendored V1 server, which leaves text and octet-stream bodies unparsed, gives `request.body` as + `{}` when there is none, and leaves an empty request stream for a JSON or urlencoded body. `res.redirect(url)` answers a bare 307 with the location as given (CL-8970). `res.send` takes one argument, as on AWS and Vercel (CL-8970, chosen by the ticket owner): a number is sent as JSON with the current status (`res.send(42)` → `42`, diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 15fd712..91ede49 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -130,6 +130,9 @@ afterEach(async () => { jest.restoreAllMocks(); delete (globalThis as Record).openStream; delete (globalThis as Record).lateDone; + delete (globalThis as Record).bodyRan; + delete (globalThis as Record).requestEnded; + delete (globalThis as Record).requestClosed; delete (globalThis as Record).lateResult; delete (globalThis as Record).piped; delete (globalThis as Record).hub; @@ -435,6 +438,197 @@ describe('CloudFunctions serve routing', () => { expect(JSON.parse(response.body)).toEqual({ length: data.length }); }); + it.each([ + ['a GET', { method: 'GET' }], + ['an empty JSON POST', { method: 'POST', headers: { 'content-type': 'application/json', 'content-length': '0' } }], + ['an empty chunked JSON POST', { method: 'POST', headers: { 'content-type': 'application/json', 'transfer-encoding': 'chunked' } }], + ])('hands the handler an undefined body for %s with no body, as deployed functions do', async (_label, options) => { + writeFunctionFile('body.js', 'export default function body(request, response) { response.json({ type: typeof request.body }); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/body', options); + + expect(response.status).toBe(200); + expect(JSON.parse(response.body)).toEqual({ type: 'undefined' }); + }); + + it('hands the handler an undefined body for a content type deployed functions do not parse', async () => { + writeFunctionFile('body.js', 'export default function body(request, response) { response.json({ type: typeof request.body }); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/body', { method: 'POST', headers: { 'content-type': 'application/xml' }, body: '' }); + + expect(JSON.parse(response.body)).toEqual({ type: 'undefined' }); + }); + + it.each([ + ['application/json', '{"event":"push"}', { event: 'push' }], + ['text/plain', 'hello', 'hello'], + ])('keeps a %s body in the request stream as well as in request.body, as deployed functions do', async (contentType, body, parsed) => { + writeFunctionFile( + 'raw.js', + [ + 'export default async function raw(request, response) {', + ' const chunks = [];', + ' for await (const chunk of request) { chunks.push(chunk); }', + ' response.json({ raw: Buffer.concat(chunks).toString(), body: request.body });', + '}', + ].join('\n'), + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/raw', { method: 'POST', headers: { 'content-type': contentType }, body }); + + expect(JSON.parse(response.body)).toEqual({ raw: body, body: parsed }); + }); + + it('lets a handler that waits for the end event read a text/plain body instead of hanging', async () => { + writeFunctionFile( + 'events.js', + [ + 'export default async function events(request, response) {', + ' let bytes = 0;', + ' await new Promise((resolve, reject) => {', + ' request.on("data", (chunk) => { bytes += chunk.length; });', + ' request.on("end", resolve);', + ' request.on("error", reject);', + ' });', + ' response.json({ bytes });', + '}', + ].join('\n'), + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/events', { method: 'POST', headers: { 'content-type': 'text/plain' }, body: 'hello' }); + + expect(JSON.parse(response.body)).toEqual({ bytes: 5 }); + }, 4000); + + it('hands the handler an undefined body for an empty chunked JSON body whose end arrives after its headers', async () => { + writeFunctionFile('body.js', 'export default function body(request, response) { response.json({ type: typeof request.body }); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const socket = connect(port, '127.0.0.1'); + const answer = new Promise((resolve) => { + let raw = ''; + socket.on('data', (chunk) => { + raw += chunk; + }); + socket.on('end', () => resolve(raw)); + }); + await new Promise((resolve) => socket.once('connect', () => resolve())); + socket.write('POST /body HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n'); + await new Promise((resolve) => setTimeout(resolve, 50)); + socket.write('0\r\n\r\n'); + const raw = await answer; + + expect(raw.split('\r\n')[0]).toBe('HTTP/1.1 200 OK'); + expect(raw.split('\r\n\r\n')[1]).toBe('{"type":"undefined"}'); + }); + + it('lets a handler that waits for the end event answer an empty chunked body of a type serve does not parse', async () => { + writeFunctionFile( + 'events.js', + [ + 'export default async function events(request, response) {', + ' let bytes = 0;', + ' await new Promise((resolve, reject) => {', + ' request.on("data", (chunk) => { bytes += chunk.length; });', + ' request.on("end", resolve);', + ' request.on("error", reject);', + ' });', + ' response.json({ bytes, type: typeof request.body });', + '}', + ].join('\n'), + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/events', { + method: 'POST', + headers: { 'content-type': 'application/xml', 'transfer-encoding': 'chunked' }, + }); + + expect(JSON.parse(response.body)).toEqual({ bytes: 0, type: 'undefined' }); + }, 4000); + + it('ends and closes a request whose large body the handler leaves unread once its response is sent on a keep-alive connection, as Node does', async () => { + writeFunctionFile( + 'unread.js', + [ + 'export default function unread(request, response) {', + ' request.on("end", () => { globalThis.requestEnded = true; });', + ' request.on("close", () => { globalThis.requestClosed = true; });', + ' response.send("ok");', + '}', + ].join('\n'), + ); + const port = await freePort(); + + const agent = new Agent({ keepAlive: true, maxSockets: 1 }); + + try { + await new CloudFunctions(workspace).serve(port); + const body = await new Promise((resolve, reject) => { + httpRequest( + { host: '127.0.0.1', port, path: '/unread', method: 'POST', agent, headers: { 'content-type': 'text/plain', 'content-length': String(1024 * 1024) } }, + (response) => { + let text = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { + text += chunk; + }); + response.on('end', () => resolve(text)); + }, + ) + .on('error', reject) + .end(Buffer.alloc(1024 * 1024, 'a')); + }); + await eventually(() => (globalThis as Record).requestClosed === true); + + expect(body).toBe('ok'); + expect((globalThis as Record).requestEnded).toBe(true); + expect((globalThis as Record).requestClosed).toBe(true); + } finally { + agent.destroy(); + } + }); + + it('answers the next request on a keep-alive connection when the handler leaves the body unread', async () => { + writeFunctionFile('ignore.js', 'export default function ignore(request, response) { response.send("ignored"); }'); + writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); + const port = await freePort(); + const agent = new Agent({ keepAlive: true, maxSockets: 1 }); + const send = (path: string, body?: Buffer): Promise => + new Promise((resolve, reject) => { + const headers = body ? { 'content-type': 'text/plain', 'content-length': String(body.length) } : {}; + httpRequest({ host: '127.0.0.1', port, path, method: body ? 'POST' : 'GET', agent, headers }, (response) => { + let text = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { + text += chunk; + }); + response.on('end', () => resolve(text)); + }) + .on('error', reject) + .end(body); + }); + + try { + await new CloudFunctions(workspace).serve(port); + + expect(await send('/ignore', Buffer.alloc(1024 * 1024, 'a'))).toBe('ignored'); + expect(await Promise.race([send('/next'), new Promise((resolve) => setTimeout(() => resolve('no answer'), 1500))])).toBe('alive'); + } finally { + agent.destroy(); + } + }); + it('hands a text/plain body to the handler as the raw string', async () => { writeFunctionFile('body.js', 'export default function body(request, response) { response.json({ body: request.body }); }'); const port = await freePort(); @@ -1625,6 +1819,54 @@ describe('CloudFunctions serve routing', () => { expect(loggedErrors).toEqual(['Request rejected before the function ran: 413 entity.too.large']); }); + it('keeps serving after a client drops its connection in the middle of sending a body', async () => { + writeFunctionFile('body.js', 'export default function body(request, response) { globalThis.bodyRan = true; response.json({ body: request.body }); }'); + writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const socket = connect(port, '127.0.0.1'); + await new Promise((resolve) => socket.once('connect', () => resolve())); + socket.write('POST /body HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: text/plain\r\nContent-Length: 100\r\n\r\nonly ten b'); + await new Promise((resolve) => setTimeout(resolve, 100)); + socket.destroy(); + await eventually(() => loggedErrors.length > 0); + + expect((await sendRequest(port, '/next')).body).toBe('alive'); + expect((globalThis as Record).bodyRan).toBeUndefined(); + expect(loggedErrors).toEqual(['Request rejected before the function ran: 400 request.aborted']); + }); + + it('answers the next request on a keep-alive connection after refusing a body over the payload limit', async () => { + writeFunctionFile('body.js', 'export default function body(request, response) { response.json({ body: request.body }); }'); + writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); + const port = await freePort(); + const agent = new Agent({ keepAlive: true, maxSockets: 1 }); + const send = (path: string, body?: Buffer): Promise => + new Promise((resolve, reject) => { + const headers = body ? { 'content-type': 'text/plain', 'content-length': String(body.length) } : {}; + httpRequest({ host: '127.0.0.1', port, path, method: body ? 'POST' : 'GET', agent, headers }, (response) => { + let text = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { + text += chunk; + }); + response.on('end', () => resolve(`${response.statusCode} ${text}`)); + }) + .on('error', reject) + .end(body); + }); + + try { + await new CloudFunctions(workspace).serve(port); + + expect(await send('/body', Buffer.alloc(7 * 1024 * 1024, 'x'))).toBe('413 '); + expect(await Promise.race([send('/next'), new Promise((resolve) => setTimeout(() => resolve('no answer'), 2000))])).toBe('200 alive'); + } finally { + agent.destroy(); + } + }); + it('answers a request error that carries no status with a bare 500', () => { const end = jest.fn(); const status = jest.fn(() => ({ end })); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index 54b887e..b566482 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -14,6 +14,7 @@ import { isBuiltin } from 'module'; import type { AddressInfo } from 'net'; import { tmpdir } from 'os'; import path from 'path'; +import { parse as parseQueryString } from 'querystring'; import type { Plugin, RollupLog } from 'rollup'; import { fileURLToPath, pathToFileURL } from 'url'; @@ -37,7 +38,7 @@ import type { CloudFunctionResource } from './types'; type CloudFunctionHandler = CloudFunctionResource['handler']; -const DEPLOYED_PAYLOAD_LIMIT = '6mb'; +const DEPLOYED_PAYLOAD_LIMIT_BYTES = 6 * 1024 * 1024; const DEPLOYED_REDIRECT_STATUS = 307; const INVALID_REDIRECT_MESSAGE = "Invalid redirect arguments. Please use a single argument URL, e.g. res.redirect('/destination') " + @@ -404,10 +405,110 @@ function applyRequestMiddleware(app: Express): void { app.use(attachCookies); app.use(redirectLikeDeployedFunctions); app.use(sendLikeDeployedFunctions); - app.use(express.json({ limit: DEPLOYED_PAYLOAD_LIMIT })); - app.use(express.urlencoded({ extended: false, limit: DEPLOYED_PAYLOAD_LIMIT })); - app.use(express.text({ limit: DEPLOYED_PAYLOAD_LIMIT })); - app.use(express.raw({ limit: DEPLOYED_PAYLOAD_LIMIT })); + app.use(readBodyLikeDeployedFunctions); +} + +function requestError(status: number, type: string, message: string): Error & { status: number; type: string } { + return Object.assign(new Error(message), { status, type }); +} + +function hasBody(request: Request): boolean { + return request.headers['transfer-encoding'] !== undefined || Number(request.headers['content-length']) > 0; +} + +function bufferBody(request: Request): Promise { + return new Promise((resolve, reject) => { + const chunks: Buffer[] = []; + let size = 0; + const settle = (): void => { + request.off('readable', read); + request.off('error', fail); + }; + const fail = (): void => { + settle(); + reject(requestError(400, 'request.aborted', 'request aborted')); + }; + const read = (): void => { + let chunk: Buffer | null; + while ((chunk = request.read() as Buffer | null) !== null) { + size += chunk.length; + if (size > DEPLOYED_PAYLOAD_LIMIT_BYTES) { + settle(); + request.resume(); + reject(requestError(413, 'entity.too.large', 'request entity too large')); + return; + } + chunks.push(chunk); + } + if (request.complete) { + settle(); + const body = Buffer.concat(chunks); + if (body.length > 0) { + request.unshift(body); + } + resolve(body); + } + }; + request.on('readable', read); + request.once('error', fail); + }); +} + +function parseBody(request: Request, body: Buffer): unknown { + if (body.length === 0) { + return undefined; + } + if (request.is('json')) { + try { + return JSON.parse(body.toString()); + } catch { + throw requestError(400, 'entity.parse.failed', 'invalid json'); + } + } + if (request.is('application/octet-stream')) { + return body; + } + if (request.is('urlencoded')) { + return parseQueryString(body.toString()); + } + if (request.is('text/plain')) { + return body.toString(); + } + return undefined; +} + +/** + * Reading the body marks the request as consumed, so Node no longer dumps it when the response finishes. Drain + * what the function left unread, as Node would, so its 'end' and 'close' events still fire. + */ +function drainUnreadBody(request: Request): void { + if (!request.readableEnded && request.listenerCount('data') === 0 && request.listenerCount('readable') === 0) { + request.resume(); + } +} + +function readBodyLikeDeployedFunctions(request: Request, response: Response, next: NextFunction): void { + if (!hasBody(request)) { + request.body = undefined; + next(); + return; + } + setImmediate(() => { + if (request.complete && request.readableLength === 0) { + request.body = undefined; + next(); + return; + } + bufferBody(request) + .then((body) => { + response.once('finish', () => drainUnreadBody(request)); + return parseBody(request, body); + }) + .then((parsed) => { + request.body = parsed; + process.nextTick(next); + }, next); + }); } import { loadDataURL } from './load-data-url';