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 #5830

Parked opened this
Closed without merging

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

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +288 −5
src/apps/check_now.ts added +48
@@ -0,0 +1,48 @@
1 /**
2 * Whether the pull a preview shows is green, for the forge pill: the newest
3 * check on that pull 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 { latestRunsForIssues } 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 const run = latestRunsForIssues(db, [pull.id]).get(pull.id);
41 if (run === undefined) return undefined;
42 const url = new URL(`/${repo.ownerName}/${repo.name}/runs/${run.id}`, forgeUrl).href;
43 if (run.state === "ok") return { state: "green", url };
44 if (run.state === "queued" || run.state === "running") return { state: "running", url };
45 if (run.state !== "failed") return undefined;
46 const test = run.checkDetail?.names[0];
47 return test === undefined || test === "" ? { state: "red", url } : { state: "red", test, url };
48 }
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 +187
@@ -0,0 +1,187 @@
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 check = (issueId: string): Run =>
106 createRun(app.db, { repoId, kind: "check", issueId, commitOid: "a".repeat(40) });
107 const now = (env: string, ...viewer: [string?]) =>
108 checkNow(app.db, forge, record, env, viewer.length ? viewer[0] : alice);
109 const env = () => `pull-${pullNumber}`;
110
111 test("nothing before a check, then running, red with its first failing test, then green", () => {
112 expect(now(env())).toBeUndefined();
113 const run = check(pullId);
114 expect(now(env())).toEqual({ state: "running", url: `${forge}/alice/notes/runs/${run.id}` });
115 claimRun(app.db, run.id);
116 expect(now(env())!.state).toBe("running");
117 finishRun(app.db, run.id, {
118 state: "failed",
119 summary: "x",
120 checkDetail: { passed: 1, failed: 2, names: ["adds up", "other"] },
121 });
122 expect(now(env())).toEqual({
123 state: "red",
124 test: "adds up",
125 url: `${forge}/alice/notes/runs/${run.id}`,
126 });
127 const next = check(pullId);
128 claimRun(app.db, next.id);
129 finishRun(app.db, next.id, { state: "ok", summary: "ok" });
130 expect(now(env())).toEqual({ state: "green", url: `${forge}/alice/notes/runs/${next.id}` });
131 });
132
133 test("production, another pull and a missing viewer show nothing", () => {
134 expect(now("production")).toBeUndefined();
135 expect(now(`pull-${pullNumber + 99}`)).toBeUndefined();
136 expect(now(env(), undefined)).toBeUndefined();
137 expect(now(env(), "nobody")).toBeUndefined();
138 });
139
140 test("a sealed pull is answered only to who may see it", () => {
141 const sealed = createIssue(app.db, { repoId, authorId: alice, title: "q", kind: "pull" });
142 if (!sealed.ok) throw new Error(sealed.error);
143 const run = check(sealed.value.id);
144 claimRun(app.db, run.id);
145 finishRun(app.db, run.id, { state: "ok", summary: "ok" });
146 const e = `pull-${sealed.value.number}`;
147 expect(now(e, alice)!.state).toBe("green");
148 setSealed(app.db, sealed.value.id, true);
149 expect(now(e, bob)).toBeUndefined();
150 expect(now(e, alice)!.state).toBe("green");
151 });
152
153 test("/__forge/check answers a granted viewer on a preview, names its timing, and {} otherwise", async () => {
154 const cookie = `forge_grant_${record.id.slice(-8)}`;
155 const ask = async (host: string, env: string, who?: string) => {
156 const target = { app: record, env } as AppTarget;
157 const grant = signGrant(dataDir, target, 60_000, Date.now(), { id: alice, name: "alice", role: "admin" });
158 return fetch(`${servers.url}/__forge/check`, {
159 headers: { host, ...(who === undefined ? {} : { cookie: `${cookie}=${grant}` }) },
160 });
161 };
162 const run = check(pullId);
163 claimRun(app.db, run.id);
164 finishRun(app.db, run.id, { state: "ok", summary: "ok" });
165 const preview = await ask(`notes--${pullNumber}.${DOMAIN}`, env(), "alice");
166 expect(preview.status).toBe(200);
167 expect(await preview.json()).toEqual({
168 state: "green",
169 url: `${servers.url}/alice/notes/runs/${run.id}`,
170 });
171 expect(preview.headers.get("server-timing")).toContain("grant;dur=");
172 expect(await (await ask(`notes--${pullNumber}.${DOMAIN}`, env())).json()).toEqual({});
173 const prod = await ask(`notes.${DOMAIN}`, "production", "alice");
174 expect(await prod.json()).toEqual({});
175 expect(prod.headers.get("server-timing")).toContain("check;dur=");
176 expect(prod.headers.get("cache-control")).toBe("no-store");
177 // Whatever host a preview answers on, an unsigned ask is empty.
178 expect(await (await ask(`notes.${DOMAIN}`, "production")).json()).toEqual({});
179 });
180
181 test("the script asks once, only on a preview, and builds with no style attribute or inline script", () => {
182 expect(toolbarJs).toContain("/__forge/check");
183 for (const words of ["check green", "check running", '"check red"']) expect(toolbarJs).toContain(words);
184 expect(toolbarJs).toContain("if (d.pull)");
185 expect(toolbarJs).not.toMatch(/setAttribute\("style"|innerHTML|<script/);
186 });
187 });
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/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