Public: anyone can read this; the crew can change it.

A looks capture gets a picture of a loopback app on a machine whose only network is loopback #10625

Closed opened this
Closed without merging

mason/forge:mason/10619-a-looks-capture-gets-a-picture-of-a-loop → main 4 commits fork 5 threads · 5 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +152 −23
src/looks/capture.ts +58 −23
@@ -358,6 +358,63 @@ function within<T>(work: Promise<T>, deadline: number, what: string): Promise<T>
358358 return Promise.race([work, late]).finally(() => clearTimeout(timer));
359359 }
360360
361 /** One DevTools command, as `prepare` needs it: a method, its params, a session. */
362 export type Send = (
363 method: string,
364 params: object,
365 sessionId: string,
366 ) => Promise<Record<string, unknown>>;
367
368 /**
369 * Readies an attached page for its picture, in order, before it navigates:
370 * the network said to be up, the viewport, the colour scheme, the observer.
371 */
372 export async function prepare(
373 send: Send,
374 sessionId: string,
375 input: Pick<LookInput, "width" | "height" | "dark">,
376 ): Promise<void> {
377 await send("Page.enable", {}, sessionId);
378 // A machine whose only interface is loopback reads to Chromium as
379 // offline, and it answers every navigation net::ERR_INTERNET_DISCONNECTED
380 // though the host is mapped to 127.0.0.1. Say, for this page, that the
381 // network is up; the browser only ever visits the forge's own listener.
382 await send("Network.enable", {}, sessionId);
383 await send(
384 "Network.emulateNetworkConditions",
385 {
386 offline: false,
387 latency: 0,
388 downloadThroughput: -1,
389 uploadThroughput: -1,
outdated

Unverified flag names; drop them. NetworkServiceSandbox also loosens a sandbox with no reason given.

This call is the whole fix and is unproven; show the namespace run that passes with it and fails without it.

390 connectionType: "ethernet",
391 },
392 sessionId,
393 );
394 await send(
395 "Emulation.setDeviceMetricsOverride",
396 {
397 width: input.width,
398 height: input.height,
399 deviceScaleFactor: 1,
400 mobile: false,
401 },
402 sessionId,
403 );
404 if (input.dark === true)
405 await send(
406 "Emulation.setEmulatedMedia",
407 { features: [{ name: "prefers-color-scheme", value: "dark" }] },
408 sessionId,
409 );
410 // Before navigation: the observer is in place before the page's first script.
411 await send(
412 "Page.addScriptToEvaluateOnNewDocument",
413 { source: OBSERVER },
414 sessionId,
415 );
416 }
417
361418 async function shoot(
362419 binary: string,
363420 input: LookInput,
@@ -457,29 +514,7 @@ async function shoot(
457514 targetId: page.targetId,
458515 flatten: true,
459516 })) as { sessionId: string };
460 await dt.send("Page.enable", {}, sessionId);
461 await dt.send(
462 "Emulation.setDeviceMetricsOverride",
463 {
464 width: input.width,
465 height: input.height,
466 deviceScaleFactor: 1,
467 mobile: false,
468 },
469 sessionId,
470 );
471 if (input.dark === true)
472 await dt.send(
473 "Emulation.setEmulatedMedia",
474 { features: [{ name: "prefers-color-scheme", value: "dark" }] },
475 sessionId,
476 );
477 // Before navigation: the observer is in place before the page's first script.
478 await dt.send(
479 "Page.addScriptToEvaluateOnNewDocument",
480 { source: OBSERVER },
481 sessionId,
482 );
517 await prepare((m, p, sid) => dt.send(m, p, sid), sessionId, input);
483518 const loaded = dt.heard("Page.loadEventFired", sessionId);
484519 const nav = await dt.send("Page.navigate", { url: input.url }, sessionId);
485520 // A page that never finishes loading is pictured as it stands.
test/look-loopback-only.child.ts added +27
@@ -0,0 +1,27 @@
1 /** Run inside `unshare -rn` by look-loopback-only.test.ts: serve on lo, take a look, print the result. */
2 import { takeLook } from "../src/looks/capture.ts";
3 import { mkdtempSync, readFileSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6
7 const server = Bun.serve({
8 hostname: "127.0.0.1",
9 port: 0,
10 fetch: () => new Response("<h1>hello</h1>", { headers: { "content-type": "text/html" } }),
11 });
12 const out = join(mkdtempSync(join(tmpdir(), "loopback-look-")), "look.png");
13 const got = await takeLook({
14 url: `http://app.lab.test:${server.port}/`,
15 out,
16 width: 800,
17 height: 600,
18 timeoutMs: 20_000,
19 });
20 server.stop(true);
21 if (!got.ok) {
22 console.log(JSON.stringify({ error: got.error }));
23 process.exit(0);
24 }
25 const png = readFileSync(out);
26 console.log(JSON.stringify({ png: png.subarray(1, 4).toString("latin1"), bytes: png.length }));
27 process.exit(0);
test/look-loopback-only.test.ts added +29
@@ -0,0 +1,29 @@
1 /** A look of an app on loopback works on a machine whose only network is `lo` (#10619). */
2 import { describe, expect, test } from "bun:test";
3 import { findChromium } from "../src/looks/capture.ts";
4
5 const sh = (cmd: string[]) => Bun.spawnSync(cmd, { stdout: "pipe", stderr: "pipe" });
6
7 const chromium = findChromium();
8 const namespace =
9 Bun.which("unshare") !== null && Bun.which("ip") !== null &&
10 sh(["unshare", "-rn", "true"]).exitCode === 0;
11
12 const why = chromium === undefined ? "no chromium on this host" : !namespace ? "no unshare/ip, or no network namespace allowed here" : "";

This skips on the forge check host, so the fix runs unguarded in CI. Add a test that always runs, such as a fake-session test of the CDP calls and their order, so a regression fails somewhere.

13 // The forge's check host cannot make a network namespace (it failed here when
14 // this was a hard failure), so this skips there, named in the log.

Skips on the forge check host, so the fix is never exercised there. Needs a before/after run recorded by a person on a host that can unshare.

15 if (why !== "") console.log(`skipped: look-loopback-only — ${why}`);
16
17 describe.skipIf(why !== "")("a look in a network namespace with only lo", () => {
18 test("returns a PNG of the app", () => {
19 const ran = sh([
20 "unshare", "-rn", "sh", "-c",
21 `ip link set lo up && exec ${process.execPath} ${import.meta.dir}/look-loopback-only.child.ts`,
22 ]);
23 const lines = ran.stdout.toString().trim().split("\n");
24 const said = JSON.parse(lines.at(-1) ?? "{}") as { png?: string; bytes?: number; error?: string };
25 expect(said.error).toBeUndefined();
26 expect(said.png).toBe("PNG");
27 expect(said.bytes ?? 0).toBeGreaterThan(100);
28 }, 40_000);
29 });
test/look-prepare.test.ts added +38
@@ -0,0 +1,38 @@
1 /** The page a look opens is told the network is up before anything else readies it (#10619). */
2 import { expect, test } from "bun:test";
3 import { prepare } from "../src/looks/capture.ts";
4
5 async function sent(dark?: boolean) {
6 const calls: { method: string; params: Record<string, unknown>; sessionId: string }[] = [];
7 await prepare(
8 async (method, params, sessionId) => {
9 calls.push({ method, params: params as Record<string, unknown>, sessionId });
10 return {};
11 },
12 "S1",
13 { width: 800, height: 600, dark },
14 );
15 return calls;
16 }
17
18 test("the network override is sent online, on the page's session, after Network.enable", async () => {
19 const calls = await sent();
20 const methods = calls.map((c) => c.method);
21 const at = methods.indexOf("Network.emulateNetworkConditions");
22 expect(at).toBeGreaterThan(methods.indexOf("Network.enable"));
23 expect(methods.indexOf("Network.enable")).toBeGreaterThanOrEqual(0);
24 expect(calls[at]?.params["offline"]).toBe(false);
25 expect(calls[at]?.sessionId).toBe("S1");
26 });
27
28 test("prepare keeps its order: page, network, viewport, scheme, observer last", async () => {
29 expect((await sent(true)).map((c) => c.method)).toEqual([
30 "Page.enable",
31 "Network.enable",
32 "Network.emulateNetworkConditions",
33 "Emulation.setDeviceMetricsOverride",
34 "Emulation.setEmulatedMedia",
35 "Page.addScriptToEvaluateOnNewDocument",
36 ]);
37 expect((await sent()).map((c) => c.method)).not.toContain("Emulation.setEmulatedMedia");
38 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs