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): serialize and parse nameless cookies per RFC 6265bis (#43168)
Pavel Feldmana1906e2cd4d8
diff --git a/packages/playwright-core/src/server/cookieStore.ts b/packages/playwright-core/src/server/cookieStore.tsindex 1c01445a19..3f0d5273d5 100644--- a/packages/playwright-core/src/server/cookieStore.ts+++ b/packages/playwright-core/src/server/cookieStore.ts@@ -119,8 +119,25 @@ type RawCookie = {sameSite?: 'Strict' | 'Lax' | 'None',};+// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.6+export function parseCookieNameValue(pair: string): { name: string, value: string } {+ const separatorPos = pair.indexOf('=');+ if (separatorPos === -1)+ return { name: '', value: pair.trim() };+ return { name: pair.slice(0, separatorPos).trim(), value: pair.slice(separatorPos + 1).trim() };+}++// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.8.3+export function serializeCookieNameValue(cookie: { name: string, value: string }): string {+ return cookie.name ? `${cookie.name}=${cookie.value}` : cookie.value;+}+export function parseRawCookie(header: string): RawCookie | null {- const pairs = header.split(';').filter(s => s.trim().length > 0).map(p => {+ const [nameValue, ...attributes] = header.split(';');+ const cookie: RawCookie = parseCookieNameValue(nameValue);+ if (!cookie.name && !cookie.value)+ return null;+ const pairs = attributes.filter(s => s.trim().length > 0).map(p => {let key = '';let value = '';const separatorPos = p.indexOf('=');@@ -135,16 +152,8 @@ export function parseRawCookie(header: string): RawCookie | null {}return [key, value];});- if (!pairs.length)- return null;- const [name, value] = pairs[0];- const cookie: RawCookie = {- name,- value,- };let maxAgeExpires: number | undefined;- for (let i = 1; i < pairs.length; i++) {- const [name, value] = pairs[i];+ for (const [name, value] of pairs) {switch (name.toLowerCase()) {case 'expires':const expiresMs = (+new Date(value));diff --git a/packages/playwright-core/src/server/fetch.ts b/packages/playwright-core/src/server/fetch.tsindex 31cc9b94d9..cdd5c504d2 100644--- a/packages/playwright-core/src/server/fetch.ts+++ b/packages/playwright-core/src/server/fetch.ts@@ -28,7 +28,7 @@ import { monotonicTime } from '@isomorphic/time';import { createProxyAgent, flattenAggregateError, happyEyeballsOptions } from '@utils/network';import { getUserAgent } from './userAgent';import { BrowserContext, findMatchingHttpCredentials, verifyClientCertificates } from './browserContext';-import { CookieStore, parseRawCookie } from './cookieStore';+import { CookieStore, parseCookieNameValue, parseRawCookie, serializeCookieNameValue } from './cookieStore';import { MultipartFormData } from './formData';import { cookieMatchesClearFilter, domainMatches, filterCookies, rewriteCookies } from './network';import { TargetClosedError } from './errors';@@ -289,7 +289,7 @@ export abstract class APIRequestContext extends SdkObject {return;const cookies = await this.cookies(progress, [url.toString()]);if (cookies.length) {- const valueArray = cookies.map(c => `${c.name}=${c.value}`);+ const valueArray = cookies.map(serializeCookieNameValue);setHeader(headers, 'cookie', valueArray.join('; '));}}@@ -329,12 +329,7 @@ export abstract class APIRequestContext extends SdkObject {};await this._updateRequestCookieHeader(progress, url, options.headers);- const requestCookies = getHeader(options.headers, 'cookie')?.split(';').map(p => {- const indexOfEquals = p.indexOf('=');- const name = indexOfEquals !== -1 ? p.substring(0, indexOfEquals).trim() : p.trim();- const value = indexOfEquals !== -1 ? p.substring(indexOfEquals + 1).trim() : '';- return { name, value };- }) || [];+ const requestCookies = getHeader(options.headers, 'cookie')?.split(';').map(parseCookieNameValue) || [];const requestEvent: APIRequestEvent = {url,method: options.method!,diff --git a/packages/playwright-core/src/server/har/harTracer.ts b/packages/playwright-core/src/server/har/harTracer.tsindex 2fca562f56..5aa4ff800a 100644--- a/packages/playwright-core/src/server/har/harTracer.ts+++ b/packages/playwright-core/src/server/har/harTracer.ts@@ -25,6 +25,7 @@ import { isTextualMimeType } from '@isomorphic/mimeType';import { urlMatches } from '@isomorphic/urlMatch';import { getPlaywrightVersion } from '../userAgent';import { BrowserContext } from '../browserContext';+import { parseCookieNameValue } from '../cookieStore';import { APIRequestContext } from '../fetch';import { Frame } from '../frames';import { helper } from '../helper';@@ -774,22 +775,12 @@ function createHarEntry(pageRef: string | undefined, method: string, url: URL, f}function parseCookie(c: string): har.Cookie {- const cookie: har.Cookie = {- name: '',- value: ''- };- let first = true;- for (const pair of c.split(/; */)) {+ const [nameValue, ...attributes] = c.split(/; */);+ const cookie: har.Cookie = parseCookieNameValue(nameValue);+ for (const pair of attributes) {const indexOfEquals = pair.indexOf('=');const name = indexOfEquals !== -1 ? pair.substr(0, indexOfEquals).trim() : pair.trim();const value = indexOfEquals !== -1 ? pair.substr(indexOfEquals + 1, pair.length).trim() : '';- if (first) {- first = false;- cookie.name = name;- cookie.value = value;- continue;- }-switch (name.toLowerCase()) {case 'domain':cookie.domain = value;diff --git a/tests/library/global-fetch-cookie.spec.ts b/tests/library/global-fetch-cookie.spec.tsindex d7a5b4e9fd..423e250dd1 100644--- a/tests/library/global-fetch-cookie.spec.ts+++ b/tests/library/global-fetch-cookie.spec.ts@@ -194,6 +194,39 @@ it('clearCookies should remove nameless cookies by empty name', {expect((await request.cookies()).map(c => c.name)).toEqual(['session']);});+it('should send nameless cookies as value only', {+ annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/43155' },+}, async ({ request, server }) => {+ await request.addCookies([+ { name: '', value: 'nameless', url: server.EMPTY_PAGE },+ { name: 'a', value: 'b', url: server.EMPTY_PAGE },+ ]);+ const [serverRequest] = await Promise.all([+ server.waitForRequest('/empty.html'),+ request.get(server.EMPTY_PAGE),+ ]);+ expect(serverRequest.headers.cookie).toBe('nameless; a=b');+});++it('should store Set-Cookie without equals sign as nameless cookie', {+ annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/43155' },+}, async ({ request, server }) => {+ server.setRoute('/setcookie.html', (req, res) => {+ res.setHeader('Set-Cookie', ['token; path=/', 'a=; path=/']);+ res.end();+ });+ await request.get(`${server.PREFIX}/setcookie.html`);+ expect((await request.cookies()).map(c => ({ name: c.name, value: c.value }))).toEqual([+ { name: '', value: 'token' },+ { name: 'a', value: '' },+ ]);+ const [serverRequest] = await Promise.all([+ server.waitForRequest('/empty.html'),+ request.get(server.EMPTY_PAGE),+ ]);+ expect(serverRequest.headers.cookie).toBe('token; a=');+});+it('should filter outgoing cookies by path', async ({ request, server }) => {server.setRoute('/setcookie.html', (req, res) => {res.setHeader('Set-Cookie', ['a=v; path=/input/subfolder', 'b=v; path=/input', 'c=v;']);diff --git a/tests/library/har.spec.ts b/tests/library/har.spec.tsindex 46243c75ef..f9d247316d 100644--- a/tests/library/har.spec.ts+++ b/tests/library/har.spec.ts@@ -248,6 +248,19 @@ it('should include set-cookies', async ({ contextFactory, server }, testInfo) =>expect(new Date(cookies[2].expires!).valueOf()).toBeGreaterThan(Date.now());});+it('should include set-cookies without equals sign as nameless', {+ annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/43155' },+}, async ({ contextFactory, server }, testInfo) => {+ const { page, getLog } = await pageWithHar(contextFactory, testInfo);+ server.setRoute('/empty.html', (req, res) => {+ res.setHeader('Set-Cookie', ['token; HttpOnly']);+ res.end();+ });+ await page.goto(server.EMPTY_PAGE);+ const log = await getLog();+ expect(log.entries[0].response.cookies).toEqual([{ name: '', value: 'token', httpOnly: true }]);+});+it('should include set-cookies with lowercase attributes', async ({ contextFactory, server }, testInfo) => {const { page, getLog } = await pageWithHar(contextFactory, testInfo);server.setRoute('/empty.html', (req, res) => {@@ -842,6 +855,24 @@ it('should correctly record API request cookies with equals sign in value', asyn]);});+it('should record nameless API request cookies', {+ annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/43155' },+}, async ({ contextFactory, server }, testInfo) => {+ const context = await contextFactory();+ const harPath = testInfo.outputPath('request.har');+ await context.request.tracing.startHar(harPath);+ await context.request.get(server.PREFIX + '/simple.json', {+ headers: { cookie: 'nameless; other=val' },+ });+ await context.request.tracing.stopHar();+ await context.close();+ const log = JSON.parse(fs.readFileSync(harPath).toString()).log as Log;+ expect(log.entries[0].request.cookies).toEqual([+ { name: '', value: 'nameless' },+ { name: 'other', value: 'val' },+ ]);+});+it('should respect minimal mode for API Requests', async ({ contextFactory, server }, testInfo) => {const context = await contextFactory();const harPath = testInfo.outputPath('request.har');