Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
fix(fetch): escape quotes and newlines in multipart field and file names (#43430)
Yury Semikhatsky0d7c1411b0af
diff --git a/packages/playwright-core/src/server/formData.ts b/packages/playwright-core/src/server/formData.tsindex b0ef5097aa..00ce2af86f 100644--- a/packages/playwright-core/src/server/formData.ts+++ b/packages/playwright-core/src/server/formData.ts@@ -38,7 +38,7 @@ export class MultipartFormData {addFileField(name: string, value: NonNullable<channels.FormField['file']>) {this._beginMultiPartHeader(name);- this._chunks.push(Buffer.from(`; filename="${value.name}"`));+ this._chunks.push(Buffer.from(`; filename="${escapeName(value.name)}"`));this._chunks.push(Buffer.from(`\r\ncontent-type: ${value.mimeType || mime.getType(value.name) || 'application/octet-stream'}`));this._finishMultiPartHeader();this._chunks.push(value.buffer);@@ -52,7 +52,7 @@ export class MultipartFormData {private _beginMultiPartHeader(name: string) {this._addBoundary();- this._chunks.push(Buffer.from(`content-disposition: form-data; name="${name}"`));+ this._chunks.push(Buffer.from(`content-disposition: form-data; name="${escapeName(normalizeLineEndings(name))}"`));}private _finishMultiPartHeader() {@@ -71,6 +71,17 @@ export class MultipartFormData {}}+// Escaping from the multipart/form-data encoding algorithm, see+// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#multipart-form-data.+// Field names get their line endings normalized to CRLF first, file names do not.+function escapeName(name: string): string {+ return name.replace(/\r/g, '%0D').replace(/\n/g, '%0A').replace(/"/g, '%22');+}++function normalizeLineEndings(name: string): string {+ return name.replace(/\r\n|\r|\n/g, '\r\n');+}+const alphaNumericEncodingMap = [0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50,diff --git a/tests/library/browsercontext-fetch.spec.ts b/tests/library/browsercontext-fetch.spec.tsindex 4b1ef5d3e2..fd80723c73 100644--- a/tests/library/browsercontext-fetch.spec.ts+++ b/tests/library/browsercontext-fetch.spec.ts@@ -1206,6 +1206,36 @@ it('should support multipart/form-data', async function({ context, server }) {expect(response.status()).toBe(200);});+it('should escape quotes and newlines in multipart field and file names', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/43422' } }, async function({ context, server }) {+ const bodyReceived = new Promise<{ contentType: string, body: Buffer }>(resolve => {+ server.setRoute('/empty.html', async (serverRequest, res) => {+ const chunks: Buffer[] = [];+ for await (const chunk of serverRequest)+ chunks.push(chunk);+ server.serveFile(serverRequest, res);+ resolve({ contentType: serverRequest.headers['content-type'], body: Buffer.concat(chunks) });+ });+ });+ const [{ contentType, body }] = await Promise.all([+ bodyReceived,+ context.request.post(server.EMPTY_PAGE, {+ multipart: {+ 'say"hi\nthere': 'v1',+ 'file': { name: 'report "final"\r\n.txt', mimeType: 'text/plain', buffer: Buffer.from('hello') },+ },+ }),+ ]);+ const headers = body.toString().split('\r\n').filter(line => line.startsWith('content-disposition'));+ expect(headers).toEqual([+ 'content-disposition: form-data; name="say%22hi%0D%0Athere"',+ 'content-disposition: form-data; name="file"; filename="report %22final%22%0D%0A.txt"',+ ]);+ // Node's standard multipart parser expects that escaping.+ const form = await new Request('http://localhost/', { method: 'POST', headers: { 'content-type': contentType }, body: new Uint8Array(body) }).formData();+ expect(form.get('say"hi\r\nthere')).toBe('v1');+ expect(await (form.get('file') as File).text()).toBe('hello');+});+it('should support multipart/form-data with ReadStream values', async function({ context, page, asset, server }) {const formReceived = new Promise<{error: any, fields: formidable.Fields, files: Record<string, formidable.File>, serverRequest: IncomingMessage}>(resolve => {server.setRoute('/empty.html', async (serverRequest, res) => {