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

Traces 5b: a trace has a share link, off by default, revocable, served with secrets redacted #18162

opened this

Closed 10h 21m ago

scout/forge:scout/18084-traces-5b-a-trace-has-a-share-link-off-b → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
9 files changed +328 −5
docs/features/traces.md +8
@@ -33,3 +33,11 @@ The file is read whole, then parsed, so the 256 MB limit is memory-bound: a sess
3333 ## One trace as a tree (#18022)
3434
3535 `GET /api/v1/traces/:id` answers the thread, its turns and their steps as one tree, rebuilt from the raw log with `parseRunLog` (a Talk turn's log is a run log): the thread's figures are the list's row (model, account, tokens in, cached and out, cost, outcome, started, ended, steps, errors), each step has its start and end in ms, kind, name, line, model, tokens and outcome (a run log holds no tokens per step, so those are 0). `timed` is false where the log kept no times. `truncated` is true when the log's start was cut (it is read from its last 512 KB) or it holds more than `MAX_STEPS` (20,000) steps. A trace the caller may not see answers exactly as an unknown id: 404 `not_found`. The tree is answered whole (about 15 ms for 5,000 steps). Code: `readTraceTree` in `src/http/api/traces.ts`.
36
37 ## A share link (#18084)
38
39 The owner of a crew run's trace (whoever sees the run's cost: the repository's owner or writers) can show it to someone without an account, and take it back. Off until made. On `/traces/<run id>` a **Share** section has **Make a link** (`POST /traces/<run id>/share`) and **Revoke every link** (`POST …/unshare`); the link `/t/<token>` is shown once on the answer to making it, and only its SHA-256 is kept (`trace_share`). Both are same-origin only; a reader who is not the owner gets the 404 a missing trace gets (403 for a writer-less reader of the log). No grant or role of its own: it is the run log's owner rule.
40
41 `/t/<token>` serves the steps and their raw lines read-only, every line passed through `redactHeld` again (a log written before a value was held is masked now), with no repository, cost or links, `no-store`, `no-referrer` and `noindex`. A revoked, unknown or malformed token is 404. Terminal door: on a trace screen `s` makes a link (shown once) and `x` revokes them. Code: `src/trace/share.ts`, `src/web/pages/trace.ts`.
42
43 Not yet: expiry, naming a link, revoking one of several, a JSON twin.
src/core/migration-pins/20261204060000-trace-share.pin added +1
@@ -0,0 +1,1 @@
1 5b75cc30bee8cf87ba84e992e83f817661e09862dbf36ce48e0fbbbf8f552781
src/core/migrations/20261204060000-trace-share.ts added +15
@@ -0,0 +1,15 @@
1 // A trace's share link (#18084, part of #17995): off until its owner makes one, revocable. One row
2 // per link a trace's owner made: the crew run it opens, the hash of the token (the token itself
3 // is shown once and never kept), who made it, and when it was taken back. Additive; no grant
4 // table of its own: who may make or revoke is the run log's owner rule (`canSeeOwnerFacts`).
5 export default `
6 CREATE TABLE trace_share (
7 id TEXT PRIMARY KEY,
8 run_id TEXT NOT NULL,
9 token_hash TEXT NOT NULL UNIQUE,
10 created_by TEXT NOT NULL,
11 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
12 revoked_at TEXT
13 ) WITHOUT ROWID;
14 CREATE INDEX trace_share_by_run ON trace_share(run_id) WHERE revoked_at IS NULL;
15 `;
src/http/lazy_lists.ts +3
@@ -703,6 +703,9 @@ export const OPERATIONS_ROUTES = [
703703 ["GET", "/traces"],
704704 ["GET", "/traces/:id"],
705705 ["GET", "/traces/:id/steps/:n"],
706 ["POST", "/traces/:id/share"],
707 ["POST", "/traces/:id/unshare"],
708 ["GET", "/t/:token"],
706709 ] as const;
707710
708711 /** `originsRoutes` (`routes/origins.ts`). */
src/http/routes/operations.ts +5 −1
@@ -22,7 +22,7 @@ import { pipelinePage } from "../../web/pages/pipeline.ts";
2222 import { advisoriesIngest, advisoriesPage } from "../../web/pages/advisories.ts";
2323 import { resiliencePage, nightlyOutputPage } from "../../web/pages/resilience.ts";
2424 import { runRedirect } from "../../web/pages/runs.ts";
25 import { tracePage, traceStep } from "../../web/pages/trace.ts";
25 import { sharedPage, tracePage, traceShare, traceStep, traceUnshare } from "../../web/pages/trace.ts";
2626 import { tracesPage } from "../../web/pages/traces.ts";
2727 import { oauthCallbackUri } from "../api.ts";
2828 import { gamesRoutes } from "../games_routes.ts";
@@ -124,4 +124,8 @@ export function operationsRoutes(router: Router<Handler>, knownPatterns: () => s
124124 router.add("GET", "/traces", tracesPage);
125125 router.add("GET", "/traces/:id", tracePage);
126126 router.add("GET", "/traces/:id/steps/:n", traceStep);
127 router.add("POST", "/traces/:id/share", traceShare);
128 router.add("POST", "/traces/:id/unshare", traceUnshare);
129 // A shared trace (#18084), open to anyone holding a live link.
130 router.add("GET", "/t/:token", sharedPage);
127131 }
src/trace/share.ts added +84
@@ -0,0 +1,84 @@
1 /**
2 * A trace's share link (#18084): the owner of a crew run's trace shows it to someone without an
3 * account, and takes it back. Off until made; the raw token is returned once and only its hash is
4 * kept (`trace_share`). Who may make or revoke is the run log's owner rule (`canSeeOwnerFacts`
5 * over a log the actor may read): no grant or role of its own. What `/t/<token>` shows is the
6 * steps and their raw lines, every line passed through `redactHeld` again on the way out (a log
7 * written before a value was held is masked now), and nothing else: no repository, cost or link.
8 */
9 import { mayReadLogOfRun } from "../actions/runs.ts";
10 import type { App } from "../app.ts";
11 import { getIssueById } from "../core/issues.ts";
12 import { canSeeOwnerFacts, getRepoById, type Repo } from "../core/repos.ts";
13 import { getRun } from "../core/runs.ts";
14 import type { User } from "../core/users.ts";
15 import { sha256 } from "../kernel/hash.ts";
16 import { id, secret } from "../kernel/id.ts";
17 import { redactHeld } from "../kernel/log.ts";
18 import { err, ok, type Result } from "../kernel/result.ts";
19 import { readRunLog, readRunTimes } from "../runs/log.ts";
20 import { restoreRunLog } from "../runs/archive.ts";
21 import { stepsOf, type Step } from "./model.ts";
22 import { parseRunLog } from "./run_log.ts";
23
24 export type ShareError = "not_found" | "owner_only";
25
26 /** What a link opens: redacted steps, each with its raw lines. */
27 export interface SharedTrace {
28 readonly title: string;
29 readonly timed: boolean;
30 readonly truncated: boolean;
31 readonly steps: readonly { readonly step: Step; readonly lines: readonly string[] }[];
32 }
33
34 /** The token's shape: `tr_` and 43 base64url characters; anything else is 404 without a lookup. */
35 export const SHARE_TOKEN = /^tr_[A-Za-z0-9_-]{20,80}$/;
36
37 /** The path a link lives at. */
38 export const shareHref = (token: string): string => `/t/${token}`;
39
40 function ownerOf(app: App, actor: User | undefined, repo: Repo, runId: string): ShareError | undefined {
41 if (actor === undefined || !mayReadLogOfRun(app, actor, repo, runId)) return "not_found";
42 return canSeeOwnerFacts(app.db, repo, actor) ? undefined : "owner_only";
43 }
44
45 /** Make a link for the run's trace. The token is in the answer once; only its hash is stored. */
46 export function createShare(app: App, actor: User | undefined, repo: Repo, runId: string): Result<{ token: string }, ShareError> {
47 const refused = ownerOf(app, actor, repo, runId);
48 if (refused !== undefined) return err(refused);
49 const token = `tr_${secret()}`;
50 app.db.query("INSERT INTO trace_share (id, run_id, token_hash, created_by) VALUES (?1, ?2, ?3, ?4)").run(id(), runId, sha256(token), actor!.id);
51 return ok({ token });
52 }
53
54 /** Take back every live link of the run; how many were live. */
55 export function revokeShares(app: App, actor: User | undefined, repo: Repo, runId: string): Result<number, ShareError> {
56 const refused = ownerOf(app, actor, repo, runId);
57 if (refused !== undefined) return err(refused);
58 const done = app.db.query("UPDATE trace_share SET revoked_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE run_id = ?1 AND revoked_at IS NULL").run(runId);
59 return ok(done.changes);
60 }
61
62 /** How many live links the run has, for its owner; undefined for anyone else. */
63 export function liveShares(app: App, actor: User | undefined, repo: Repo, runId: string): number | undefined {
64 if (ownerOf(app, actor, repo, runId) !== undefined) return undefined;
65 return app.db.query<{ n: number }, [string]>("SELECT count(*) AS n FROM trace_share WHERE run_id = ?1 AND revoked_at IS NULL").get(runId)!.n;
66 }
67
68 /** The trace a live link opens, redacted; undefined for an unknown, malformed or revoked token. */
69 export async function readShared(app: App, token: string): Promise<SharedTrace | undefined> {
70 if (!SHARE_TOKEN.test(token)) return undefined;
71 const row = app.db.query<{ run_id: string }, [string]>("SELECT run_id FROM trace_share WHERE token_hash = ?1 AND revoked_at IS NULL").get(sha256(token));
72 const run = row === null ? undefined : getRun(app.db, row.run_id);
73 if (run === undefined) return undefined;
74 const repo = getRepoById(app.db, run.repoId);
75 if (repo === undefined) return undefined;
76 await restoreRunLog(app.db, app.config.dataDir, run.id);
77 const { lines: raw, truncated } = readRunLog(app.config.dataDir, run.id);
78 const lines = raw.map(redactHeld);
79 const issue = run.issueId === null ? undefined : getIssueById(app.db, run.issueId);
80 const title = redactHeld(issue?.title ?? (run.summary === "" ? `${run.kind} run` : run.summary));
81 const { trace, spans, timed } = parseRunLog(run.id, title, lines, readRunTimes(app.config.dataDir, run.id, lines.length));
82 const steps = stepsOf(trace).map((step, i) => ({ step, lines: lines.slice(spans[i]!.from, spans[i]!.to) }));
83 return { title, timed, truncated, steps };
84 }
src/tui/screens/trace.ts +28 −2
@@ -6,6 +6,7 @@
66
77 import type { Repo } from "../../core/repos.ts";
88 import { readTrace, traceHref, traceRows } from "../../trace/read.ts";
9 import { createShare, liveShares, revokeShares, shareHref } from "../../trace/share.ts";
910 import type { Ctx, Screen } from "../app/app.ts";
1011 import { binding } from "../app/keys.ts";
1112 import type { Session } from "../session.ts";
@@ -17,14 +18,26 @@ import { Scroll, openOnWeb } from "./common.ts";
1718 export function traceScreen(f: Session, ctx: Ctx, repo: Repo, runId: string): Screen {
1819 const scroll = new Scroll();
1920 let rows: string[] | undefined;
21 let base: string[] | undefined;
2022 let loaded = false;
23 /** What sharing last said: a link is shown here once, as on the page. */
24 let said: string | undefined;
25 const shareRows = (): string[] => {
26 const live = liveShares(f.app, f.user, repo, runId);
27 if (live === undefined) return [];
28 return [
29 "",
30 said ?? (live === 0 ? "Sharing is off. s makes a link." : `${live} link${live === 1 ? " is" : "s are"} live. s makes another, x revokes them.`),
31 ];
32 };
2133 return {
2234 title: "Trace",
2335 here: () => ({ repo, run: runId }),
24 keys: [binding(["j", "k"], "scroll"), binding(["pgup", "pgdn"], "page"), binding(["o"], "open on the web")],
36 keys: [binding(["j", "k"], "scroll"), binding(["pgup", "pgdn"], "page"), binding(["s"], "share link"), binding(["x"], "revoke links"), binding(["o"], "open on the web")],
2537 async load() {
2638 const view = await readTrace(f.app, f.user, repo, runId);
27 rows = view === undefined ? undefined : traceRows(view);
39 base = view === undefined ? undefined : traceRows(view);
40 rows = base === undefined ? undefined : [...base, ...shareRows()];
2841 loaded = true;
2942 ctx.invalidate();
3043 },
@@ -47,6 +60,19 @@ export function traceScreen(f: Session, ctx: Ctx, repo: Repo, runId: string): Sc
4760 return true;
4861 }
4962 if (rows === undefined) return false;
63 if ((e.key === "s" || e.key === "x") && !e.ctrl && !e.alt) {
64 if (e.key === "s") {
65 const made = createShare(f.app, f.user, repo, runId);
66 said = made.ok ? `Link, shown once: ${f.app.config.url}${shareHref(made.value.token)}` : "Only the trace's owner shares it.";
67 } else {
68 const done = revokeShares(f.app, f.user, repo, runId);
69 said = !done.ok ? "Only the trace's owner shares it." : done.value === 0 ? "There was no link to revoke." : "Every link is revoked.";
70 }
71 rows = [...(base ?? []), ...shareRows()];
72 if (said !== undefined && !rows.includes(said)) rows.push(said);
73 ctx.invalidate();
74 return true;
75 }
5076 const took = scroll.key(e, rows.length);
5177 if (took) ctx.invalidate();
5278 return took;
src/web/pages/trace.ts +78 −2
@@ -17,6 +17,11 @@ import { crumbsFor, notFoundPage, pageHead, repoPalette } from "../chrome.ts";
1717 import { html, type Html } from "../html.ts";
1818 import { page } from "../layout.ts";
1919 import { behaviorsJs } from "../behaviors.ts";
20 import { btn } from "../ui.ts";
21 import { readForm } from "../form.ts";
22 import { flashTo } from "../layout.ts";
23 import { createShare, liveShares, revokeShares, shareHref, SHARE_TOKEN, readShared, type ShareError, type SharedTrace } from "../../trace/share.ts";
24 import { signInFirst } from "../chrome.ts";
2025
2126 /** A trace with this many steps or fewer opens its branches; a longer one opens none. */
2227 export const OPEN_BELOW = 100;
@@ -92,7 +97,19 @@ function strip(steps: readonly Step[], timed: boolean): Html {
9297 return html`<svg class="trace-strip" viewBox="0 0 1000 28" preserveAspectRatio="none" role="group" aria-label="${timed ? `Steps over ${spanWords(whole)}` : "Steps in order"}">${out}</svg>`;
9398 }
9499
95 function body(view: TraceView): Html {
100 /** The owner's share controls (#18084); `token` is the link just made, shown this once. */
101 function shareBlock(runId: string, live: number, token: string | undefined, origin: string): Html {
102 const base = traceHref(runId);
103 return html`<section id="trace-share" aria-label="Share link">
104 <h2>Share</h2>
105 ${token === undefined ? null : html`<p id="trace-share-token"><strong>Link, shown once:</strong> <code class="mono">${origin}${shareHref(token)}</code></p>`}
106 <p class="small muted">${live === 0 ? "Sharing is off." : `${String(live)} link${live === 1 ? " is" : "s are"} live.`} Anyone with a link reads this trace without an account, secrets masked.</p>
107 <form method="post" action="${base}/share" class="bar">${btn("Make a link", { size: "sm" })}</form>
108 ${live === 0 ? null : html`<form method="post" action="${base}/unshare" class="bar">${btn("Revoke every link", { size: "sm", variant: "danger" })}</form>`}
109 </section>`;
110 }
111
112 function body(view: TraceView, share: Html | null = null): Html {
96113 const steps = stepsInView(view);
97114 const total = steps.length;
98115 const base = traceHref(view.run.id);
@@ -119,6 +136,7 @@ function body(view: TraceView): Html {
119136 <nav class="bar small" id="trace-links" aria-label="Where this run went">${view.links.map((l) => html`<a href="${l.href}">${l.label}</a>`)}<a href="/traces">All traces</a></nav>
120137 ${changed === undefined ? null : html`<p id="trace-changed"><strong>What it changed:</strong> ${changed}. <a href="${view.links.find((l) => l.label.startsWith("Pull"))?.href ?? "#"}">Read the diff on the pull</a>.</p>`}
121138 ${view.truncated ? html`<p class="small muted" id="trace-cut">The start of the log was cut, so steps count from the cut.</p>` : null}
139 ${share}
122140 ${total === 0 ? html`<p class="muted" id="trace-empty">This run wrote no steps.</p>` : html`${strip(steps, timed)}
123141 <div class="trace-tree" id="trace-tree" data-base="${base}" role="group" aria-label="Steps">${rows}</div>
124142 ${timed ? null : html`<p class="small muted" id="trace-untimed">This run's log kept no times, so steps show none; it holds no tokens or cost per step.</p>`}`}`;
@@ -135,21 +153,79 @@ function repoOfRun(ctx: Ctx): { repo: Repo; id: string } | undefined {
135153 // GET /traces/:id
136154 export async function tracePage(ctx: Ctx): Promise<Response> {
137155 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
156 return traceAnswer(ctx);
157 }
158
159 async function traceAnswer(ctx: Ctx, token?: string): Promise<Response> {
138160 const found = repoOfRun(ctx);
139161 if (found === undefined) return notFoundPage(ctx);
140162 const view = await readTrace(ctx.app, ctx.auth.user, found.repo, found.id);
141163 if (view === undefined) return notFoundPage(ctx);
164 const live = liveShares(ctx.app, ctx.auth.user, found.repo, found.id);
142165 return page({
143166 ctx,
144167 title: `Trace · ${view.title}`,
145168 crumbs: crumbsFor(found.repo),
146169 palette: repoPalette(ctx, found.repo),
147 body: body(view),
170 body: body(view, live === undefined ? null : shareBlock(found.id, live, token, ctx.url.origin)),
148171 styleCss: TRACE_CSS,
149172 scriptJs: `${behaviorsJs}\n${TRACE_JS}`,
150173 });
151174 }
152175
176 const refused = (ctx: Ctx, why: ShareError): Response =>
177 why === "owner_only" ? new Response("only the trace's owner shares it", { status: 403, headers: { "cache-control": "no-store" } }) : notFoundPage(ctx);
178
179 /** The form door both owner acts share: signed in, same-origin, a run the viewer may read. */
180 async function ownerAct(ctx: Ctx, act: (found: { repo: Repo; id: string }) => Promise<Response> | Response): Promise<Response> {
181 if (!ctx.auth.user) return signInFirst(ctx);
182 const form = await readForm(ctx, "rw");
183 if (form instanceof Response) return form;
184 const found = repoOfRun(ctx);
185 return found === undefined ? notFoundPage(ctx) : act(found);
186 }
187
188 // POST /traces/:id/share — the owner makes a link; the answer is the trace page showing it once.
189 export const traceShare = (ctx: Ctx): Promise<Response> =>
190 ownerAct(ctx, async (found) => {
191 const made = createShare(ctx.app, ctx.auth.user, found.repo, found.id);
192 if (!made.ok) return refused(ctx, made.error);
193 const res = await traceAnswer(ctx, made.value.token);
194 res.headers.set("cache-control", "private, no-store");
195 return res;
196 });
197
198 // POST /traces/:id/unshare — the owner takes every link back.
199 export const traceUnshare = (ctx: Ctx): Promise<Response> =>
200 ownerAct(ctx, (found) => {
201 const done = revokeShares(ctx.app, ctx.auth.user, found.repo, found.id);
202 if (!done.ok) return refused(ctx, done.error);
203 return flashTo(ctx, traceHref(found.id), { message: done.value === 0 ? "There was no link to revoke." : "Every link is revoked." });
204 });
205
206 function sharedBody(t: SharedTrace): Html {
207 const total = t.steps.length;
208 return html`${pageHead(html`Trace: ${t.title}`, { sub: "A crew run, step by step. Shared read-only; secrets are masked." })}
209 ${t.truncated ? html`<p class="small muted">The start of the log was cut, so steps count from the cut.</p>` : null}
210 ${total === 0 ? html`<p class="muted">This run wrote no steps.</p>` : html`<div id="shared-steps">${t.steps.map(({ step, lines }, i) => html`<details class="trace-step trace-${step.kind}${step.outcome === "error" ? " trace-bad" : ""}" id="${step.id}">
211 <summary><span class="trace-n mono">${String(i + 1)}/${String(total)}</span>${step.outcome === "error" ? "✗ " : ""}${step.line}</summary>
212 <pre class="trace-raw mono">${lines.join("\n")}</pre>
213 </details>`)}</div>`}`;
214 }
215
216 // GET /t/:token — a shared trace, for anyone holding a live link; revoked, unknown or malformed
217 // is 404.
218 export async function sharedPage(ctx: Ctx): Promise<Response> {
219 const token = ctx.params.token ?? "";
220 const shared = SHARE_TOKEN.test(token) ? await readShared(ctx.app, token) : undefined;
221 if (shared === undefined) return notFoundPage(ctx, { noEcho: true, signedOut: true });
222 const res = page({ ctx, title: `Trace · ${shared.title}`, body: sharedBody(shared), styleCss: TRACE_CSS });
223 res.headers.set("cache-control", "private, no-store");
224 res.headers.set("referrer-policy", "no-referrer");
225 res.headers.set("x-robots-tag", "noindex, nofollow");
226 return res;
227 }
228
153229 // GET /traces/:id/steps/:n — the raw lines of one step, as text, read when a step is opened.
154230 export async function traceStep(ctx: Ctx): Promise<Response> {
155231 const found = repoOfRun(ctx);
test/trace-share.test.ts added +106
@@ -0,0 +1,106 @@
1 /** A trace's share link (#18084): off by default, the owner's alone, redacted, revocable. */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { appendFileSync } from "node:fs";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { createRepo } from "../src/actions/repos.ts";
9 import type { Repo } from "../src/core/repos.ts";
10 import { createRun, finishRun } from "../src/core/runs.ts";
11 import { createToken } from "../src/core/tokens.ts";
12 import { createUser, type User } from "../src/core/users.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14 import { appendRunLog, flushRunLogs, runLogPath } from "../src/runs/log.ts";
15 import { createShare, liveShares, readShared, revokeShares } from "../src/trace/share.ts";
16 import { seedAdmin } from "./helpers/admin.ts";
17
18 let dir = "";
19 let app: App, servers: Servers, runId = "", asAlice = "", asBob = "";
20 let alice: User, bob: User;
21 let repo: Repo;
22 const PLANTED = "ghp_abcdefghijklmnopqrstuvwxyz0123456789";
23
24 const post = (path: string, bearer: string, headers: Record<string, string> = {}) =>
25 fetch(`${servers.url}${path}`, { method: "POST", headers: { authorization: `Bearer ${bearer}`, ...headers }, redirect: "manual" });
26
27 beforeAll(async () => {
28 dir = await mkdtemp(join(tmpdir(), "forge-trace-share-"));
29 app = createApp({ dataDir: dir, port: 0 });
30 servers = await serve(app);
31 const admin = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
32 if (!admin.ok) throw new Error(admin.error);
33 alice = admin.value;
34 const made = await createRepo(app, alice, { name: "notes", visibility: "public", description: "" });
35 if (!made.ok) throw new Error(String(made.error));
36 repo = made.value;
37 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bobby", email: "[email protected]", password: "correct-horse-battery" });
38 if (!b.ok) throw new Error(b.error);
39 bob = b.value;
40 asAlice = createToken(app.db, alice.id, "t", "rw").token;
41 asBob = createToken(app.db, bob.id, "t", "rw").token;
42 const run = createRun(app.db, { repoId: repo.id, kind: "agent" });
43 runId = run.id;
44 // Written straight, as a log from before the value was masked at the door.
45 appendRunLog(dir, runId, "I will read the config.");
46 flushRunLogs();
47 appendFileSync(runLogPath(dir, runId), `→ Bash echo ${PLANTED}\nDone.\n`);
48 finishRun(app.db, runId, { state: "ok", summary: "read config" });
49 }, 30_000);
50
51 afterAll(async () => {
52 servers.stop();
53 app.close();
54 await rm(dir, { recursive: true, force: true });
55 });
56
57 test("sharing is off until the owner makes a link, and a non-owner cannot", async () => {
58 expect(liveShares(app, alice, repo, runId)).toBe(0);
59 expect(liveShares(app, bob, repo, runId)).toBeUndefined();
60 const refused = createShare(app, bob, repo, runId);
61 expect(refused.ok).toBe(false);
62 expect(createShare(app, undefined, repo, runId).ok).toBe(false);
63 expect((await post(`/traces/${runId}/share`, asBob)).status).toBe(404);
64 expect(liveShares(app, alice, repo, runId)).toBe(0);
65 });
66
67 test("a link serves the trace with a planted token redacted, shows once, keeps only a hash, then revoke makes it 404", async () => {
68 const res = await post(`/traces/${runId}/share`, asAlice);
69 expect(res.status).toBe(200);
70 const text = await res.text();
71 const token = /tr_[A-Za-z0-9_-]{43}/.exec(text)?.[0];
72 expect(token).toBeDefined();
73 expect(text).toContain("Link, shown once");
74 // The page afterwards does not show it again, and the table holds no raw token.
75 expect(await (await fetch(`${servers.url}/traces/${runId}`, { headers: { authorization: `Bearer ${asAlice}` } })).text()).not.toContain(token!);
76 expect(JSON.stringify(app.db.query("SELECT * FROM trace_share").all())).not.toContain(token!);
77
78 const shared = await fetch(`${servers.url}/t/${token}`);
79 expect(shared.status).toBe(200);
80 const body = await shared.text();
81 expect(body).toContain("read the config");
82 expect(body).toContain("[redacted]");
83 expect(body).not.toContain(PLANTED);
84 expect(shared.headers.get("referrer-policy")).toBe("no-referrer");
85 expect(shared.headers.get("cache-control")).toBe("private, no-store");
86 expect(JSON.stringify(await readShared(app, token!))).not.toContain(PLANTED);
87
88 // A non-owner cannot revoke; a cross-origin revoke is refused; the owner's revoke takes it back.
89 expect((await post(`/traces/${runId}/unshare`, asBob)).status).toBe(404);
90 expect((await post(`/traces/${runId}/unshare`, asAlice, { origin: "https://evil.example" })).status).toBe(403);
91 expect((await fetch(`${servers.url}/t/${token}`)).status).toBe(200);
92 expect((await post(`/traces/${runId}/unshare`, asAlice)).status).toBe(303);
93 expect((await fetch(`${servers.url}/t/${token}`)).status).toBe(404);
94 expect(liveShares(app, alice, repo, runId)).toBe(0);
95 });
96
97 test("a cross-origin make is refused, and an unknown or malformed token is 404", async () => {
98 expect((await post(`/traces/${runId}/share`, asAlice, { origin: "https://evil.example" })).status).toBe(403);
99 expect(liveShares(app, alice, repo, runId)).toBe(0);
100 expect((await fetch(`${servers.url}/t/tr_${"a".repeat(43)}`)).status).toBe(404);
101 expect((await fetch(`${servers.url}/t/nope`)).status).toBe(404);
102 const made = createShare(app, alice, repo, runId);
103 expect(made.ok && (await readShared(app, made.value.token)) !== undefined).toBe(true);
104 expect(revokeShares(app, bob, repo, runId).ok).toBe(false);
105 expect(revokeShares(app, alice, repo, runId)).toEqual({ ok: true, value: 1 });
106 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs