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

In a preview, the forge pill's panel says the pull's check: green, red with its first failing test, or running, and links to the check log #6370

Closed opened this
Closed without merging

scout/forge:scout/5827-in-a-preview-the-forge-pill-s-panel-says → main 7 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +320 −6
src/apps/check_now.ts added +56
@@ -0,0 +1,56 @@
1 /**
2 * Whether the pull a preview shows is green, for the forge pill: the newest
3 * check on that pull's current head as `green`, `red` with its first failing test, or
4 * `running`, and the forge page of its log. Only on a preview, and only for
5 * a person the app has admitted who may read the repository and the pull;
6 * everyone else, production, and a pull nothing has checked get nothing.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import type { AppRecord } from "../core/apps.ts";
11 import { getIssue } from "../core/issues.ts";
12 import { canRead, getRepoById } from "../core/repos.ts";
13 import { verdictForHead } from "../core/runs.ts";
14 import { mayView } from "../core/sealed.ts";
15 import { getUserById, isActive } from "../core/users.ts";
16
17 export type CheckNow = {
18 state: "green" | "red" | "running";
19 /** The first failing test's name, for a red check that named one. */
20 test?: string;
21 url: string;
22 };
23
24 export function checkNow(
25 db: Database,
26 forgeUrl: string,
27 app: AppRecord,
28 env: string,
29 viewerId: string | undefined,
30 ): CheckNow | undefined {
31 const number = /^pull-(\d+)$/.exec(env)?.[1];
32 if (number === undefined || viewerId === undefined) return undefined;
33 const viewer = getUserById(db, viewerId);
34 const repo = getRepoById(db, app.repoId);
35 if (viewer === undefined || !isActive(viewer) || repo === undefined) return undefined;
36 if (!canRead(db, repo, viewer)) return undefined;
37 const pull = getIssue(db, repo.id, Number(number));
38 if (pull === undefined || pull.kind !== "pull" || !mayView(db, repo, pull, viewer))
39 return undefined;
40 // Only a run at the pull's current head speaks; a push that has no run yet is running.
41 const head = db
42 .query<{ head_oid: string }, [string]>("SELECT head_oid FROM pull WHERE issue_id = ?1")
43 .get(pull.id)?.head_oid;
44 if (head === undefined || head === "") return undefined;
45 const run = verdictForHead(db, pull.id, head).find((r) => r.kind === "check");
46 if (run === undefined) {
47 const url = new URL(`/${repo.ownerName}/${repo.name}/pulls/${pull.number}`, forgeUrl).href;
48 return { state: "running", url };
49 }
50 const url = new URL(`/${repo.ownerName}/${repo.name}/runs/${run.id}`, forgeUrl).href;
51 if (run.state === "ok") return { state: "green", url };
52 if (run.state === "queued" || run.state === "running") return { state: "running", url };
53 if (run.state !== "failed") return undefined;
54 const test = run.checkDetail?.names[0];
55 return test === undefined || test === "" ? { state: "red", url } : { state: "red", test, url };
56 }
src/apps/proxy.ts +27
@@ -36,6 +36,7 @@ import { err, ok, type Result } from "../kernel/result.ts";
3636 import { loadKey } from "../kernel/secret.ts";
3737 import { previewEnv, type EnvName } from "./data.ts";
3838 import type { AppsRuntime, EnvStatus } from "./runtime.ts";
39 import { checkNow } from "./check_now.ts";
3940 import { crewNow, tellLink } from "./crew.ts";
4041 import { feedback, mintProof } from "./feedback.ts";
4142 import { clientBucket } from "../http/peer.ts";
@@ -692,6 +693,32 @@ export async function proxyApp(
692693 ),
693694 );
694695 }
696 // The pill's fifth door: whether this preview's pull is green, for the
697 // person the app's own grant names. Production, and anyone unseen, get {}.
698 if (url.pathname === "/__forge/check" && !target.nested) {
699 const began = performance.now();
700 const cookie = cookieValue(request, grantCookieName(target));
701 const signed =
702 cookie === undefined
703 ? undefined
704 : readGrant(runtime.app.config.dataDir, cookie, target);
705 const read = performance.now();
706 const check = checkNow(
707 runtime.app.db,
708 runtime.options.forgeUrl,
709 target.app,
710 target.env,
711 signed?.who?.id,
712 );
713 const done = performance.now();
714 return Response.json(check ?? {}, {
715 headers: {
716 "cache-control": "no-store",
717 "x-content-type-options": "nosniff",
718 "server-timing": `grant;dur=${(read - began).toFixed(1)}, check;dur=${(done - read).toFixed(1)}`,
719 },
720 });
721 }
695722 // The forge's small page on the app's own host: the way back when the pill
696723 // is not shown. A nested host is its guest's, and has no such page.
697724 if (url.pathname === "/__forge/") {
src/apps/toolbar.ts +21
@@ -279,6 +279,27 @@ export const toolbarJs = `(function () {
279279 })
280280 .catch(function () {});
281281 } catch (e) {}
282 // Whether this preview's pull is green, asked once, the same way; production asks nothing.
283 if (d.pull) {
284 try {
285 fetch("/__forge/check", { credentials: "same-origin", cache: "no-store" })
286 .then(function (r) { return r.json(); })
287 .then(function (c) {
288 var text = c.state === "red" ? "check red" + (c.test ? ": " + c.test : "")
289 : c.state === "green" ? "check green" : c.state === "running" ? "check running" : "";
290 var u = new URL(c.url);
291 if (!text || u.origin !== new URL(me.src).origin) return;
292 var a = document.createElement("a");
293 a.textContent = text;
294 a.target = "_blank";
295 a.rel = "noopener";
296 a.href = u.href;
297 a.style.cssText = "color:#8ab4ff;text-decoration:none;display:flex;align-items:center;min-height:44px;overflow-wrap:anywhere";
298 crew.appendChild(a);
299 })
300 .catch(function () {});
301 } catch (e) {}
302 }
282303 // Where the pill sits: one of four corners, kept per app host (localStorage
283304 // is per origin), so a page's own controls can be left uncovered.
284305 var KEY = "forge-pill-corner";
test/apps-check-pill.test.ts added +210
@@ -0,0 +1,210 @@
1 /**
2 * The forge pill says whether a preview's pull is green (#5827): green, red
3 * with its first failing test, or running, linked to the check's log; nothing
4 * on production, for a pull the viewer cannot see, or without a grant.
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 { checkNow } from "../src/apps/check_now.ts";
14 import { signGrant, type AppTarget } from "../src/apps/proxy.ts";
15 import { AppsRuntime } from "../src/apps/runtime.ts";
16 import { toolbarJs } from "../src/apps/toolbar.ts";
17 import { getAppByRepo, type AppRecord } from "../src/core/apps.ts";
18 import { createIssue } from "../src/core/issues.ts";
19 import { claimRun, createRun, finishRun, type Run } from "../src/core/runs.ts";
20 import { setSealed } from "../src/core/sealed.ts";
21 import { createUser } from "../src/core/users.ts";
22 import { serve, type Servers } from "../src/http/server.ts";
23 import { quietLogs } from "./helpers/globals.ts";
24
25 quietLogs();
26
27 const DOMAIN = "apps.test";
28
29 describe("the check line", () => {
30 let dataDir: string;
31 let app: App;
32 let servers: Servers;
33 let runtime: AppsRuntime;
34 let alice: string;
35 let bob: string;
36 let record: AppRecord;
37 let repoId: string;
38 let pullId: string;
39 let pullNumber: number;
40 let sealedId: string;
41 const forge = "http://forge.test";
42
43 beforeAll(async () => {
44 dataDir = await mkdtemp(join(tmpdir(), "forge-check-"));
45 app = createApp({ dataDir, port: 0, host: "forge.test" });
46 servers = await serve(app);
47 runtime = new AppsRuntime(app, {
48 domain: DOMAIN,
49 scheme: "http",
50 publicPort: servers.port,
51 forgeUrl: servers.url,
52 concurrency: 1,
53 });
54 await runtime.start();
55 const person = async (username: string, adminIfFirst?: boolean) => {
56 const u = await createUser(app.db, {
57 origin: "seed",
58 trusted: true,
59 username,
60 email: `${username}@forge.local`,
61 password: "a-good-passphrase",
62 ...(adminIfFirst ? { adminIfFirst } : {}),
63 });
64 if (!u.ok) throw new Error(u.error);
65 return u.value;
66 };
67 const a = await person("alice", true);
68 alice = a.id;
69 bob = (await person("bob")).id;
70 const made = await newApp(app, a, {
71 name: "notes",
72 description: "x",
73 visibility: "public",
74 });
75 if (!made.ok) throw new Error(String(made.error));
76 repoId = made.value.repo.id;
77 record = getAppByRepo(app.db, repoId)!;
78 const pull = createIssue(app.db, {
79 repoId,
80 authorId: alice,
81 title: "p",
82 kind: "pull",
83 });
84 if (!pull.ok) throw new Error(pull.error);
85 pullId = pull.value.id;
86 pullNumber = pull.value.number;
87 const secret = createIssue(app.db, {
88 repoId,
89 authorId: alice,
90 title: "s",
91 kind: "issue",
92 });
93 if (!secret.ok) throw new Error(secret.error);
94 sealedId = secret.value.id;
95 setSealed(app.db, sealedId, true);
96 }, 120_000);
97
98 afterAll(async () => {
99 await runtime.stop();
100 servers.stop();
101 app.close();
102 await rm(dataDir, { recursive: true, force: true });
103 });
104
105 const headAt = (issueId: string, oid: string) =>
106 app.db
107 .query(
108 "INSERT OR REPLACE INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid) VALUES (?, 'main', 'h', 'b', ?)",
109 )
110 .run(issueId, oid);
111 const check = (issueId: string, oid = "a".repeat(40)): Run => {
112 headAt(issueId, oid);
113 return createRun(app.db, { repoId, kind: "check", issueId, commitOid: oid });
114 };
115 const now = (env: string, ...viewer: [string?]) =>
116 checkNow(app.db, forge, record, env, viewer.length ? viewer[0] : alice);
117 const env = () => `pull-${pullNumber}`;
118
119 test("nothing before a check, then running, red with its first failing test, then green", () => {
120 expect(now(env())).toBeUndefined();
121 const run = check(pullId);
122 expect(now(env())).toEqual({ state: "running", url: `${forge}/alice/notes/runs/${run.id}` });
123 claimRun(app.db, run.id);
124 expect(now(env())!.state).toBe("running");
125 finishRun(app.db, run.id, {
126 state: "failed",
127 summary: "x",
128 checkDetail: { passed: 1, failed: 2, names: ["adds up", "other"] },
129 });
130 expect(now(env())).toEqual({
131 state: "red",
132 test: "adds up",
133 url: `${forge}/alice/notes/runs/${run.id}`,
134 });
135 const next = check(pullId);
136 claimRun(app.db, next.id);
137 finishRun(app.db, next.id, { state: "ok", summary: "ok" });
138 expect(now(env())).toEqual({ state: "green", url: `${forge}/alice/notes/runs/${next.id}` });
139 });
140
141 test("a push whose check has not begun is running, never the last head's verdict", () => {
142 const p = createIssue(app.db, { repoId, authorId: alice, title: "r", kind: "pull" });
143 if (!p.ok) throw new Error(p.error);
144 const run = check(p.value.id, "b".repeat(40));
145 claimRun(app.db, run.id);
146 finishRun(app.db, run.id, { state: "ok", summary: "ok" });
147 const e = `pull-${p.value.number}`;
148 expect(now(e)!.state).toBe("green");
149 headAt(p.value.id, "c".repeat(40));
150 expect(now(e)).toEqual({
151 state: "running",
152 url: `${forge}/alice/notes/pulls/${p.value.number}`,
153 });
154 });
155
156 test("production, another pull and a missing viewer show nothing", () => {
157 expect(now("production")).toBeUndefined();
158 expect(now(`pull-${pullNumber + 99}`)).toBeUndefined();
159 expect(now(env(), undefined)).toBeUndefined();
160 expect(now(env(), "nobody")).toBeUndefined();
161 });
162
163 test("a sealed pull is answered only to who may see it", () => {
164 const sealed = createIssue(app.db, { repoId, authorId: alice, title: "q", kind: "pull" });
165 if (!sealed.ok) throw new Error(sealed.error);
166 const run = check(sealed.value.id);
167 claimRun(app.db, run.id);
168 finishRun(app.db, run.id, { state: "ok", summary: "ok" });
169 const e = `pull-${sealed.value.number}`;
170 expect(now(e, alice)!.state).toBe("green");
171 setSealed(app.db, sealed.value.id, true);
172 expect(now(e, bob)).toBeUndefined();
173 expect(now(e, alice)!.state).toBe("green");
174 });
175
176 test("/__forge/check answers a granted viewer on a preview, names its timing, and {} otherwise", async () => {
177 const cookie = `forge_grant_${record.id.slice(-8)}`;
178 const ask = async (host: string, env: string, who?: string) => {
179 const target = { app: record, env } as AppTarget;
180 const grant = signGrant(dataDir, target, 60_000, Date.now(), { id: alice, name: "alice", role: "admin" });
181 return fetch(`${servers.url}/__forge/check`, {
182 headers: { host, ...(who === undefined ? {} : { cookie: `${cookie}=${grant}` }) },
183 });
184 };
185 const run = check(pullId);
186 claimRun(app.db, run.id);
187 finishRun(app.db, run.id, { state: "ok", summary: "ok" });
188 const preview = await ask(`notes--${pullNumber}.${DOMAIN}`, env(), "alice");
189 expect(preview.status).toBe(200);
190 expect(await preview.json()).toEqual({
191 state: "green",
192 url: `${servers.url}/alice/notes/runs/${run.id}`,
193 });
194 expect(preview.headers.get("server-timing")).toContain("grant;dur=");
195 expect(await (await ask(`notes--${pullNumber}.${DOMAIN}`, env())).json()).toEqual({});
196 const prod = await ask(`notes.${DOMAIN}`, "production", "alice");
197 expect(await prod.json()).toEqual({});
198 expect(prod.headers.get("server-timing")).toContain("check;dur=");
199 expect(prod.headers.get("cache-control")).toBe("no-store");
200 // Whatever host a preview answers on, an unsigned ask is empty.
201 expect(await (await ask(`notes.${DOMAIN}`, "production")).json()).toEqual({});
202 });
203
204 test("the script asks once, only on a preview, and builds with no style attribute or inline script", () => {
205 expect(toolbarJs).toContain("/__forge/check");
206 for (const words of ["check green", "check running", '"check red"']) expect(toolbarJs).toContain(words);
207 expect(toolbarJs).toContain("if (d.pull)");
208 expect(toolbarJs).not.toMatch(/setAttribute\("style"|innerHTML|<script/);
209 });
210 });
test/apps-crew-pill.test.ts +3 −3
@@ -197,15 +197,15 @@ describe("the crew line", () => {
197197
198198 test("the script asks once, same-origin, and never reads the page or its cookies", () => {
199199 expect(toolbarJs).toContain("/__forge/crew");
200 // One fetch is the crew line; the other is `call`, the feedback door's
200 // Two fetches are the crew line and the check line (#5827); the third is `call`, the feedback door's
201201 // single path (#4758): the sender's notes, polled only while the panel
202202 // is open, and the send, each carrying the proof header in and out.
203 expect(toolbarJs.match(/fetch\(/g)?.length).toBe(2);
203 expect(toolbarJs.match(/fetch\(/g)?.length).toBe(3);
204204 expect(toolbarJs.match(/setInterval/g)?.length).toBe(1);
205205 expect(toolbarJs).not.toMatch(
206206 /document\.cookie|querySelector|getElementById|setTimeout/,
207207 );
208208 expect(toolbarJs).toContain('aria-live", "polite"');
209 expect(toolbarJs.length).toBeLessThan(16 * 1024);
209 expect(toolbarJs.length).toBeLessThan(18 * 1024);
210210 });
211211 });
test/apps-toolbar.test.ts +1 −1
@@ -366,7 +366,7 @@ describe("the forge pill", () => {
366366 expect(res.headers.get("content-type")).toContain("javascript");
367367 const code = await res.text();
368368 expect(code).toBe(toolbarJs);
369 expect(code.length).toBeLessThan(16 * 1024);
369 expect(code.length).toBeLessThan(18 * 1024);
370370 expect(code).not.toMatch(/\beval\b|new Function|\son[a-z]+\s*=/);
371371 expect(code).toContain("attachShadow");
372372 });
test/toolbar-actions.test.ts +2 −2
@@ -88,9 +88,9 @@ describe("toolbar actions", () => {
8888
8989 test("the bar links to the forge page and never posts or reads the app", () => {
9090 expect(toolbarJs).toContain('"/toolbar"');
91 // Its requests are all to the app's own origin: the crew line (#2233) and,
91 // Its requests are all to the app's own origin: the crew line (#2233), the check line (#5827) and,
9292 // for the feedback door (#4758), the sender's notes and their status.
93 expect(toolbarJs.match(/fetch\(/g)?.length).toBe(2);
93 expect(toolbarJs.match(/fetch\(/g)?.length).toBe(3);
9494 expect(toolbarJs).toContain('fetch("/__forge/crew"');
9595 expect(toolbarJs).toContain('call("/__forge/note"');
9696 expect(toolbarJs).not.toMatch(/FormData|\.send\(/);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs