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

The forge pill links to the same path on the app's other side, and a `//` path cannot leave the forge's addresses #6261

Parked opened this
Closed without merging

scout/forge:scout/6076-the-forge-pill-links-to-the-same-path-on → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
3 files changed +180 −3
src/apps/proxy.ts +41 −1
@@ -37,6 +37,7 @@ import { loadKey } from "../kernel/secret.ts";
3737 import { previewEnv, type EnvName } from "./data.ts";
3838 import type { AppsRuntime, EnvStatus } from "./runtime.ts";
3939 import { crewNow, tellLink } from "./crew.ts";
40 import { sideOf, type SidePreview } from "./side.ts";
4041 import { feedback, mintProof } from "./feedback.ts";
4142 import { clientBucket } from "../http/peer.ts";
4243 import { DOOR_PULL_LIMIT, doorPage, type DoorPullLine } from "./door.ts";
@@ -50,6 +51,38 @@ import { holdPortRequest, holdPortSocket } from "./handoff.ts";
5051 import { secureFor } from "../http/cookie_secure.ts";
5152 import { htmlAnswer, readPage, rewritable, withToolbar, type PillWhere } from "./toolbar.ts";
5253
54 /**
55 * The pill's other side, for a viewer who may read the repository; a guest
56 * of a private app, or anyone unnamed, gets none. Previews offered are those
57 * whose pull the viewer may see.
58 */
59 export function otherSide(
60 runtime: AppsRuntime,
61 target: AppTarget,
62 viewerId: string | undefined,
63 ): ReturnType<typeof sideOf> {
64 if (viewerId === undefined) return null;
65 const db = runtime.app.db;
66 const viewer = getUserById(db, viewerId);
67 const repo = getRepoById(db, target.app.repoId);
68 if (viewer === undefined || !isActive(viewer) || repo === undefined) return null;
69 if (!canRead(db, repo, viewer)) return null;
70 const previews: SidePreview[] = [];
71 let production = "";
72 for (const s of runtime.status(target.app)) {
73 if (s.env === "production") {
74 production = s.url;
75 continue;
76 }
77 const number = /^pull-(\d+)$/.exec(s.env)?.[1];
78 const pull = number === undefined ? undefined : getIssue(db, repo.id, Number(number));
79 if (number === undefined || pull === undefined || !mayView(db, repo, pull, viewer)) continue;
80 previews.push({ number: Number(number), title: pull.title, state: s.state, url: s.url });
81 }
82 if (production === "") production = runtime.urlFor(target.app, "production");
83 return sideOf({ url: production }, target.env, previews);
84 }
85
5386 const proxySecure = (request: Request, url: URL, forgeUrl: string): boolean =>
5487 secureFor(url, forgeUrl) ||
5588 request.headers.get("x-forwarded-proto") === "https";
@@ -677,8 +710,15 @@ export async function proxyApp(
677710 target.app,
678711 signed?.who?.id,
679712 );
713 const side = timePhase(request, "side", () =>
714 otherSide(runtime, target, signed?.who?.id),
715 );
680716 const body = timePhase(request, "render", () =>
681 JSON.stringify({ ...crew, ...(tell === undefined ? {} : { tell }) }),
717 JSON.stringify({
718 ...crew,
719 ...(tell === undefined ? {} : { tell }),
720 ...(side === null ? {} : { side }),
721 }),
682722 );
683723 return withPhases(
684724 request,
src/apps/toolbar.ts +14 −2
@@ -234,6 +234,7 @@ export const toolbarJs = `(function () {
234234 .then(function (c) {
235235 if (!c) return;
236236 var forge = new URL(me.src).origin;
237 var ROW = "color:#8ab4ff;text-decoration:none;display:flex;align-items:center;min-height:44px";
237238 // Signed in, the crew can be told from here. The form is the forge's
238239 // own page, on its own origin, with its own CSRF check: the app's
239240 // page only carries the address and the pull to it.
@@ -247,10 +248,21 @@ export const toolbarJs = `(function () {
247248 ta.target = "_blank";
248249 ta.rel = "noopener";
249250 ta.href = t.href;
250 ta.style.cssText = "color:#8ab4ff;text-decoration:none;display:flex;align-items:center;min-height:44px";
251 ta.style.cssText = ROW;
251252 crew.appendChild(ta);
252253 }
253254 }
255 // The other side: its origin plus this path, never resolved against it.
256 if (c.side && typeof c.side.url === "string" && typeof c.side.label === "string") {
257 var so = new URL(c.side.url);
258 if (/^https?:$/.test(so.protocol)) {
259 var sa = document.createElement("a");
260 sa.textContent = c.side.label;
261 sa.href = so.origin + location.pathname + location.search;
262 sa.style.cssText = ROW;
263 crew.appendChild(sa);
264 }
265 }
254266 if (typeof c.who !== "string" || typeof c.url !== "string") return;
255267 var u = new URL(c.url);
256268 if (u.origin !== forge) return;
@@ -258,7 +270,7 @@ export const toolbarJs = `(function () {
258270 a.textContent = c.who + " is working on this";
259271 a.rel = "noopener";
260272 a.href = u.href;
261 a.style.cssText = "color:#8ab4ff;text-decoration:none;display:flex;align-items:center;min-height:44px";
273 a.style.cssText = ROW;
262274 crew.appendChild(a);
263275 })
264276 .catch(function () {});
test/apps-pill-side.test.ts added +125
@@ -0,0 +1,125 @@
1 /**
2 * The pill's other side (#6076): the crew door hands a viewer who may read
3 * the repository the other environment's address; the script joins that
4 * origin to this page's path and never resolves the path against it.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { newApp } from "../src/actions/apps.ts";
13 import { otherSide, type AppTarget } from "../src/apps/proxy.ts";
14 import type { AppsRuntime } from "../src/apps/runtime.ts";
15 import { toolbarJs } from "../src/apps/toolbar.ts";
16 import { getAppByRepo, type AppRecord } from "../src/core/apps.ts";
17 import { createIssue } from "../src/core/issues.ts";
18 import { createUser } from "../src/core/users.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20
21 quietLogs();
22
23 describe("the pill's other side", () => {
24 let dataDir: string;
25 let app: App;
26 let alice: string;
27 let bob: string;
28 let record: AppRecord;
29 let number: number;
30 let runtime: AppsRuntime;
31
32 beforeAll(async () => {
33 dataDir = await mkdtemp(join(tmpdir(), "forge-side-"));
34 app = createApp({ dataDir, port: 0, host: "forge.test" });
35 const person = async (username: string, adminIfFirst?: boolean) => {
36 const u = await createUser(app.db, {
37 origin: "seed",
38 trusted: true,
39 username,
40 email: `${username}@forge.local`,
41 password: "a-good-passphrase",
42 ...(adminIfFirst ? { adminIfFirst } : {}),
43 });
44 if (!u.ok) throw new Error(u.error);
45 return u.value;
46 };
47 const a = await person("alice", true);
48 alice = a.id;
49 bob = (await person("bob")).id;
50 const made = await newApp(app, a, { name: "notes", description: "x", visibility: "private" });
51 if (!made.ok) throw new Error(String(made.error));
52 record = getAppByRepo(app.db, made.value.repo.id)!;
53 const pull = createIssue(app.db, { repoId: record.repoId, authorId: alice, title: "Big", kind: "pull" });
54 if (!pull.ok) throw new Error(pull.error);
55 number = pull.value.number;
56 runtime = {
57 app,
58 urlFor: () => "https://notes.apps.test",
59 status: () => [
60 { env: "production", state: "running", url: "https://notes.apps.test" },
61 { env: `pull-${number}`, state: "running", url: `https://notes--${number}.apps.test` },
62 ],
63 } as unknown as AppsRuntime;
64 }, 120_000);
65
66 afterAll(async () => {
67 app.close();
68 await rm(dataDir, { recursive: true, force: true });
69 });
70
71 const target = (env: string) => ({ app: record, env }) as AppTarget;
72
73 test("a reader gets the other side; a guest or a stranger of a private app gets none", () => {
74 expect(otherSide(runtime, target("production"), alice)).toEqual({
75 label: "Newest preview: #" + number + " Big",
76 url: `https://notes--${number}.apps.test`,
77 });
78 expect(otherSide(runtime, target(`pull-${number}`), alice)).toEqual({
79 label: "Open on production",
80 url: "https://notes.apps.test",
81 });
82 expect(otherSide(runtime, target("production"), undefined)).toBeNull();
83 expect(otherSide(runtime, target("production"), bob)).toBeNull();
84 });
85
86 const hrefFor = async (pathname: string, search: string, side: unknown) => {
87 const links: Record<string, any>[] = [];
88 const el = (): Record<string, any> => ({
89 style: {},
90 dataset: {},
91 appendChild() {},
92 setAttribute() {},
93 addEventListener() {},
94 attachShadow() { return el(); },
95 });
96 const make = (tag: string) => { const e = el(); if (tag === "a") links.push(e); return e; };
97 const doc = {
98 currentScript: { src: "http://forge.test/assets/toolbar-x.js", dataset: { app: "notes", env: "production" } },
99 createElement: make,
100 addEventListener() {},
101 body: el(),
102 };
103 const fn = new Function("window", "document", "fetch", "location", "URL", toolbarJs);
104 await new Promise<void>((done) => {
105 fn({}, doc, () => ({
106 then: (f: (r: unknown) => unknown) => {
107 f({ ok: true, json: () => ({ side }) });
108 return { then: (g: (c: unknown) => void) => { g({ side }); setTimeout(done, 0); return { catch() {} }; } };
109 },
110 }), { href: "https://notes--9.apps.test" + pathname, origin: "https://notes--9.apps.test", pathname, search }, URL);
111 });
112 return links.find((l) => l.textContent === "Open on production")?.href as string | undefined;
113 };
114 const side = { label: "Open on production", url: "https://notes.apps.test" };
115
116 test("the href keeps the path and query on the app's own origin", async () => {
117 expect(await hrefFor("/a/b", "?x=1", side)).toBe("https://notes.apps.test/a/b?x=1");
118 });
119
120 test("a // path cannot leave the app's origin", async () => {
121 const href = await hrefFor("//evil.test/x", "", side);
122 expect(new URL(href!).origin).toBe("https://notes.apps.test");
123 expect(new URL(href!).hostname).not.toBe("evil.test");
124 });
125 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs