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
4 changes: 2 additions & 2 deletions .talismanrc
Original file line number Diff line number Diff line change
Expand Up @@ -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\\)`"
Expand Down Expand Up @@ -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
Expand Down
13 changes: 10 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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`,
Expand Down
242 changes: 242 additions & 0 deletions src/functions/cloud-functions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,9 @@ afterEach(async () => {
jest.restoreAllMocks();
delete (globalThis as Record<string, unknown>).openStream;
delete (globalThis as Record<string, unknown>).lateDone;
delete (globalThis as Record<string, unknown>).bodyRan;
delete (globalThis as Record<string, unknown>).requestEnded;
delete (globalThis as Record<string, unknown>).requestClosed;
delete (globalThis as Record<string, unknown>).lateResult;
delete (globalThis as Record<string, unknown>).piped;
delete (globalThis as Record<string, unknown>).hub;
Expand Down Expand Up @@ -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: '<a/>' });

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<string>((resolve) => {
let raw = '';
socket.on('data', (chunk) => {
raw += chunk;
});
socket.on('end', () => resolve(raw));
});
await new Promise<void>((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<string>((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<string, unknown>).requestClosed === true);

expect(body).toBe('ok');
expect((globalThis as Record<string, unknown>).requestEnded).toBe(true);
expect((globalThis as Record<string, unknown>).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<string> =>
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<string>((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();
Expand Down Expand Up @@ -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<void>((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<string, unknown>).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<string> =>
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<string>((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 }));
Expand Down
Loading
Loading