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

Before publishing: decide who reads a public repository's crew run logs, and seal the security work from before sealing existed #1208

Closed opened this
Closed without merging

scout/forge:scout/1075-before-publishing-decide-who-reads-a-pub → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
9 files changed +179 −23
docs/APPS.md +4
@@ -124,6 +124,10 @@ started`; a deploy no push asked for — a redeploy someone pressed, a
124124 follows the same rule: its environments' state and errors (`envsFor`),
125125 its runs and their logs (`mayReadRuns`) and its run and serving events
126126 reach only those who may enter it.
127 On any repository, public too, a run's **log** (the agent's
128 transcript, a deploy's output) is read only by its writers and crew
129 (`mayReadRunLog`); a stranger reads the run and its summary, not the
130 log, on the page, the API and the live tails (#1075).
127131 6. **A run's credential dies with the run.** An agent run gets a token
128132 scoped `rw` (no settings, no tokens, no administration) with an expiry,
129133 and the token is deleted when the run ends however it ends. It never
src/actions/runs.ts +24 −2
@@ -15,7 +15,7 @@ import { steerRun } from "../crew/runner.ts";
1515 import { getIssueById } from "../core/issues.ts";
1616 import { addComment } from "./issues.ts";
1717 import { getAppByRepo } from "../core/apps.ts";
18 import { canEnterApp, type Repo } from "../core/repos.ts";
18 import { canEnterApp, canSeeOwnerFacts, type Repo } from "../core/repos.ts";
1919 import {
2020 cancelRun as markCancelled,
2121 getRun,
@@ -82,6 +82,22 @@ export function mayReadRuns(
8282 );
8383 }
8484
85 /**
86 * Whether `actor` may read a run's log — the agent's transcript, or a
87 * deploy's output. A summary is public with the run; the log is for the
88 * repository's writers and crew only, on a public repository too: it says
89 * what the agent ran, read and concluded, in the detail it wrote for itself.
90 */
91 export function mayReadRunLog(
92 app: App,
93 actor: User | undefined,
94 repo: Repo,
95 ): boolean {
96 return (
97 mayReadRuns(app, actor, repo) && canSeeOwnerFacts(app.db, repo, actor)
98 );
99 }
100
85101 export function listRepoRuns(
86102 app: App,
87103 actor: User | undefined,
@@ -118,6 +134,8 @@ export interface RunLogView {
118134 readonly lines: string[];
119135 readonly truncated: boolean;
120136 readonly path: string;
137 /** The reader may see the run but not its log: `lines` is empty. */
138 readonly logHidden: boolean;
121139 }
122140
123141 export function runLog(
@@ -128,12 +146,16 @@ export function runLog(
128146 ): Result<RunLogView, "not_found"> {
129147 const found = getRepoRun(app, actor, repo, runId);
130148 if (!found.ok) return found;
131 const { lines, truncated } = readRunLog(app.config.dataDir, runId);
149 const logHidden = !mayReadRunLog(app, actor, repo);
150 const { lines, truncated } = logHidden
151 ? { lines: [], truncated: false }
152 : readRunLog(app.config.dataDir, runId);
132153 return ok({
133154 run: found.value,
134155 lines,
135156 truncated,
136157 path: runLogPath(app.config.dataDir, runId),
158 logHidden,
137159 });
138160 }
139161
src/http/api.ts +1 −1
@@ -4449,7 +4449,7 @@ export function apiRoutes(router: Router<Handler>): void {
44494449 const repo = loadRepo(ctx);
44504450 if (!repo) return notFound();
44514451 const found = runLog(ctx.app, ctx.auth.user, repo, ctx.params.id ?? "");
4452 if (!found.ok) return notFound();
4452 if (!found.ok || found.value.logHidden) return notFound();
44534453 const follow =
44544454 ctx.url.searchParams.get("follow") === "1" ||
44554455 (ctx.request.headers.get("accept") ?? "").includes("text/event-stream");
src/web/pages/runs.ts +2 −2
@@ -298,8 +298,8 @@ export async function runPage(ctx: Ctx): Promise<Response> {
298298 if (!repo) return notFoundPage(ctx);
299299 const found = runLog(ctx.app, ctx.auth.user, repo, ctx.params.id ?? "");
300300 if (!found.ok) return notFoundPage(ctx);
301 const { run, lines, truncated } = found.value;
302 return await runView(ctx, repo, run, lines, truncated);
301 const { run, lines, truncated, logHidden } = found.value;
302 return await runView(ctx, repo, run, lines, truncated, logHidden);
303303 }
304304
305305 // POST /:owner/:name/runs/:id/steer { text }
src/web/studio/now.ts +2 −2
@@ -20,7 +20,7 @@ import { getUsersByIds } from "../../core/users.ts";
2020 import { repoDir } from "../../git/repos.ts";
2121 import type { Ctx } from "../../http/context.ts";
2222 import { readRunLogTail } from "../../runs/log.ts";
23 import { mayReadRuns } from "../../actions/runs.ts";
23 import { mayReadRunLog } from "../../actions/runs.ts";
2424 import { loadRepo, repoBase } from "../chrome.ts";
2525 import { html, type Html } from "../html.ts";
2626 import { fragment } from "../layout.ts";
@@ -169,7 +169,7 @@ export async function nowCard(
169169 (r) => r.kind === "agent" && r.state === "running",
170170 );
171171 const activeTail =
172 activeRun && mayReadRuns(ctx.app, ctx.auth.user, repo)
172 activeRun && mayReadRunLog(ctx.app, ctx.auth.user, repo)
173173 ? logBox({
174174 id: "app-run-tail",
175175 who: voiceFor(runActor(activeRun), ownerFacts),
src/web/studio/previews.ts +3 −2
@@ -194,7 +194,8 @@ function previewsPanel(
194194 * Once the deploy has swapped in, the lines are the app's own — never the
195195 * deploy's, whose word (`envPhrase`) has already moved on to "live" — and
196196 * an app's stdout can carry anything the owner never meant for a stranger,
197 * so only a viewer who can see the owner's facts is shown it at all.
197 * so only a viewer who can see the owner's facts is shown it at all —
198 * a deploy's too, as it is a log (`mayReadRunLog`).
198199 */
199200 function productionTail(
200201 ctx: Ctx,
@@ -206,7 +207,7 @@ function productionTail(
206207 if (production === undefined || production.runId === undefined) return none;
207208 const deploying = production.state === "deploying";
208209 if (!deploying && production.state !== "running") return none;
209 if (!deploying && !writer) return none;
210 if (!writer) return none;
210211 const agentBusy = listRuns(ctx.app.db, repo.id, {
211212 kind: "agent",
212213 limit: 8,
src/web/studio/run.ts +11 −3
@@ -66,6 +66,7 @@ export async function runView(
6666 run: Run,
6767 lines: readonly string[],
6868 truncated: boolean,
69 logHidden = false,
6970 ): Promise<Response> {
7071 const db = ctx.app.db;
7172 const base = repoBase(repo);
@@ -203,6 +204,13 @@ export async function runView(
203204 </div>`,
204205 )}
205206 ${when(pull, (p) => previewCard(ctx, repo, p))}
207 ${when(
208 logHidden,
209 () =>
210 html`<p class="muted small" id="run-log-hidden">
211 The log is for this repository's writers and crew.
212 </p>`,
213 )}
206214 ${when(
207215 truncated,
208216 () =>
@@ -211,14 +219,14 @@ export async function runView(
211219 </p>`,
212220 )}
213221 ${when(
214 lines.length === 0,
222 lines.length === 0 && !logHidden,
215223 () =>
216224 html`<p class="muted small" id="run-empty">
217225 Nothing has been logged yet.
218226 </p>`,
219227 )}
220228 <div class="run-live" id="run-live" data-state="${run.state}">
221 ${logBox({
229 ${when(!logHidden, () => logBox({
222230 id: "run-log",
223231 who,
224232 cap: all
@@ -232,7 +240,7 @@ export async function runView(
232240 extra: html`<button type="button" class="run-jump" id="run-jump" hidden>
233241 newer below
234242 </button>`,
235 })}
243 }))}
236244 ${when(
237245 run.kind === "agent",
238246 () => html`<p class="muted small crew-note">${directionNote(repo)}</p>`,
test/run-log-audience.test.ts added +124
@@ -0,0 +1,124 @@
1 /**
2 * A public repository's run is public in its summary and private in its log
3 * (#1075): the log is the agent's transcript — what it ran, read and
4 * concluded — so only the repository's writers and crew read it, on the run
5 * page, the API, and the live tails beside it.
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 { commitToBranch, createRepo } from "../src/actions/repos.ts";
13 import { claimRun, createRun } from "../src/core/runs.ts";
14 import { finishRun } from "../src/core/runs.ts";
15 import { createToken } from "../src/core/tokens.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
18 import { appendRunLog } from "../src/runs/log.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20
21 quietLogs();
22
23 const LINE = "R7LOGLINE cat /sandbox/notes.txt";
24 const SUMMARY = "R7SUMMARY fixed the thing";
25
26 let dataDir: string;
27 let app: App;
28 let http: ForgeHttp;
29 let runId: string;
30 const token: Record<string, string> = {};
31
32 const ok = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
33 if (!r.ok) throw new Error(JSON.stringify(r.error));
34 return r.value;
35 };
36
37 async function get(path: string, who?: string) {
38 const res = await http.handle(new Request(`http://forge.test${path}`, {
39 headers: who === undefined ? {} : { authorization: `Bearer ${token[who]}` },
40 }));
41 return { status: res.status, text: await res.text() };
42 }
43
44 beforeAll(async () => {
45 dataDir = await mkdtemp(join(tmpdir(), "forge-runlog-"));
46 app = createApp({ dataDir, port: 0 });
47 http = forgeHttp(app);
48 const alice: User = ok(
49 await createUser(app.db, {
50 trusted: true,
51 username: "alice",
52 email: "[email protected]",
53 password: "a-good-passphrase",
54 adminIfFirst: true,
55 }),
56 );
57 const mallory = ok(
58 await createUser(app.db, {
59 trusted: true,
60 username: "mallory",
61 email: "[email protected]",
62 password: "a-good-passphrase",
63 }),
64 );
65 const repo = ok(
66 await createRepo(app, alice, { name: "square", visibility: "public" }),
67 );
68 ok(
69 await commitToBranch(app, alice, repo, {
70 message: "Start",
71 files: [{ path: "README.md", content: "# square\n" }],
72 }),
73 );
74 token.alice = createToken(app.db, alice.id, "t", "rw").token;
75 token.mallory = createToken(app.db, mallory.id, "t", "rw").token;
76 const run = createRun(app.db, {
77 repoId: repo.id,
78 kind: "agent",
79 actorId: alice.id,
80 reason: "assigned",
81 });
82 claimRun(app.db, run.id);
83 runId = run.id;
84 appendRunLog(dataDir, runId, LINE);
85 finishRun(app.db, runId, { state: "ok", summary: SUMMARY });
86 }, 60_000);
87
88 afterAll(async () => {
89 app?.close();
90 await rm(dataDir, { recursive: true, force: true });
91 });
92
93 describe("run log audience", () => {
94 test("a stranger reads a public repository's run summary, not its log", async () => {
95 for (const who of [undefined, "mallory"]) {
96 const api = await get(`/api/v1/repos/alice/square/runs/${runId}`, who);
97 expect(api.status).toBe(200);
98 expect(api.text).toContain("R7SUMMARY");
99
100 const page = await get(`/alice/square/runs/${runId}`, who);
101 expect(page.status).toBe(200);
102 expect(page.text).toContain("R7SUMMARY");
103 expect(page.text).not.toContain("R7LOGLINE");
104 expect(page.text).not.toContain(`/runs/${runId}/log`);
105
106 for (const path of [
107 `/api/v1/repos/alice/square/runs/${runId}/log`,
108 `/api/v1/repos/alice/square/runs/${runId}/log?follow=1`,
109 ]) {
110 const log = await get(path, who);
111 expect(log.status).toBe(404);
112 expect(log.text).not.toContain("R7LOGLINE");
113 }
114 }
115 });
116
117 test("a writer still reads the log, on the API and the page", async () => {
118 const log = await get(`/api/v1/repos/alice/square/runs/${runId}/log`, "alice");
119 expect(log.status).toBe(200);
120 expect(log.text).toContain("R7LOGLINE");
121 const page = await get(`/alice/square/runs/${runId}`, "alice");
122 expect(page.text).toContain("R7LOGLINE");
123 });
124 });
test/studio.test.ts +8 −11
@@ -6076,17 +6076,14 @@ describe("a stranger sees the app, not the owner's books", () => {
60766076 ).json()) as { items: { costUsd: number }[] };
60776077 expect(listAsStranger.items.every((r) => r.costUsd === 0)).toBe(true);
60786078
6079 const tailAsStranger = await (
6080 await get(
6081 `/api/v1/repos/alice/beacon/runs/${run.id}/log?follow=1`,
6082 strangerCookie,
6083 )
6084 ).text();
6085 expect(tailAsStranger).toContain("event: done");
6086 // The cost by its key, not its digits: a timestamp's seconds can read
6087 // "42.5" too, and once did.
6088 expect(tailAsStranger).not.toContain('"costUsd":42.5');
6089 expect(tailAsStranger).toContain('"costUsd":0');
6079 // The log is the writers' and crew's (#1075): a stranger's tail is
6080 // refused, and carries neither the cost nor the transcript.
6081 const tailAsStranger = await get(
6082 `/api/v1/repos/alice/beacon/runs/${run.id}/log?follow=1`,
6083 strangerCookie,
6084 );
6085 expect(tailAsStranger.status).toBe(404);
6086 expect(await tailAsStranger.text()).not.toContain("42.5");
60906087 const tailAsOwner = await (
60916088 await get(
60926089 `/api/v1/repos/alice/beacon/runs/${run.id}/log?follow=1`,

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs