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
18 changes: 17 additions & 1 deletion playwright/src/settle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,22 @@
import type { BrowserContext, Frame, Page, Request, Route } from '@playwright/test';
import { workerMark } from './random';

// RFC 7230 OWS + token characters (tchar) for Content-Disposition's disposition-type.
const DISPOSITION_TYPE = /^[ \t]*([!#$%&'*+.^_`|~0-9A-Za-z-]+)[ \t]*$/;

/**
* Reports whether a Content-Disposition header triggers a browser download
* (RFC 6266 §4.2): any valid disposition-type token other than "inline"
* (case-insensitive) is handled as an attachment. Missing, empty, or malformed
* disposition types render inline, regardless of parameters such as filename.
*/
export function isDownloadDisposition(header: string | undefined): boolean {
if (!header) return false;
const semi = header.indexOf(';');
const match = DISPOSITION_TYPE.exec(semi === -1 ? header : header.slice(0, semi));
return match !== null && match[1].toLowerCase() !== 'inline';
}

export class Inflight {
// Each call's number, in the order the browser reported it.
private readonly open = new Map<Request, { frame: Frame | null; nav: boolean; n: number }>();
Expand Down Expand Up @@ -64,7 +80,7 @@ export class Inflight {
let f: Frame | null = null;
try { f = r.frame(); } catch { f = null; }
// A 204 or 205 answer, or a download, leaves the document in place.
const keeps = res.status() === 204 || res.status() === 205 || /attachment/i.test(res.headers()['content-disposition'] ?? '');
const keeps = res.status() === 204 || res.status() === 205 || isDownloadDisposition(res.headers()['content-disposition']);
if (f && !keeps) loading.set(f, this.reported);
});
const watch = (p: Page): void => {
Expand Down
23 changes: 23 additions & 0 deletions playwright/test/fixtures/settle.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ test('a call its page cancelled by loading another document', async ({ page }) =
await reached();
await page.goto(`${base}/page?next`);
});
test('a call its page cancelled by loading an inline document with attachment in its filename', async ({ page }) => {
await page.goto(`${base}/page`);
const sent = page.waitForRequest(/\/slow$/);
await page.evaluate(() => { void fetch('/slow'); });
await sent;
await reached();
await page.goto(`${base}/inline-attachment-name`);
});
test('a call its new document makes as it loads', async ({ page }) => {
// The document's image, which its parser asks for as it loads, is still
// in flight when the body ends. The body ends once the test has seen the
Expand Down Expand Up @@ -252,6 +260,21 @@ test('a call in flight across a lowercase attachment download', async ({ page })
await page.evaluate(() => { history.pushState({}, '', '/page?route'); });
await routed;
});
test('a call in flight across an unknown disposition type download', async ({ page }) => {
await page.goto(`${base}/page`);
const sent = page.waitForRequest(/\/slow$/);
const answered = page.waitForResponse(/\/download-x$/);
const downloaded = page.waitForEvent('download');
await page.evaluate(() => { void fetch('/slow'); });
await sent;
// Browsers treat an unknown disposition type as attachment (RFC 6266 §4.2): still a download.
await page.evaluate(() => { location.href = '/download-x'; });
await answered;
await downloaded;
const routed = page.waitForEvent('framenavigated');
await page.evaluate(() => { history.pushState({}, '', '/page?route'); });
await routed;
});
test('a page that starts a Shared Worker', async ({ page }) => {
await page.goto(`${base}/page`);
// The worker answers once its script has run; its URL's fragment is no
Expand Down
21 changes: 21 additions & 0 deletions playwright/test/rows.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,15 @@ async function pageServer(j) {
return;
}
if (req.url === '/resetcontent') { res.writeHead(205); res.end(); return; }
if (req.url === '/inline-attachment-name') {
res.writeHead(200, { 'content-type': 'text/html', 'content-disposition': 'inline; filename="attachment-page.html"' });
res.end('<html><body>inline page</body></html>');
return;
}
// A disposition's type is case-insensitive (RFC 6266): the browser downloads "Attachment" too.
if (req.url === '/download') { res.writeHead(200, { 'content-type': 'application/octet-stream', 'content-disposition': 'Attachment; filename="d.bin"' }); res.end('bytes'); return; }
// An unknown disposition type is handled as attachment (RFC 6266 §4.2), even for HTML.
if (req.url === '/download-x') { res.writeHead(200, { 'content-type': 'text/html', 'content-disposition': 'x-download; filename="a.html"' }); res.end('<html></html>'); return; }
if (req.url === '/download-lower') { res.writeHead(200, { 'content-type': 'application/octet-stream', 'content-disposition': 'attachment; filename="e.bin"' }); res.end('bytes'); return; }
if (req.url === '/slowdoc') {
// A document whose last byte comes only once /release is called.
Expand Down Expand Up @@ -414,6 +421,19 @@ test('settle: a call cancelled by its page loading another document is not waite
} finally { await p.close(); await a.close(); }
});

test('settle: an inline document with attachment in its filename still replaces the page', async () => {
const j = journal();
const a = await fakeAgent(j);
const p = await pageServer(j);
try {
const title = 'a call its page cancelled by loading an inline document with attachment in its filename';
const { tests, out } = await playwright(['settle.spec.ts', '-g', 'inline document with attachment in its filename'], { ...keployEnv(a.url), SLOW_BASE: p.url, NO_RELEASE: '1', PW_TIMEOUT: '20000' });
assert.equal(tests[title]?.status, 'passed', out);
const order = j.events.map((e) => (e.page ? e.page : e.agent.path));
assert.deepEqual(order.filter((e) => e.startsWith('slow') || e === '/agent/scope/end'), ['slow sent', 'slow cut', '/agent/scope/end']);
} finally { await p.close(); await a.close(); }
});

// Firefox can report the new document's first call before the frame's
// commit; the commit cancels only the old document's calls, so this one is
// still waited for, in every engine. The call is answered only once settle's
Expand Down Expand Up @@ -782,6 +802,7 @@ for (const [title, why, call] of [
['a call in flight across a navigation answered 205', 'a navigation answered 205 replaces no document', '/slow'],
['a call in flight across a download', 'a navigation answered with an attachment (a download, "Attachment") replaces no document', '/slow'],
['a call in flight across a lowercase attachment download', 'a navigation answered with an attachment (a download, "attachment") replaces no document', '/slow'],
['a call in flight across an unknown disposition type download', 'a navigation answered with an unknown disposition type (a download, "x-download") replaces no document', '/slow'],
['a document still loading after its frame commits', 'a navigation\'s own request stays in flight after its document commits', '/slowdoc'],
['a call in flight while another page of the test closes', 'another page closing cancels nothing of this page', '/slow'],
['a call in flight across a route change after an answered call', 'a route change after an answered call cancels nothing', '/slow'],
Expand Down
53 changes: 52 additions & 1 deletion playwright/test/unit.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import os from 'node:os';
import path from 'node:path';
import { AgentClient, KeployError } from '../dist/agent.js';
import { decide } from '../dist/join.js';
import { Inflight, workersScript } from '../dist/settle.js';
import { Inflight, isDownloadDisposition, workersScript } from '../dist/settle.js';
import { markWorker } from '../dist/random.js';
import { EventEmitter } from 'node:events';
import vm from 'node:vm';
Expand Down Expand Up @@ -947,6 +947,57 @@ test('settle: a frame\'s commit drops only the calls reported before its new doc
}
});

test('isDownloadDisposition: classifies by disposition type, not parameter values', () => {
assert.equal(isDownloadDisposition(undefined), false);
assert.equal(isDownloadDisposition(''), false);
assert.equal(isDownloadDisposition(' '), false);
assert.equal(isDownloadDisposition('inline'), false);
assert.equal(isDownloadDisposition('INLINE; filename="attachment-page.html"'), false);
assert.equal(isDownloadDisposition(' inline ; filename="attachment.bin"'), false);
assert.equal(isDownloadDisposition('; filename="attachment.bin"'), false);
assert.equal(isDownloadDisposition('filename="attachment.bin"'), false);
assert.equal(isDownloadDisposition('attachment, attachment'), false);
assert.equal(isDownloadDisposition('bad value; filename="a.bin"'), false);
assert.equal(isDownloadDisposition('att/ach; filename="a.bin"'), false);
assert.equal(isDownloadDisposition('attachment'), true);
assert.equal(isDownloadDisposition('Attachment; filename="d.bin"'), true);
assert.equal(isDownloadDisposition('attachment; filename="e.bin"'), true);
assert.equal(isDownloadDisposition('attachment\t; filename=a.bin'), true);
assert.equal(isDownloadDisposition('x-download; filename="a.html"'), true);
assert.equal(isDownloadDisposition('form-data; name="field"'), true);
});

test('settle: Inflight classifies navigation downloads by disposition type', async () => {
for (const [header, keeps] of [
['inline; filename="attachment-page.html"', false],
['attachment; filename="d.bin"', true],
['x-download; filename="a.html"', true],
]) {
const ctx = fakeContext();
const inflight = new Inflight(ctx);
const page = new EventEmitter();
const frame = { page: () => page };
ctx.emit('page', page);
const slow = frameRequest(frame, '/slow');
ctx.emit('request', slow);
const nav = frameRequest(frame, '/doc', true);
ctx.emit('request', nav);
ctx.emit('response', answer(nav, 200, { 'content-disposition': header }));
ctx.emit('requestfinished', nav);
page.emit('framenavigated', frame);
assert.deepEqual(inflight.describe(), keeps ? ['GET http://localhost/slow'] : [], `${header}: keeps=${keeps}`);
let settled = false;
inflight.settled().then(() => { settled = true; });
await ticks();
assert.equal(settled, !keeps, `${header}: settled=${!keeps}`);
if (keeps) {
ctx.emit('requestfinished', slow);
await ticks();
assert.equal(settled, true, `${header}: wakes once slow ends`);
}
}
});

test('decide: inert, refused, active', () => {
const never = () => { throw new Error('runsInside called'); };
assert.deepEqual(decide({}, 10, never), { mode: 'inert' });
Expand Down
Loading