Public: anyone can read this; the crew can change it.
A browser tab takes runs through the same versioned protocol and stops when it closes #18534
Merged 24m ago, goes live with the next release
mason/forge:mason/18526-a-browser-tab-takes-runs-through-the-sam → main 0 commits fork 4 threads · 4 unresolved
19 files
changed +466
−18
- docs/features/runners.md
- docs/features/settings-runners.md
- src/actions/environments.ts
- src/actions/runners.ts
- src/checks/runner_jobs.ts
- src/core/migration-pins/20261206180000-tab-runner.pin
- src/core/migrations/20261206180000-tab-runner.ts
- src/http/lazy_lists.ts
- src/http/marks/settings.json
- src/http/settings_routes.ts
- src/machines/live_runners.ts
- src/machines/tab_runner.ts
- src/machines/tab_safe.ts
- src/tui/screens/runners.ts
- src/web/pages/runners.ts
- src/web/style/components.ts
- src/web/tab_runner_client.ts
- test/no-polling.test.ts
- test/tab-runner.test.ts
docs/features/runners.md +8
| @@ -205,3 +205,11 @@ A runner may answer a held job `{ "interrupted": "<why>" }` (a game box does whe | ||
| 205 | 205 | ## Pausing a runner (#18038) |
| 206 | 206 | |
| 207 | 207 | An admin holds a runner without revoking it: `POST /api/v1/admin/runners/:id/pause` (beside `…/resume` and `…/revoke`), or `p` on its row in the terminal's Runners screen. Its claims are refused and a job it holds finishes; its `paused` text reads `paused by <admin>`, and `runner.paused` is written. The forge's own `local-N` runner, a revoked one and one already paused answer 422 (`local`, `revoked`, `paused`). Resume undoes it. |
| 208 | ||
| 209 | ## A browser tab as a runner (#18526) | |
| 210 | ||
| 211 | An admin's Settings → Runners page offers **Use this tab as a runner**. The page asks `POST /settings/runners/tab` (same origin, admin) for a runner token, keeps it in a script variable only (no storage, no cookie), and speaks the one agent protocol (`/api/v1/agent/v1/…`: a heartbeat every 10 seconds, a claim held open, logs, a result) with the ordinary `runner` role. The tab is a row of kind `tab` on the runners page and in the terminal's Runners screen ("a browser tab"), and it is gone within 30 seconds of the last heartbeat: a token whose last request is older than `TAB_TTL_MS` is refused (401) at once, and its row is deleted at the next listing (the terminal's Runners screen lists through the same `list`, so it shows the same). A job it held is queued again. Without scripts the page says a tab runner needs them. At most 8 tabs are open at once (409 past that). Pressing the button again stops it. | |
| 212 | ||
| 213 | A tab is never trusted and runs nothing of a pull's. It claims only a job the forge marked tab-safe (`check_job.tab_safe`, set by `isTabSafe` in `src/machines/tab_safe.ts`): every step is the one verb a tab knows, `forge-tab echo <text>`, which the tab prints and reports green; no cell, no label, no files handed back, no environment and no variables in the job's `env`, no seeds, a public repository. Anything it says of itself (`cells: true`, a machine) is ignored or only narrows its claim (a heartbeat `paused` makes it claim nothing). A job with any other step is handed back. Nothing marks a real check tab-safe yet; the verb list is the place a later change widens what a tab may do. | |
| 214 | ||
| 215 | Code: `src/machines/tab_runner.ts`, `src/machines/tab_safe.ts`, `src/web/tab_runner_client.ts`. Test: `test/tab-runner.test.ts`. |
docs/features/settings-runners.md +2
| @@ -42,3 +42,5 @@ word of any machine. With no runner the page says what a runner is and how to ad | ||
| 42 | 42 | each row says busy or idle and the run it holds; `j`/`k` move, `x` removes the hand-made runner under the cursor after a confirm. Both go through |
| 43 | 43 | `removeHandMade` in `src/actions/runners.ts`. Anyone else gets the plain 404 on the web and is |
| 44 | 44 | not offered the screen. |
| 45 | ||
| 46 | **This tab** (#18526): a button, **Use this tab as a runner**, makes the open page a runner of kind tab while it stays open: [](runners.md#a-browser-tab-as-a-runner-18526). The terminal lists such a runner as "a browser tab" but cannot be one. |
src/actions/environments.ts +2 −1
| @@ -32,7 +32,8 @@ export function removeEnvironmentEntry(app: App, actor: User | undefined, repo: | ||
| 32 | 32 | |
| 33 | 33 | export function setRunnerTrust(app: App, actor: User | undefined, runnerId: string, trusted: boolean): Result<{ id: string; name: string; trusted: boolean }, "not_found" | "local"> { |
| 34 | 34 | const runner = getRunner(app.db, runnerId); |
| 35 | if (actor === undefined || !actor.isAdmin || runner === undefined) return err("not_found"); | |
| 35 | // A browser tab is never trusted (#18526): it is not a machine this forge's admin can vouch for. | |
| 36 | if (actor === undefined || !actor.isAdmin || runner === undefined || runner.kind === "tab") return err("not_found"); | |
| 36 | 37 | // The forge's own `local-N` runners hold the forge's data already; trust is for machines it does |
| 37 | 38 | // not own. |
| 38 | 39 | if (runner.name.startsWith("local-")) return err("local"); |
src/actions/runners.ts +21 −3
| @@ -31,6 +31,9 @@ import { isLocal } from "../checks/runner_pool.ts"; | ||
| 31 | 31 | import { getRepo } from "../core/repos.ts"; |
| 32 | 32 | import type { User } from "../core/users.ts"; |
| 33 | 33 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 34 | import { enrolTab, reapTabs } from "../machines/tab_runner.ts"; | |
| 35 | import { TAB_TTL_MS } from "../machines/tab_safe.ts"; | |
| 36 | import { tellRunners } from "../machines/runner_signal.ts"; | |
| 34 | 37 | |
| 35 | 38 | const admin = (actor: User | undefined): actor is User => |
| 36 | 39 | actor !== undefined && actor.isAdmin && actor.kind === "user"; |
| @@ -123,6 +126,18 @@ export function pause(app: App, actor: User | undefined, runnerId: string, reaso | ||
| 123 | 126 | return ok({ ...runner, paused: why }); |
| 124 | 127 | } |
| 125 | 128 | |
| 129 | /** | |
| 130 | * An admin's open page enrols its tab as a runner of kind `tab` (#18526). The token is returned | |
| 131 | * once, to be held in the page's memory; `full` when `TAB_MAX` tabs are open already. | |
| 132 | */ | |
| 133 | export function enrolThisTab(app: App, actor: User | undefined): Result<{ runner: Enrolled; token: string }, "not_found" | "full"> { | |
| 134 | if (!admin(actor)) return err("not_found"); | |
| 135 | const made = enrolTab(app.db, actor.id, Date.now()); | |
| 136 | if (made === undefined) return err("full"); | |
| 137 | app.bus.append({ kind: "runner.enrolled", actorId: actor.id, payload: { id: made.runner.id, name: made.runner.name, kind: "tab" } }); | |
| 138 | return ok(made); | |
| 139 | } | |
| 140 | ||
| 126 | 141 | /** The forge pauses a lent runner whose answer it caught out; the event is the record. */ |
| 127 | 142 | function pauseLent(app: App, runnerId: string, why: string): void { |
| 128 | 143 | if (!pauseRunner(app.db, runnerId, why)) return; |
| @@ -189,7 +204,10 @@ export function list( | ||
| 189 | 204 | app: App, |
| 190 | 205 | actor: User | undefined, |
| 191 | 206 | ): Result<Enrolled[], "not_found"> { |
| 192 | return admin(actor) ? ok(listRunners(app.db)) : err("not_found"); | |
| 207 | if (!admin(actor)) return err("not_found"); | |
| 208 | // A tab whose heartbeat was missed is gone from the list, and an open page is told. | |
| 209 | if (reapTabs(app.db, Date.now()) > 0) tellRunners(app, "released"); | |
| 210 | return ok(listRunners(app.db)); | |
| 193 | 211 | } |
| 194 | 212 | |
| 195 | 213 | export function remove( |
| @@ -217,9 +235,9 @@ function enrolled(app: App, actor: User | undefined, runnerId: string): Enrolled | ||
| 217 | 235 | } |
| 218 | 236 | |
| 219 | 237 | /** A runner's state from when it last asked for work. */ |
| 220 | export function runnerState(seenAt: number, now: number): "connected" | "quiet" | "never" { | |
| 238 | export function runnerState(seenAt: number, now: number, kind: "machine" | "tab" = "machine"): "connected" | "quiet" | "never" { | |
| 221 | 239 | if (seenAt === 0) return "never"; |
| 222 | return now - seenAt <= SEEN_FRESH_MS ? "connected" : "quiet"; | |
| 240 | return now - seenAt <= (kind === "tab" ? TAB_TTL_MS : SEEN_FRESH_MS) ? "connected" : "quiet"; | |
| 223 | 241 | } |
| 224 | 242 | |
| 225 | 243 | /** |
src/checks/runner_jobs.ts +29 −4
| @@ -24,6 +24,7 @@ import { boxAuthors, boxSpareMiB } from "../games/lend_fit.ts"; | ||
| 24 | 24 | import { startProof } from "../games/lent_proof.ts"; |
| 25 | 25 | import { id, secret } from "../kernel/id.ts"; |
| 26 | 26 | import { background } from "../perf/jobs.ts"; |
| 27 | import { TAB_TTL_MS, isTabSafe } from "../machines/tab_safe.ts"; | |
| 27 | 28 | import { DONE_ENV, keepDone } from "./shard_event.ts"; |
| 28 | 29 | import { canaryCommand, canaryDue, coreMs, lentName, outOfScope, readScope, scopeFrom, utcDay, type LendInput, type LentScope } from "./lent_scope.ts"; |
| 29 | 30 | |
| @@ -165,6 +166,11 @@ export interface Enrolled { | ||
| 165 | 166 | readonly state: string; |
| 166 | 167 | /** Whether a site admin marked it trusted for secrets (`environment.ts`). */ |
| 167 | 168 | readonly trusted: boolean; |
| 169 | /** | |
| 170 | * `tab` for a browser tab that enrolled itself (`machines/tab_runner.ts`); `machine` for any | |
| 171 | * other. | |
| 172 | */ | |
| 173 | readonly kind: "machine" | "tab"; | |
| 168 | 174 | /** Set by `runnerByToken` alone: this request is the first within `SEEN_FRESH_MS` (#18458). */ |
| 169 | 175 | readonly wasQuiet?: true; |
| 170 | 176 | } |
| @@ -188,8 +194,9 @@ type RunnerRow = { | ||
| 188 | 194 | repos: string; |
| 189 | 195 | state: string; |
| 190 | 196 | trusted_at: number; |
| 197 | kind: string; | |
| 191 | 198 | }; |
| 192 | const RUNNER_COLUMNS = "id, name, created_at, seen_at, scope, core_ms, day, day_core_ms, paused, revoked_at, jobs, cpus, memory_mib, host_cpus, labels, repos, state, trusted_at"; | |
| 199 | const RUNNER_COLUMNS = "id, name, created_at, seen_at, scope, core_ms, day, day_core_ms, paused, revoked_at, jobs, cpus, memory_mib, host_cpus, labels, repos, state, trusted_at, kind"; | |
| 193 | 200 | |
| 194 | 201 | /** A JSON array of strings as kept in a column; anything else is none. */ |
| 195 | 202 | const stringList = (raw: string): string[] => { |
| @@ -220,6 +227,7 @@ const toEnrolled = (r: RunnerRow, now: number = Date.now()): Enrolled => { | ||
| 220 | 227 | repos: stringList(r.repos), |
| 221 | 228 | state: r.state, |
| 222 | 229 | trusted: r.trusted_at > 0, |
| 230 | kind: r.kind === "tab" ? "tab" : "machine", | |
| 223 | 231 | }; |
| 224 | 232 | }; |
| 225 | 233 | |
| @@ -412,6 +420,9 @@ export function runnerByToken( | ||
| 412 | 420 | .query<RunnerRow, [string]>(`SELECT ${RUNNER_COLUMNS} FROM check_runner WHERE token_hash = ?1`) |
| 413 | 421 | .get(sha256(presented)); |
| 414 | 422 | if (row === null) return undefined; |
| 423 | // A tab's token lives only while its heartbeats do (`machines/tab_runner.ts`): past that it is | |
| 424 | // refused, and its row is swept at the next listing. | |
| 425 | if (row.kind === "tab" && (row.seen_at > now || now - row.seen_at > TAB_TTL_MS)) return undefined; | |
| 415 | 426 | // One write is a commit: a runner polling every few seconds is noted at most once per |
| 416 | 427 | // `SEEN_WRITE_MS`, which is well inside `SEEN_FRESH_MS`. |
| 417 | 428 | if (now - row.seen_at < SEEN_WRITE_MS && row.seen_at <= now) return toEnrolled(row, now); |
| @@ -496,7 +507,7 @@ export function offerJob( | ||
| 496 | 507 | ): RunnerJob { |
| 497 | 508 | const job: RunnerJob = { ...input.job, id: id() }; |
| 498 | 509 | db.query( |
| 499 | "INSERT INTO check_job (id, run_id, repo_id, dir, spec, needs_cell, author, label) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", | |
| 510 | "INSERT INTO check_job (id, run_id, repo_id, dir, spec, needs_cell, author, label, tab_safe) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", | |
| 500 | 511 | ).run( |
| 501 | 512 | job.id, |
| 502 | 513 | input.runId, |
| @@ -506,6 +517,7 @@ export function offerJob( | ||
| 506 | 517 | job.cell === "required" ? 1 : 0, |
| 507 | 518 | (input.author ?? "").toLowerCase(), |
| 508 | 519 | job.label ?? "", |
| 520 | isTabSafe(job) ? 1 : 0, | |
| 509 | 521 | ); |
| 510 | 522 | return job; |
| 511 | 523 | } |
| @@ -535,6 +547,7 @@ type ClaimRow = { | ||
| 535 | 547 | labels: string; |
| 536 | 548 | repos: string; |
| 537 | 549 | state: string; |
| 550 | kind: string; | |
| 538 | 551 | }; |
| 539 | 552 | |
| 540 | 553 | /** |
| @@ -549,7 +562,7 @@ export function claimJob( | ||
| 549 | 562 | ): Claim | undefined { |
| 550 | 563 | const me = db |
| 551 | 564 | .query<ClaimRow, [string]>( |
| 552 | "SELECT id, name, created_at, scope, day, day_core_ms, paused, revoked_at, salt, ran, canary_at, box_id, labels, repos, state FROM check_runner WHERE id = ?1", | |
| 565 | "SELECT id, name, created_at, scope, day, day_core_ms, paused, revoked_at, salt, ran, canary_at, box_id, labels, repos, state, kind FROM check_runner WHERE id = ?1", | |
| 553 | 566 | ) |
| 554 | 567 | .get(runner.id); |
| 555 | 568 | // A runner that said `paused` in its heartbeat (a Mac on battery) takes nothing until it says |
| @@ -572,7 +585,19 @@ export function claimJob( | ||
| 572 | 585 | const repos = me.repos; |
| 573 | 586 | const spareMiB = me.box_id === "" ? -1 : boxSpareMiB(db, me.box_id, now); |
| 574 | 587 | const queued = |
| 575 | scope === undefined | |
| 588 | me.kind === "tab" | |
| 589 | ? // A tab takes only a job the forge marked tab-safe, of a public repository, and never a canary | |
| 590 | // or one that hands files back: what it says of itself (`cells`) is not read here. | |
| 591 | db | |
| 592 | .query<{ id: string }, []>( | |
| 593 | `SELECT j.id FROM check_job j JOIN repo r ON r.id = j.repo_id | |
| 594 | WHERE j.state = 'queued' AND j.tab_safe = 1 AND j.needs_cell = 0 AND j.canary_for IS NULL AND j.label = '' | |
| 595 | AND r.visibility = 'public' AND json_extract(j.spec, '$.hands') IS NULL | |
| 596 | AND NOT EXISTS (SELECT 1 FROM json_each(j.spec, '$.env')) | |
| 597 | ORDER BY j.id LIMIT 8`, | |
| 598 | ) | |
| 599 | .all() | |
| 600 | : scope === undefined | |
| 576 | 601 | ? db |
| 577 | 602 | .query<{ id: string }, [number, string, string]>( |
| 578 | 603 | `SELECT id FROM check_job WHERE state = 'queued' AND canary_for IS NULL AND (needs_cell = 0 OR ?1 = 1) |
src/core/migration-pins/20261206180000-tab-runner.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | a09a5265a3be1b847e50c9bbd24d2fff9af86cacfdb624db9504a0e760cf10f2 |
src/core/migrations/20261206180000-tab-runner.ts added +8
| @@ -0,0 +1,8 @@ | ||
| 1 | // A browser tab that takes runs as a runner (#18526): `check_runner.kind` is `machine` for every | |
| 2 | // runner enrolled before and `tab` for one a signed-in admin's open page enrolled; a tab's row | |
| 3 | // lives while its heartbeats do (`machines/tab_runner.ts`). `check_job.tab_safe` is 1 for a job the | |
| 4 | // forge marked a tab may take (`machines/tab_safe.ts`). Additive: two columns with defaults. | |
| 5 | export default ` | |
| 6 | ALTER TABLE check_runner ADD COLUMN kind TEXT NOT NULL DEFAULT 'machine'; | |
| 7 | ALTER TABLE check_job ADD COLUMN tab_safe INTEGER NOT NULL DEFAULT 0; | |
| 8 | `; |
src/http/lazy_lists.ts +1
| @@ -35,6 +35,7 @@ export const SETTINGS_ROUTES = [ | ||
| 35 | 35 | ["POST", "/settings/runners/:id/trust"], |
| 36 | 36 | ["POST", "/settings/runners/:id/untrust"], |
| 37 | 37 | ["POST", "/settings/runners/register"], |
| 38 | ["POST", "/settings/runners/tab"], | |
| 38 | 39 | ["GET", "/settings/runners/lending/live"], |
| 39 | 40 | ["POST", "/settings/runners/lending"], |
| 40 | 41 | ["POST", "/settings/runners/lending/:id/stop"], |
src/http/marks/settings.json +1
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | "/settings/runners/:id/resume": "open", |
| 16 | 16 | "/settings/runners/:id/pause": "open", |
| 17 | 17 | "/settings/runners/register": "open", |
| 18 | "/settings/runners/tab": "open", | |
| 18 | 19 | "/settings/runners/lending/live": "open", |
| 19 | 20 | "/settings/runners/lending": "open", |
| 20 | 21 | "/settings/runners/lending/:id/stop": "open", |
src/http/settings_routes.ts +2 −1
| @@ -26,7 +26,7 @@ import { paymentsCsv, paymentsPage } from "../web/pages/payments.ts"; | ||
| 26 | 26 | import { billingPage, billingChange, billingGrant, billingSetLinks, billingSetPortal, billingMakeCode, billingRevokeCode, stripeConnect, stripeDisconnect, stripeSecret, orderRetry } from "../web/pages/billing.ts"; |
| 27 | 27 | import { economicsPage, economicsSet } from "../web/pages/economics.ts"; |
| 28 | 28 | import { trustedAdd, trustedPage, trustedRemove, trustedRevert, trustedStop } from "../web/pages/trusted.ts"; |
| 29 | import { lendingLive, lendingOffer, lendingResume, lendingStop, lendingStopNow, runnerPause, runnerRegister, runnerRemove, runnerResume, runnerRevoke, runnerTrust, runnersLive, runnersPage } from "../web/pages/runners.ts"; | |
| 29 | import { lendingLive, lendingOffer, lendingResume, lendingStop, lendingStopNow, runnerPause, runnerRegister, runnerRemove, runnerResume, runnerRevoke, runnerTab, runnerTrust, runnersLive, runnersPage } from "../web/pages/runners.ts"; | |
| 30 | 30 | import { usagePage } from "../web/pages/usage.ts"; |
| 31 | 31 | import { spendPage } from "../web/pages/spend-tab.ts"; |
| 32 | 32 | import { securityControlsPage } from "../web/pages/security_controls.ts"; |
| @@ -183,6 +183,7 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea | ||
| 183 | 183 | router.add("POST", "/settings/runners/:id/trust", runnerTrust(true)); |
| 184 | 184 | router.add("POST", "/settings/runners/:id/untrust", runnerTrust(false)); |
| 185 | 185 | router.add("POST", "/settings/runners/register", runnerRegister); |
| 186 | router.add("POST", "/settings/runners/tab", runnerTab); | |
| 186 | 187 | router.add("GET", "/settings/runners/lending/live", lendingLive); |
| 187 | 188 | router.add("POST", "/settings/runners/lending", lendingOffer); |
| 188 | 189 | router.add("POST", "/settings/runners/lending/:id/stop", lendingStop); |
src/machines/live_runners.ts +6 −2
| @@ -16,6 +16,7 @@ import { list, runnerState } from "../actions/runners.ts"; | ||
| 16 | 16 | import { getRepoById, type Repo } from "../core/repos.ts"; |
| 17 | 17 | import type { User } from "../core/users.ts"; |
| 18 | 18 | import { readRunLogTail } from "../runs/log.ts"; |
| 19 | import { TAB_TTL_MS } from "./tab_safe.ts"; | |
| 19 | 20 | |
| 20 | 21 | /** How many lines of a run's log the first paint carries. */ |
| 21 | 22 | export const TAIL_LINES = 30; |
| @@ -34,6 +35,8 @@ export interface HeldRun { | ||
| 34 | 35 | export interface RunnerLine { |
| 35 | 36 | readonly id: string; |
| 36 | 37 | readonly name: string; |
| 38 | /** `tab` for a browser tab, `machine` for any other. */ | |
| 39 | readonly kind: "machine" | "tab"; | |
| 37 | 40 | /** Asked within `SEEN_FRESH_MS` and not revoked. */ |
| 38 | 41 | readonly connected: boolean; |
| 39 | 42 | /** Holds a claimed job, or said `busy` in its heartbeat. */ |
| @@ -85,12 +88,13 @@ export function runnerLines(app: App, viewer: User | undefined, now: number): Ru | ||
| 85 | 88 | const repos = new Map<string, Repo | undefined>(); |
| 86 | 89 | return seen.value.map((r) => { |
| 87 | 90 | const jobs = claimed.get(r.id) ?? []; |
| 88 | const standing = runnerState(r.seenAt, now); | |
| 91 | const standing = runnerState(r.seenAt, now, r.kind); | |
| 89 | 92 | const word = r.revokedAt !== 0 ? "revoked" : r.paused !== "" ? "paused" : standing; |
| 90 | 93 | const first = jobs[0]; |
| 91 | 94 | return { |
| 92 | 95 | id: r.id, |
| 93 | 96 | name: r.name, |
| 97 | kind: r.kind, | |
| 94 | 98 | connected: standing === "connected" && r.revokedAt === 0, |
| 95 | 99 | busy: jobs.length > 0 || r.state === "busy", |
| 96 | 100 | word, |
| @@ -106,6 +110,6 @@ export function runnerLines(app: App, viewer: User | undefined, now: number): Ru | ||
| 106 | 110 | * runner falls quiet (`SEEN_FRESH_MS` after it last asked), as an ISO time; "" when none will. |
| 107 | 111 | */ |
| 108 | 112 | export function nextQuiet(lines: readonly RunnerLine[], freshMs: number): string { |
| 109 | const due = lines.filter((l) => l.connected).map((l) => l.seenAt + freshMs); | |
| 113 | const due = lines.filter((l) => l.connected).map((l) => l.seenAt + (l.kind === "tab" ? TAB_TTL_MS : freshMs)); | |
| 110 | 114 | return due.length === 0 ? "" : new Date(Math.min(...due)).toISOString(); |
| 111 | 115 | } |
src/machines/tab_runner.ts added +36
| @@ -0,0 +1,36 @@ | ||
| 1 | /** | |
| 2 | * A browser tab as a runner (#18526): an admin's open Settings → Runners page asks for a token, and | |
| 3 | * the forge enrols the tab as a `check_runner` of kind `tab`. The token is the same runner token | |
| 4 | * the agent protocol already takes (`protocol.ts`, role runner), shown once to the page, which | |
| 5 | * keeps it in a variable and nowhere else. The row lives while the tab's requests do: a token whose | |
| 6 | * last request is older than `TAB_TTL_MS` is refused (`runner_jobs.ts` `runnerByToken`) and its row | |
| 7 | * is deleted at the next listing, so a closed tab is gone within half a minute. A tab is never | |
| 8 | * trusted for secrets and claims only what `tab_safe.ts` marks. | |
| 9 | */ | |
| 10 | import type { Database } from "bun:sqlite"; | |
| 11 | import { enrolRunner, removeRunner, type Enrolled } from "../checks/runner_jobs.ts"; | |
| 12 | import { secret } from "../kernel/id.ts"; | |
| 13 | import { TAB_MAX, TAB_TTL_MS } from "./tab_safe.ts"; | |
| 14 | ||
| 15 | /** | |
| 16 | * Delete every tab whose last request is past its time; how many went. A held job is queued again. | |
| 17 | */ | |
| 18 | export function reapTabs(db: Database, now: number): number { | |
| 19 | const gone = db | |
| 20 | .query<{ id: string }, [number, number]>("SELECT id FROM check_runner WHERE kind = 'tab' AND (seen_at < ?1 OR seen_at > ?2)") | |
| 21 | .all(now - TAB_TTL_MS, now); | |
| 22 | for (const t of gone) removeRunner(db, t.id); | |
| 23 | return gone.length; | |
| 24 | } | |
| 25 | ||
| 26 | /** | |
| 27 | * Enrol a tab: a runner of kind `tab`, seen now. `undefined` when `TAB_MAX` tabs are open already. | |
| 28 | */ | |
| 29 | export function enrolTab(db: Database, createdBy: string, now: number): { runner: Enrolled; token: string } | undefined { | |
| 30 | reapTabs(db, now); | |
| 31 | const open = db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM check_runner WHERE kind = 'tab'").get()?.n ?? 0; | |
| 32 | if (open >= TAB_MAX) return undefined; | |
| 33 | const made = enrolRunner(db, `tab-${secret().slice(0, 6).toLowerCase()}`, createdBy, undefined, now); | |
| 34 | db.query("UPDATE check_runner SET kind = 'tab', seen_at = ?2 WHERE id = ?1").run(made.runner.id, now); | |
| 35 | return { runner: { ...made.runner, kind: "tab", seenAt: now }, token: made.token }; | |
| 36 | } |
src/machines/tab_safe.ts added +50
| @@ -0,0 +1,50 @@ | ||
| 1 | /** | |
| 2 | * What a browser tab may take (#18526), as plain data. A tab is never trusted and runs nothing of a | |
| 3 | * pull's: a job is tab-safe only when the forge itself reads every step as one of the few verbs a | |
| 4 | * tab knows (`forge-tab echo <text>`), which are data a tab prints, not commands it runs. Anything | |
| 5 | * else (a shell command, a cell, a label, files handed back, an environment, any variable, seeds) | |
| 6 | * is a job for a machine. `readStep` is the one reading of a step, shared by the forge's marking | |
| 7 | * and the tab's own script, so the two cannot drift. | |
| 8 | */ | |
| 9 | ||
| 10 | /** A tab's token and its row live this long after its last request. */ | |
| 11 | export const TAB_TTL_MS = 30_000; | |
| 12 | /** The most tabs one forge holds at once. */ | |
| 13 | export const TAB_MAX = 8; | |
| 14 | /** How often the tab says it is here, and the longest a claim of its waits: well inside the TTL. */ | |
| 15 | export const TAB_BEAT_MS = 10_000; | |
| 16 | ||
| 17 | /** | |
| 18 | * The one verb's pattern, as source: the tab's script builds its own regular expression from it. | |
| 19 | */ | |
| 20 | export const STEP_PATTERN = "^forge-tab echo ([\\x20-\\x7e]{0,200})$"; | |
| 21 | const VERB = new RegExp(STEP_PATTERN); | |
| 22 | ||
| 23 | /** The text a step has the tab print; undefined for any step a tab does not know. */ | |
| 24 | export function readStep(command: string): string | undefined { | |
| 25 | return VERB.exec(command)?.[1]; | |
| 26 | } | |
| 27 | ||
| 28 | /** The part of a job that decides it, so this module imports nothing of `checks/`. */ | |
| 29 | export interface TabJobFacts { | |
| 30 | readonly steps: readonly { readonly command: string }[]; | |
| 31 | readonly cell: "required" | "preferred"; | |
| 32 | readonly label?: string; | |
| 33 | readonly hands?: readonly string[]; | |
| 34 | readonly seeds?: readonly unknown[]; | |
| 35 | readonly environment?: string; | |
| 36 | readonly env?: Readonly<Record<string, string>>; | |
| 37 | } | |
| 38 | ||
| 39 | export function isTabSafe(job: TabJobFacts): boolean { | |
| 40 | return ( | |
| 41 | job.steps.length > 0 && | |
| 42 | job.steps.every((s) => readStep(s.command) !== undefined) && | |
| 43 | job.cell !== "required" && | |
| 44 | (job.label ?? "") === "" && | |
| 45 | (job.hands === undefined || job.hands.length === 0) && | |
| 46 | (job.seeds === undefined || job.seeds.length === 0) && | |
| 47 | job.environment === undefined && | |
| 48 | (job.env === undefined || Object.keys(job.env).length === 0) | |
| 49 | ); | |
| 50 | } |
src/tui/screens/runners.ts +2 −2
| @@ -40,7 +40,7 @@ function lendingLine(f: Session): string { | ||
| 40 | 40 | const revocable = (r: Enrolled): boolean => (r.scope !== undefined || r.labels.length > 0) && r.revokedAt === 0; |
| 41 | 41 | |
| 42 | 42 | const stateWords = (r: Enrolled, now: number): string => |
| 43 | r.revokedAt !== 0 ? "revoked" : r.paused !== "" ? "paused" : STATE_WORDS[runnerState(r.seenAt, now)]; | |
| 43 | r.revokedAt !== 0 ? "revoked" : r.paused !== "" ? "paused" : STATE_WORDS[runnerState(r.seenAt, now, r.kind)]; | |
| 44 | 44 | |
| 45 | 45 | /** A row of the screen: a runner enrolled here, or an offer to lend runners to another forge. */ |
| 46 | 46 | type Entry = { readonly kind: "runner"; readonly r: Enrolled } | { readonly kind: "offer"; readonly o: LendView }; |
| @@ -85,7 +85,7 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen { | ||
| 85 | 85 | const busyWord = line === undefined || r.revokedAt !== 0 ? "" : line.busy ? " · busy" : line.connected ? " · idle" : ""; |
| 86 | 86 | const holds = line?.run === undefined ? "" : line.run.id === "" ? " · holds a run" : ` · holds run ${line.run.id.slice(0, 8)} of ${line.run.repo}`; |
| 87 | 87 | return { |
| 88 | title: `${r.name} ${stateWords(r, now)}${r.trusted ? " trusted for secrets" : ""}${isLocal(r) ? " (the forge's own)" : ""}`, | |
| 88 | title: `${r.name} ${stateWords(r, now)}${r.trusted ? " trusted for secrets" : ""}${isLocal(r) ? " (the forge's own)" : ""}${r.kind === "tab" ? " (a browser tab)" : ""}`, | |
| 89 | 89 | meta: `${asked}${busyWord}${holds}${machine === "" ? "" : ` · ${machine}`}${proto.has(r.id) ? ` · ${proto.get(r.id)}` : ""}${outsideWords(r) === "" ? "" : ` · ${outsideWords(r)}`} · runs ${w.jobs} at once · holding ${n} · ${w.ran} job${w.ran === 1 ? "" : "s"} run${scopeLine(r, now)}${cannot.has(r.id) ? ` · ${cannot.get(r.id)}` : ""}`, |
| 90 | 90 | // Under the row, where a narrow screen never gives it up as it does the meta's pieces. |
| 91 | 91 | ...(proofs.has(r.id) ? { note: proofWords(proofs.get(r.id)) } : {}), |
src/web/pages/runners.ts +32 −5
| @@ -11,7 +11,7 @@ | ||
| 11 | 11 | import { adminPage, signedInPage } from "../../http/page_may.ts"; |
| 12 | 12 | import { listLending, offerLending, resumeLending, stopLending, type LendView } from "../../actions/lending.ts"; |
| 13 | 13 | import { setRunnerTrust } from "../../actions/environments.ts"; |
| 14 | import { enrol, list, pause, removeHandMade, resume, revoke, runnerState } from "../../actions/runners.ts"; | |
| 14 | import { enrolThisTab, enrol, list, pause, removeHandMade, resume, revoke, runnerState } from "../../actions/runners.ts"; | |
| 15 | 15 | import { isLocal } from "../../checks/runner_pool.ts"; |
| 16 | 16 | import { proofByRunner, proofWords } from "../../games/lent_proof.ts"; |
| 17 | 17 | import { cannotByRunner } from "../../games/lend_why.ts"; |
| @@ -27,6 +27,8 @@ import { sshOn } from "../../settings/ssh.ts"; | ||
| 27 | 27 | import { liveRegionsJs } from "../client.ts"; |
| 28 | 28 | import { behaviorsJs } from "../behaviors.ts"; |
| 29 | 29 | import { runnerTailJs } from "../runner_tail.ts"; |
| 30 | import { tabRunnerJs } from "../tab_runner_client.ts"; | |
| 31 | import { TAB_BEAT_MS } from "../../machines/tab_safe.ts"; | |
| 30 | 32 | import { logBox } from "../studio/log.ts"; |
| 31 | 33 | import { notFoundPage, pageHead, settingsLayout, signInFirst } from "../chrome.ts"; |
| 32 | 34 | import { readForm } from "../form.ts"; |
| @@ -80,14 +82,14 @@ function runnerOpen(line: RunnerLine, facts: { label: string; value: string }[]) | ||
| 80 | 82 | } |
| 81 | 83 | |
| 82 | 84 | function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number, cannot: string, proof: string, protocol: string, line?: RunnerLine) { |
| 83 | const state = runnerState(r.seenAt, now); | |
| 85 | const state = runnerState(r.seenAt, now, r.kind); | |
| 84 | 86 | const machine = runnerMachineWords(r); |
| 85 | 87 | const facts = [...(cannot === "" ? [] : [{ label: "Lending", value: cannot }]), ...(proof === "" ? [] : [{ label: "Server", value: proof }]), ...(machine === "" ? [] : [{ label: "Machine", value: machine }]), ...(protocol === "" ? [] : [{ label: "Protocol", value: protocol }]), ...(outsideWords(r) === "" ? [] : [{ label: "Outside", value: outsideWords(r) }]), ...scopeFacts(r, now)]; |
| 86 | 88 | const opens = line?.run !== undefined && line.run.id !== "" && line.run.lines !== undefined; |
| 87 | 89 | return row({ |
| 88 | 90 | lead: icon("activity"), |
| 89 | 91 | state: state === "connected" && r.revokedAt === 0 ? "open" : "draft", |
| 90 | title: html`${r.name} <span class="muted small mono">${r.id}</span> | |
| 92 | title: html`${r.name} <span class="muted small mono">${r.id}</span>${r.kind === "tab" ? badge("Tab", { variant: "outline", icon: "globe" }) : null} | |
| 91 | 93 | ${r.revokedAt !== 0 |
| 92 | 94 | ? badge("Revoked", { variant: "outline", icon: "ban" }) |
| 93 | 95 | : r.paused !== "" |
| @@ -188,6 +190,31 @@ function lendingBlock(ctx: Ctx) { | ||
| 188 | 190 | </section>`; |
| 189 | 191 | } |
| 190 | 192 | |
| 193 | /** This tab as a runner (#18526): the button, and the line the script says what it does in. */ | |
| 194 | function tabBlock() { | |
| 195 | return html`<section class="settings-block" id="tab-runner" data-tab-runner> | |
| 196 | <h2>This tab</h2> | |
| 197 | <p class="muted small">Take runs that need nothing of a machine in this tab while it stays open; it is never sent a secret.</p> | |
| 198 | <noscript><p class="muted small">A tab runner needs scripts; this page has them off.</p></noscript> | |
| 199 | ${btn("Use this tab as a runner", { type: "button", variant: "outline", label: "Use this tab as a runner" })} | |
| 200 | <p class="muted small" data-tab-say aria-live="polite"></p> | |
| 201 | </section>`; | |
| 202 | } | |
| 203 | ||
| 204 | // POST /settings/runners/tab: the token is shown once, to the page's script, and kept nowhere. | |
| 205 | export async function runnerTab(ctx: Ctx): Promise<Response> { | |
| 206 | const denied = admin(ctx); | |
| 207 | if (denied) return denied; | |
| 208 | const form = await readForm(ctx, "admin"); | |
| 209 | if (form instanceof Response) return form; | |
| 210 | const made = enrolThisTab(ctx.app, ctx.auth.user); | |
| 211 | const res = made.ok | |
| 212 | ? Response.json({ id: made.value.runner.id, token: made.value.token, beat: TAB_BEAT_MS }, { status: 201 }) | |
| 213 | : Response.json({ error: made.error === "full" ? "full" : "not_found" }, { status: made.error === "full" ? 409 : 404 }); | |
| 214 | res.headers.set("cache-control", "no-store"); | |
| 215 | return res; | |
| 216 | } | |
| 217 | ||
| 191 | 218 | /** |
| 192 | 219 | * Register an outside runner (#18037), a Mac say: its name, the labels it holds and the |
| 193 | 220 | * repositories it serves. The owner's word here is the only source of its labels. Posts without |
| @@ -331,12 +358,12 @@ export function runnersPage(ctx: Ctx): Response { | ||
| 331 | 358 | ${lent === "" ? "" : html`<p class="muted small" id="lent-line">${lent}</p>`} |
| 332 | 359 | <p class="muted small">Enrol one with <code>POST /api/v1/admin/runners</code>, or register a machine below.</p> |
| 333 | 360 | ${runnersLivePart(ctx, seen.value)} |
| 334 | </section>${registerBlock()}${lendingBlock(ctx)}`; | |
| 361 | </section>${tabBlock()}${registerBlock()}${lendingBlock(ctx)}`; | |
| 335 | 362 | notePhase(ctx.request, "render", performance.now() - rendering); |
| 336 | 363 | return page({ |
| 337 | 364 | ctx, |
| 338 | 365 | title: "Runners", |
| 339 | scriptJs: `${liveRegionsJs}\n${runnerTailJs}\n${behaviorsJs}`, | |
| 366 | scriptJs: `${liveRegionsJs}\n${runnerTailJs}\n${tabRunnerJs}\n${behaviorsJs}`, | |
| 340 | 367 | body: html`${pageHead("Runners", { sub: "The machines that take this forge's checks, and whether each is asking for work." })} |
| 341 | 368 | ${settingsLayout(accountSections("runners", { admin: true, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`, |
| 342 | 369 | }); |
src/web/style/components.ts +1
| @@ -1342,6 +1342,7 @@ a[data-palette] { display: none; } | ||
| 1342 | 1342 | .settings-block > h2 { margin-bottom: 8px; } |
| 1343 | 1343 | .settings-block > .bar { gap: 12px; flex-wrap: wrap; } |
| 1344 | 1344 | .settings-block > p { margin-top: 8px; } |
| 1345 | [data-tab-say] { min-height: 1.5em; } | |
| 1345 | 1346 | .status-rows { margin: 24px 0 0; border-top: 1px solid var(--border); } |
| 1346 | 1347 | .status-row { |
| 1347 | 1348 | display: grid; grid-template-columns: minmax(0, 1fr); gap: 2px 16px; align-items: center; |
src/web/tab_runner_client.ts added +100
| @@ -0,0 +1,100 @@ | ||
| 1 | /** | |
| 2 | * "Use this tab as a runner" (#18526): the script behind the button on Settings → Runners. It asks | |
| 3 | * the forge for a runner token (`POST /settings/runners/tab`), keeps it in a variable (never in | |
| 4 | * storage, a cookie or the page), and speaks the agent protocol (`/api/v1/agent/v1/<message>`): | |
| 5 | * a heartbeat every `beat` ms, a claim held open, then logs and a result for the job it took. It | |
| 6 | * runs only the steps `machines/tab_safe.ts` reads (text it prints); a job with any other step is | |
| 7 | * handed back untouched, and no code of a pull is ever evaluated here. Close the tab, or press the | |
| 8 | * button again, and the heartbeats stop: the forge drops the row within half a minute. | |
| 9 | */ | |
| 10 | import { STEP_PATTERN } from "../machines/tab_safe.ts"; | |
| 11 | ||
| 12 | export const tabRunnerJs = /* js */ ` | |
| 13 | (function () { | |
| 14 | var box = document.querySelector('[data-tab-runner]'); | |
| 15 | if (!box) return; | |
| 16 | var button = box.querySelector('button'); | |
| 17 | var say = box.querySelector('[data-tab-say]'); | |
| 18 | var step = new RegExp(${JSON.stringify(STEP_PATTERN)}); | |
| 19 | var token = ''; | |
| 20 | var busy = false; | |
| 21 | var beat = null; | |
| 22 | function tell(text) { say.textContent = text; } | |
| 23 | function send(message, bearer, body) { | |
| 24 | body.v = 1; | |
| 25 | return fetch('/api/v1/agent/v1/' + message, { | |
| 26 | method: 'POST', | |
| 27 | headers: { authorization: 'Bearer ' + bearer, 'content-type': 'application/json' }, | |
| 28 | body: JSON.stringify(body), | |
| 29 | }); | |
| 30 | } | |
| 31 | function stop(why) { | |
| 32 | token = ''; | |
| 33 | if (beat) clearInterval(beat); | |
| 34 | beat = null; | |
| 35 | button.textContent = 'Use this tab as a runner'; | |
| 36 | tell(why); | |
| 37 | } | |
| 38 | function heartbeat(mine) { | |
| 39 | send('heartbeat', mine, { state: busy ? 'busy' : 'idle' }).then(function (r) { | |
| 40 | if (token === mine && r.status === 401) stop('The forge no longer knows this tab. Use it as a runner again.'); | |
| 41 | }, function () {}); | |
| 42 | } | |
| 43 | async function run(job, jobToken) { | |
| 44 | var started = Date.now(); | |
| 45 | var steps = []; | |
| 46 | var lines = []; | |
| 47 | for (var i = 0; i < job.steps.length; i++) { | |
| 48 | var m = step.exec(String(job.steps[i].command)); | |
| 49 | if (!m) { | |
| 50 | await send('result', jobToken, { job: job.id, abandon: 'this tab does not know the step ' + String(job.steps[i].name).slice(0, 40) }); | |
| 51 | return 'handed back a job it cannot run'; | |
| 52 | } | |
| 53 | lines.push(m[1]); | |
| 54 | steps.push({ name: job.steps[i].name, ok: true, ms: Date.now() - started }); | |
| 55 | } | |
| 56 | await send('logs', jobToken, { job: job.id, lines: lines, step: 'check' }); | |
| 57 | await send('result', jobToken, { job: job.id, done: { steps: steps, contained: false, note: 'ran in a browser tab' } }); | |
| 58 | return 'ran a job'; | |
| 59 | } | |
| 60 | async function loop(mine) { | |
| 61 | while (token === mine) { | |
| 62 | var r; | |
| 63 | try { | |
| 64 | r = await send('claim', mine, { wait: 10, cells: false }); | |
| 65 | } catch (e) { | |
| 66 | await new Promise(function (ok) { setTimeout(ok, 3000); }); | |
| 67 | continue; | |
| 68 | } | |
| 69 | if (token !== mine) return; | |
| 70 | if (r.status === 401) return stop('The forge no longer knows this tab. Use it as a runner again.'); | |
| 71 | if (r.status !== 200) continue; | |
| 72 | var got = await r.json(); | |
| 73 | busy = true; | |
| 74 | heartbeat(mine); | |
| 75 | try { | |
| 76 | tell('This tab ' + (await run(got.job, got.token)) + '.'); | |
| 77 | } finally { | |
| 78 | busy = false; | |
| 79 | } | |
| 80 | } | |
| 81 | } | |
| 82 | button.addEventListener('click', function () { | |
| 83 | if (token !== '') return stop('This tab stopped taking runs.'); | |
| 84 | button.disabled = true; | |
| 85 | fetch('/settings/runners/tab', { method: 'POST', credentials: 'same-origin' }) | |
| 86 | .then(function (r) { return r.ok ? r.json() : Promise.reject(r.status); }) | |
| 87 | .then(function (made) { | |
| 88 | token = String(made.token); | |
| 89 | button.textContent = 'Stop using this tab'; | |
| 90 | tell('This tab is a runner while it stays open. It takes only runs that need nothing of a machine.'); | |
| 91 | var mine = token; | |
| 92 | heartbeat(mine); | |
| 93 | beat = setInterval(function () { heartbeat(mine); }, Number(made.beat) || 10000); | |
| 94 | loop(mine); | |
| 95 | }) | |
| 96 | .catch(function (why) { tell(why === 409 ? 'Eight tabs are runners already.' : 'Could not make this tab a runner.'); }) | |
| 97 | .then(function () { button.disabled = false; }); | |
| 98 | }); | |
| 99 | })(); | |
| 100 | `; |
test/no-polling.test.ts +1
| @@ -112,6 +112,7 @@ const ALLOWED: Record<string, { allow: string[]; why: string }> = { | ||
| 112 | 112 | "src/web/client.ts": { allow: ["setInterval"], why: "clocks that only redraw text" }, |
| 113 | 113 | "src/web/space_client.ts": { allow: ["setInterval"], why: "the map clock label only redraws text; it fetches and reloads nothing" }, |
| 114 | 114 | "src/web/pages/boards-stream.ts": { allow: ["setInterval"], why: "the board's \"updated Ns ago\" label only redraws text; the stream carries the data" }, |
| 115 | "src/web/tab_runner_client.ts": { allow: ["setInterval"], why: "the tab runner's heartbeat: the forge learns the tab is alive only by hearing from it, so there is no /events to hear" }, | |
| 115 | 116 | }; |
| 116 | 117 | |
| 117 | 118 | const PATTERNS: [string, RegExp][] = [ |
test/tab-runner.test.ts added +163
| @@ -0,0 +1,163 @@ | ||
| 1 | /** | |
| 2 | * A browser tab as a runner (#18526): an admin's page enrols it, it speaks the agent protocol with | |
| 3 | * a runner token, claims only what the forge marked tab-safe, and is refused once a heartbeat is | |
| 4 | * missed. | |
| 5 | */ | |
| 6 | import { expect, test } from "bun:test"; | |
| 7 | import { deskOf, listRunners, offerJob, runnerByToken, viewJob, type RunnerJob } from "../src/checks/runner_jobs.ts"; | |
| 8 | import { createSession } from "../src/core/sessions.ts"; | |
| 9 | import { reapTabs } from "../src/machines/tab_runner.ts"; | |
| 10 | import { TAB_MAX, TAB_TTL_MS, isTabSafe, readStep } from "../src/machines/tab_safe.ts"; | |
| 11 | import { tabRunnerJs } from "../src/web/tab_runner_client.ts"; | |
| 12 | import { checksForge } from "./helpers/checks-forge.ts"; | |
| 13 | import { quietLogs } from "./helpers/globals.ts"; | |
| 14 | ||
| 15 | quietLogs(); | |
| 16 | const f = checksForge("forge-tab-runner-"); | |
| 17 | ||
| 18 | const base: Omit<RunnerJob, "id"> = { | |
| 19 | run: "run1", | |
| 20 | repo: "alice/lib", | |
| 21 | commit: "a".repeat(40), | |
| 22 | depth: 1, | |
| 23 | steps: [{ name: "check", command: "forge-tab echo hello from a tab" }], | |
| 24 | env: {}, | |
| 25 | limits: {}, | |
| 26 | timeoutS: 60, | |
| 27 | egress: [], | |
| 28 | egressMode: "enforce", | |
| 29 | cell: "preferred", | |
| 30 | cache: { repo: "r", tree: "", base: "" }, | |
| 31 | }; | |
| 32 | const shell: Omit<RunnerJob, "id"> = { ...base, steps: [{ name: "check", command: "bun test" }] }; | |
| 33 | ||
| 34 | const cookie = (who: { id: string }) => `forge_session=${createSession(f.app.db, who.id).token}`; | |
| 35 | const enrol = (who: { id: string }, origin = f.servers.url) => | |
| 36 | fetch(`${f.servers.url}/settings/runners/tab`, { method: "POST", headers: { cookie: cookie(who), origin } }); | |
| 37 | const v1 = (message: string, token: string, body: Record<string, unknown>) => | |
| 38 | fetch(`${f.servers.url}/api/v1/agent/v1/${message}`, { | |
| 39 | method: "POST", | |
| 40 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 41 | body: JSON.stringify({ v: 1, ...body }), | |
| 42 | }); | |
| 43 | const tab = async (): Promise<{ id: string; token: string }> => { | |
| 44 | const r = await enrol(f.alice); | |
| 45 | expect(r.status).toBe(201); | |
| 46 | return (await r.json()) as { id: string; token: string }; | |
| 47 | }; | |
| 48 | const clear = () => { | |
| 49 | f.app.db.query("DELETE FROM check_runner WHERE kind = 'tab'").run(); | |
| 50 | f.app.db.query("DELETE FROM check_job WHERE state = 'queued'").run(); | |
| 51 | }; | |
| 52 | const age = (id: string, ms: number) => f.app.db.query("UPDATE check_runner SET seen_at = seen_at - ?2 WHERE id = ?1").run(id, ms); | |
| 53 | ||
| 54 | test("only an admin's same-origin page enrols a tab, and the token is never stored", async () => { | |
| 55 | expect((await enrol(f.bob)).status).toBe(404); | |
| 56 | expect((await enrol(f.alice, "https://evil.example")).status).toBe(403); | |
| 57 | const r = await enrol(f.alice); | |
| 58 | expect(r.headers.get("cache-control")).toBe("no-store"); | |
| 59 | const made = (await r.json()) as { id: string; token: string }; | |
| 60 | const row = listRunners(f.app.db).find((x) => x.id === made.id)!; | |
| 61 | expect(row.kind).toBe("tab"); | |
| 62 | expect(row.trusted).toBe(false); | |
| 63 | expect(JSON.stringify(row)).not.toContain(made.token); | |
| 64 | // The page's script keeps the token in a variable, in no storage. | |
| 65 | expect(tabRunnerJs).not.toMatch(/localStorage|sessionStorage|document\.cookie/); | |
| 66 | expect(tabRunnerJs).not.toMatch(/\beval\(|new Function/); | |
| 67 | }); | |
| 68 | ||
| 69 | test("a tab claims a tab-safe run through the protocol and reports it", async () => { | |
| 70 | const t = await tab(); | |
| 71 | expect((await v1("heartbeat", t.token, { state: "idle" })).status).toBe(204); | |
| 72 | const job = offerJob(f.app.db, { runId: "run-tab", repoId: f.repo.id, dir: "/nowhere", job: base }); | |
| 73 | deskOf(f.app).ears.set(job.id, { lines: () => {}, wake: () => {} }); | |
| 74 | const claimed = await v1("claim", t.token, { wait: 0, cells: true }); | |
| 75 | expect(claimed.status).toBe(200); | |
| 76 | const got = (await claimed.json()) as { job: { id: string; steps: { command: string }[] }; token: string }; | |
| 77 | expect(got.job.id).toBe(job.id); | |
| 78 | expect(readStep(got.job.steps[0]!.command)).toBe("hello from a tab"); | |
| 79 | expect((await v1("logs", got.token, { job: job.id, lines: ["hello from a tab"], step: "check" })).status).toBe(200); | |
| 80 | const done = await v1("result", got.token, { job: job.id, done: { steps: [{ name: "check", ok: true, ms: 1 }], contained: false, note: "ran in a browser tab" } }); | |
| 81 | expect(done.status).toBe(200); | |
| 82 | expect(viewJob(f.app.db, job.id)?.state).toBe("done"); | |
| 83 | }); | |
| 84 | ||
| 85 | test("a tab takes no run that is not marked tab-safe, whatever it says of itself", async () => { | |
| 86 | const t = await tab(); | |
| 87 | offerJob(f.app.db, { runId: "run-shell", repoId: f.repo.id, dir: "/nowhere", job: shell }); | |
| 88 | offerJob(f.app.db, { runId: "run-cell", repoId: f.repo.id, dir: "/nowhere", job: { ...base, cell: "required" } }); | |
| 89 | offerJob(f.app.db, { runId: "run-label", repoId: f.repo.id, dir: "/nowhere", job: { ...base, label: "macos" } }); | |
| 90 | const r = await v1("claim", t.token, { wait: 0, cells: true, machine: { cpus: 64, memoryMiB: 99999 } }); | |
| 91 | expect(r.status).toBe(204); | |
| 92 | expect(isTabSafe(base)).toBe(true); | |
| 93 | expect(isTabSafe({ ...base, hands: ["x"] })).toBe(false); | |
| 94 | expect(isTabSafe({ ...base, environment: "prod" })).toBe(false); | |
| 95 | expect(isTabSafe({ ...base, env: { TOKEN: "s3cret" } })).toBe(false); | |
| 96 | expect(isTabSafe({ ...base, env: {} })).toBe(true); | |
| 97 | expect(isTabSafe({ ...base, steps: [{ command: "forge-tab run a" }] })).toBe(false); | |
| 98 | expect(isTabSafe({ ...base, steps: [{ command: "forge-tab echo a\nrm -rf /" }] })).toBe(false); | |
| 99 | // A tab that says it is paused claims nothing even for a safe job. | |
| 100 | offerJob(f.app.db, { runId: "run-safe2", repoId: f.repo.id, dir: "/nowhere", job: base }); | |
| 101 | expect((await v1("heartbeat", t.token, { state: "paused" })).status).toBe(204); | |
| 102 | expect((await v1("claim", t.token, { wait: 0 })).status).toBe(204); | |
| 103 | }); | |
| 104 | ||
| 105 | test("an expired token is refused, and the tab is gone from the list", async () => { | |
| 106 | const t = await tab(); | |
| 107 | offerJob(f.app.db, { runId: "run-late", repoId: f.repo.id, dir: "/nowhere", job: base }); | |
| 108 | age(t.id, TAB_TTL_MS + 1_000); | |
| 109 | expect(runnerByToken(f.app.db, t.token, Date.now())).toBeUndefined(); | |
| 110 | expect((await v1("heartbeat", t.token, { state: "idle" })).status).toBe(401); | |
| 111 | const claim = await v1("claim", t.token, { wait: 0 }); | |
| 112 | expect(claim.status).toBe(401); | |
| 113 | expect(reapTabs(f.app.db, Date.now())).toBeGreaterThanOrEqual(1); | |
| 114 | expect(listRunners(f.app.db).some((r) => r.id === t.id)).toBe(false); | |
| 115 | }); | |
| 116 | ||
| 117 | test("a tab that keeps asking stays; the page lists it as a tab and caps how many", async () => { | |
| 118 | const t = await tab(); | |
| 119 | age(t.id, TAB_TTL_MS - 5_000); | |
| 120 | expect((await v1("heartbeat", t.token, { state: "idle" })).status).toBe(204); | |
| 121 | const page = await (await fetch(`${f.servers.url}/settings/runners`, { headers: { cookie: cookie(f.alice) } })).text(); | |
| 122 | expect(page).toContain("Use this tab as a runner"); | |
| 123 | expect(page).toContain(t.id); | |
| 124 | expect(page).toContain("Tab"); | |
| 125 | for (let i = 0; i < TAB_MAX + 2; i++) await enrol(f.alice); | |
| 126 | expect(listRunners(f.app.db).filter((r) => r.kind === "tab").length).toBeLessThanOrEqual(TAB_MAX); | |
| 127 | expect((await enrol(f.alice)).status).toBe(409); | |
| 128 | }); | |
| 129 | ||
| 130 | test("the claim itself refuses a private repository, hands and an env, even for a row marked safe", async () => { | |
| 131 | clear(); | |
| 132 | const t = await tab(); | |
| 133 | const unsafe = [ | |
| 134 | offerJob(f.app.db, { runId: "run-hands", repoId: f.repo.id, dir: "/nowhere", job: { ...base, hands: ["x"] } }), | |
| 135 | offerJob(f.app.db, { runId: "run-env", repoId: f.repo.id, dir: "/nowhere", job: { ...base, env: { TOKEN: "s3cret" } } }), | |
| 136 | offerJob(f.app.db, { runId: "run-priv", repoId: f.repo.id, dir: "/nowhere", job: base }), | |
| 137 | ]; | |
| 138 | // Force the mark, so only the claim's own conditions stand in the way. | |
| 139 | f.app.db.query("UPDATE check_job SET tab_safe = 1 WHERE id IN (?1, ?2, ?3)").run(unsafe[0]!.id, unsafe[1]!.id, unsafe[2]!.id); | |
| 140 | f.app.db.query("UPDATE repo SET visibility = 'private' WHERE id = ?1").run(f.repo.id); | |
| 141 | try { | |
| 142 | expect((await v1("claim", t.token, { wait: 0 })).status).toBe(204); | |
| 143 | } finally { | |
| 144 | f.app.db.query("UPDATE repo SET visibility = 'public' WHERE id = ?1").run(f.repo.id); | |
| 145 | } | |
| 146 | // Public again, the two that carry hands and an env are still refused; the plain one is taken. | |
| 147 | const r = await v1("claim", t.token, { wait: 0 }); | |
| 148 | expect(r.status).toBe(200); | |
| 149 | expect(((await r.json()) as { job: { id: string } }).job.id).toBe(unsafe[2]!.id); | |
| 150 | expect((await v1("claim", t.token, { wait: 0 })).status).toBe(204); | |
| 151 | }); | |
| 152 | ||
| 153 | test("a job a tab holds is queued again when the tab is reaped", async () => { | |
| 154 | clear(); | |
| 155 | const t = await tab(); | |
| 156 | const job = offerJob(f.app.db, { runId: "run-held", repoId: f.repo.id, dir: "/nowhere", job: base }); | |
| 157 | deskOf(f.app).ears.set(job.id, { lines: () => {}, wake: () => {} }); | |
| 158 | expect((await v1("claim", t.token, { wait: 0 })).status).toBe(200); | |
| 159 | expect(viewJob(f.app.db, job.id)?.state).toBe("claimed"); | |
| 160 | age(t.id, TAB_TTL_MS + 1_000); | |
| 161 | expect(reapTabs(f.app.db, Date.now())).toBeGreaterThanOrEqual(1); | |
| 162 | expect(viewJob(f.app.db, job.id)?.state).toBe("queued"); | |
| 163 | }); |
new above
offline
Medium:
envis not checked here, yet the job (with its env) is handed to the tab on claim. Require an emptyenvso a tab is never sent a secret, and test it.