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

Universal runner: a Mac registers itself, ships TestFlight from main with the forge's secrets, and has one switch #18291

opened this in answer to

Merged 4h 10m ago, live in production

mason/forge:mason/18257-universal-runner-a-mac-registers-itself → main 0 commits fork 2 threads · 2 unresolved

  • Merged. mason/18257-universal-runner-a-mac-registers-itself was merged into main as 08c168a.

Review

Sign in to review this change.
32 files changed +1012 −9
docs/features/environments.md added +53
@@ -0,0 +1,53 @@
1 ---
2 topic: Ship and undo
3 row: Environments: variables and sealed secrets a check receives, and which runners are trusted for them
4 ---
5 # Environments: what a check receives, and from whom
6
7 A repository has named environments (`checks`, `testflight`). Each holds **variables** (plain,
8 listed with their values) and **secrets** (sealed on the forge, write-only: nothing returns one).
9 `forge.json` names the environment a check uses: `{"check": {"run": "…", "environment": "testflight"}}`.
10
11 Each entry says who may receive it: `any` runner or `trusted` runners only. A variable defaults to
12 any, a secret to trusted; a secret for any runner needs `confirm` set to its own name.
13
14 ## The rule
15
16 A secret is sent to a job only when the job is on main (never a pull's head, never a fork's),
17 and the runner was marked trusted for secrets by a site admin, and the entry allows it. A fork is
18 another repository: it holds its own entries and none of its parent's. A job's log says which
19 names it received and which it held back and why; a secret's value is masked in every line a
20 runner reports.
21
22 ## Set them (repository administrator)
23
24 In the terminal: the palette's "Environments" for the repository lists each entry by name, kind
25 and who may receive it (never a secret's value); `a` sets one (a secret's value is asked in a
26 hidden prompt), `x` removes the one under the cursor. Or over the API:
27
28 ```
29 curl -X PUT -H "authorization: Bearer $TOKEN" -d '{"kind":"secret","value":"…"}' \
30 $FORGE_URL/api/v1/repos/OWNER/NAME/environments/testflight/ASC_KEY
31 curl -H "authorization: Bearer $TOKEN" $FORGE_URL/api/v1/repos/OWNER/NAME/environments
32 ```
33
34 A secret is at least 4 characters. Names the forge or a shell reads to run code (`CI`, `FORGE_*`,
35 `PATH`, `HOME`, `BUN_*`, `NODE_*`, `LD_*`, `DYLD_*`, `GIT_*`, `SSH_*`, `BASH_ENV`, `ENV`, …) are
36 refused, in any case.
37
38 ## Trust a runner (site admin)
39
40 Settings → Runners has a Trust / Untrust button on each runner that is not the forge's own; in the
41 terminal, `t` on the runner's row. Over the API: `POST /api/v1/admin/runners/ID/trust` with
42 `{"trusted": true}`; the same with `false` takes it back.
43
44 ## What the log never shows
45
46 Every line a runner reports, and a step's error and note, is masked of every secret of the job's
47 environment, not only those the runner was given, so taking trust back mid-job does not unmask
48 what it holds. A multi-line secret is masked line by line, and each line in base64 and URL form
49 too. Not covered: a secret split across two reported lines or batches, a form a step computes
50 itself, and a secret rotated or removed while a job that held the old value runs.
51
52 A check's job is on `main` only when it is the default branch's own check; a pull's check is
53 `pull`, an outside contributor's `fork`, and neither is sent a secret.
src/actions/environments.ts added +42
@@ -0,0 +1,42 @@
1 /**
2 * Setting a repository's environments and trusting a runner (#18257): the repository's
3 * administrator sets entries (`checks/environment.ts`); a site admin marks a runner trusted for
4 * secrets. Each is an event: who, which name; never a value.
5 */
6 import type { App } from "../app.ts";
7 import { canAdmin, type Repo } from "../core/repos.ts";
8 import type { User } from "../core/users.ts";
9 import { err, ok, type Result } from "../kernel/result.ts";
10 import { removeEntry, setEntry, trustRunner, type EntryKind, type EntryScope, type SetError } from "../checks/environment.ts";
11 import { getRunner } from "../checks/runner_jobs.ts";
12
13 export function setEnvironmentEntry(
14 app: App,
15 actor: User | undefined,
16 repo: Repo,
17 input: { env: string; name: string; kind: EntryKind; value: string; scope?: EntryScope; confirm?: string },
18 ): Result<{ scope: EntryScope }, "not_found" | SetError> {
19 if (actor === undefined || !canAdmin(app.db, repo, actor)) return err("not_found");
20 const scope = input.scope ?? (input.kind === "secret" ? "trusted" : "any");
21 const failed = setEntry(app.db, app.config.dataDir, repo.id, { ...input, scope, by: actor.username }, Date.now());
22 if (failed !== undefined) return err(failed);
23 app.bus.append({ kind: "environment.set", actorId: actor.id, repoId: repo.id, payload: { env: input.env, name: input.name, entry: input.kind, scope } });
24 return ok({ scope });
25 }
26
27 export function removeEnvironmentEntry(app: App, actor: User | undefined, repo: Repo, env: string, name: string): Result<true, "not_found"> {
28 if (actor === undefined || !canAdmin(app.db, repo, actor) || !removeEntry(app.db, repo.id, env, name)) return err("not_found");
29 app.bus.append({ kind: "environment.removed", actorId: actor.id, repoId: repo.id, payload: { env, name } });
30 return ok(true);
31 }
32
33 export function setRunnerTrust(app: App, actor: User | undefined, runnerId: string, trusted: boolean): Result<{ id: string; name: string; trusted: boolean }, "not_found" | "local"> {
34 const runner = getRunner(app.db, runnerId);
35 if (actor === undefined || !actor.isAdmin || runner === undefined) return err("not_found");
36 // The forge's own `local-N` runners hold the forge's data already; trust is for machines it does
37 // not own.
38 if (runner.name.startsWith("local-")) return err("local");
39 trustRunner(app.db, runnerId, trusted, actor.username, Date.now());
40 app.bus.append({ kind: trusted ? "runner.trusted" : "runner.untrusted", actorId: actor.id, payload: { id: runnerId, name: runner.name } });
41 return ok({ id: runnerId, name: runner.name, trusted });
42 }
src/apps/manifest.ts +9
@@ -549,8 +549,13 @@ export interface CheckManifest {
549549 * ever.
550550 */
551551 readonly label?: string | undefined;
552 /**
553 * `check.environment` (#18257): the repository's environment whose variables the check receives.
554 */
555 readonly environment?: string | undefined;
552556 }
553557
558 const ENV_NAME = /^[a-z][a-z0-9-]{0,31}$/;
554559 const CHECK_LABEL = /^[a-z0-9][a-z0-9._-]{0,31}$/;
555560 const CHECK_TIMEOUT_DEFAULT = 20 * 60;
556561 export const CHECK_TIMEOUT_MAX = 2 * 60 * 60;
@@ -602,8 +607,12 @@ export function parseCheck(
602607 const label = check["label"];
603608 if (label !== undefined && (typeof label !== "string" || !CHECK_LABEL.test(label)))
604609 return invalid("forge.json: check.label must be a lower-case label such as macos (letters, digits, . _ -, at most 32)");
610 const environment = check["environment"];
611 if (environment !== undefined && (typeof environment !== "string" || !ENV_NAME.test(environment)))
612 return invalid("forge.json: check.environment must be a lower-case name such as checks (letters, digits, -, at most 32)");
605613 return ok({
606614 ...(label === undefined ? {} : { label }),
615 ...(environment === undefined ? {} : { environment }),
607616 run: run.value,
608617 fast: fast.value || null,
609618 full: full.value || run.value,
src/checks/environment.ts added +191
@@ -0,0 +1,191 @@
1 /**
2 * A repository's environments (#18257): named sets of variables (plain, readable) and secrets
3 * (sealed with `kernel/secret.ts`, write-only: no function here returns a secret's value to a
4 * person). Each entry says who may receive it: `any` runner or `trusted` runners only; a secret
5 * is `trusted` unless set otherwise, and `any` needs a typed confirmation at the door.
6 *
7 * `received` is the one rule a job's environment is built by, and it is pure:
8 * - a variable goes to any runner when its scope is `any`, and to a trusted one always;
9 * - a secret goes only when the job is a main job (`lane: "main"`: never a pull's head, never a
10 * fork's), and the runner is trusted, and the entry's scope allows the runner (`any` or
11 * `trusted`: a trusted runner holds both).
12 * A fork is another repository, so it holds its own entries and none of its parent's.
13 */
14
15 import type { Database } from "bun:sqlite";
16 import { open, seal } from "../kernel/secret.ts";
17
18 export type EntryKind = "var" | "secret";
19 export type EntryScope = "any" | "trusted";
20 /** Where a job's commit came from: the base branch moving, a pull's head, or a fork's. */
21 export type Lane = "main" | "pull" | "fork";
22
23 export const ENV_RE = /^[a-z][a-z0-9-]{0,31}$/;
24 export const ENTRY_RE = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
25 export const VALUE_MAX = 16 * 1024;
26 export const MAX_ENTRIES = 64;
27 /** Names the forge sets on every job itself; an entry may not shadow them. */
28 const RESERVED = /^(CI|FORGE_.*|PATH|HOME|BUN_.*|NODE_.*|LD_.*|DYLD_.*|BASH_ENV|ENV|GIT_.*|SSH_.*|SHELL|IFS|PS4|TMPDIR|USER)$/i;
29 /** A secret shorter than this is refused: a mask cannot tell it from the text around it. */
30 export const SECRET_MIN = 4;
31
32 export interface EntryName {
33 readonly env: string;
34 readonly name: string;
35 readonly kind: EntryKind;
36 readonly scope: EntryScope;
37 readonly setBy: string;
38 readonly setAt: number;
39 /** A variable's own value; absent for a secret, whatever asks. */
40 readonly value?: string;
41 }
42
43 type Row = { env: string; name: string; kind: EntryKind; value: string; scope: EntryScope; set_by: string; set_at: number };
44
45 const aad = (repoId: string, env: string, name: string): string => `env:${repoId}:${env}:${name}`;
46
47 export type SetError = "bad_env" | "bad_name" | "reserved" | "bad_value" | "too_many" | "confirm";
48
49 /**
50 * Set one entry. A secret for `any` runner is refused unless `confirm` is the secret's own name:
51 * the typed confirmation.
52 */
53 export function setEntry(
54 db: Database,
55 dataDir: string,
56 repoId: string,
57 input: { env: string; name: string; kind: EntryKind; value: string; scope?: EntryScope; confirm?: string; by: string },
58 now: number,
59 ): SetError | undefined {
60 if (!ENV_RE.test(input.env)) return "bad_env";
61 if (!ENTRY_RE.test(input.name)) return "bad_name";
62 if (RESERVED.test(input.name)) return "reserved";
63 if (input.value.length > VALUE_MAX || (input.kind === "secret" && input.value.length < SECRET_MIN)) return "bad_value";
64 const scope = input.scope ?? (input.kind === "secret" ? "trusted" : "any");
65 if (input.kind === "secret" && scope === "any" && input.confirm !== input.name) return "confirm";
66 const have = db.query<{ n: number; same: number }, [string, string, string]>(
67 "SELECT COUNT(*) AS n, SUM(env = ?2 AND name = ?3) AS same FROM repo_env WHERE repo_id = ?1",
68 ).get(repoId, input.env, input.name)!;
69 if (!have.same && have.n >= MAX_ENTRIES) return "too_many";
70 const kept = input.kind === "secret" ? seal(dataDir, input.value, aad(repoId, input.env, input.name)) : input.value;
71 db.query(
72 `INSERT INTO repo_env (repo_id, env, name, kind, value, scope, set_by, set_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
73 ON CONFLICT (repo_id, env, name) DO UPDATE SET kind = ?4, value = ?5, scope = ?6, set_by = ?7, set_at = ?8`,
74 ).run(repoId, input.env, input.name, input.kind, kept, scope, input.by, now);
75 return undefined;
76 }
77
78 export function removeEntry(db: Database, repoId: string, env: string, name: string): boolean {
79 return db.query("DELETE FROM repo_env WHERE repo_id = ?1 AND env = ?2 AND name = ?3").run(repoId, env, name).changes > 0;
80 }
81
82 /**
83 * The entries of a repository, by environment then name: variables with values, secrets without.
84 */
85 export function listEntries(db: Database, repoId: string): EntryName[] {
86 return db
87 .query<Row, [string]>("SELECT env, name, kind, value, scope, set_by, set_at FROM repo_env WHERE repo_id = ?1 ORDER BY env, name")
88 .all(repoId)
89 .map((r) => ({
90 env: r.env,
91 name: r.name,
92 kind: r.kind,
93 scope: r.scope,
94 setBy: r.set_by,
95 setAt: r.set_at,
96 ...(r.kind === "var" ? { value: r.value } : {}),
97 }));
98 }
99
100 /** Who and when: mark a runner trusted for secrets, or take it back. */
101 export function trustRunner(db: Database, runnerId: string, trusted: boolean, by: string, now: number): boolean {
102 return (
103 db
104 .query("UPDATE check_runner SET trusted_by = ?2, trusted_at = ?3 WHERE id = ?1")
105 .run(runnerId, trusted ? by : "", trusted ? Math.max(1, now) : 0).changes > 0
106 );
107 }
108
109 export const runnerTrusted = (db: Database, runnerId: string): boolean =>
110 db.query<{ t: number }, [string]>("SELECT trusted_at AS t FROM check_runner WHERE id = ?1").get(runnerId)?.t! > 0;
111
112 export interface Received {
113 /** Name to value: what the job's steps get beside `CI` and `FORGE_*`. */
114 readonly env: Record<string, string>;
115 /** The names received, with no value: what the run page lists. */
116 readonly names: readonly string[];
117 /** Names an entry held back, and why: the run page says it too. */
118 readonly withheld: readonly { name: string; why: string }[];
119 }
120
121 /** What a job of this lane on this runner receives of one environment. */
122 export function received(
123 db: Database,
124 dataDir: string,
125 input: { repoId: string; env: string; lane: Lane; trusted: boolean },
126 ): Received {
127 const rows = db
128 .query<Row, [string, string]>("SELECT env, name, kind, value, scope, set_by, set_at FROM repo_env WHERE repo_id = ?1 AND env = ?2 ORDER BY name")
129 .all(input.repoId, input.env);
130 const env: Record<string, string> = {};
131 const withheld: { name: string; why: string }[] = [];
132 for (const r of rows) {
133 if (r.kind === "var") {
134 if (r.scope === "trusted" && !input.trusted) withheld.push({ name: r.name, why: "for trusted runners only" });
135 else env[r.name] = r.value;
136 continue;
137 }
138 if (input.lane !== "main") withheld.push({ name: r.name, why: `a secret goes only to a job on main, not to ${input.lane === "fork" ? "a fork's" : "a pull's"} head` });
139 else if (!input.trusted) withheld.push({ name: r.name, why: "this runner is not trusted for secrets" });
140 else {
141 const opened = open(dataDir, r.value, aad(input.repoId, r.env, r.name));
142 if (opened.ok) env[r.name] = opened.value;
143 else withheld.push({ name: r.name, why: "it could not be opened" });
144 }
145 }
146 return { env, names: Object.keys(env), withheld };
147 }
148
outdated

Masks only exact single-line values of 4+ characters. Multi-line secrets (.p8 keys) and short ones are not masked. Fix as in point 2.

149 /**
150 * Every secret value of an environment, opened, whatever the job's lane or runner's trust:
151 * what a log is masked by must not shrink when trust is taken back or an entry's scope changes
152 * while a job holds the value.
153 */
154 export function secretValues(db: Database, dataDir: string, repoId: string, env: string): string[] {
155 const out: string[] = [];
156 for (const r of db
157 .query<Row, [string, string]>("SELECT env, name, kind, value, scope, set_by, set_at FROM repo_env WHERE repo_id = ?1 AND env = ?2 AND kind = 'secret'")
158 .all(repoId, env)) {
159 const opened = open(dataDir, r.value, aad(repoId, r.env, r.name));
160 if (opened.ok) out.push(opened.value);
161 }
162 return out;
163 }
164
165 /**
166 * The forms of a secret a step may print: the whole value, each line of it alone (a key file is
167 * several lines, and a step prints them one at a time), and each in base64 and URL form.
168 */
169 function formsOf(value: string): string[] {
170 const parts = [value, ...value.split(/\r?\n/).map((l) => l.trim())].filter((p) => p.length >= SECRET_MIN);
171 const forms = new Set<string>();
172 for (const p of parts) {
173 forms.add(p);
174 forms.add(Buffer.from(p).toString("base64"));
175 forms.add(encodeURIComponent(p));
176 }
177 return [...forms].filter((f) => f.length >= SECRET_MIN).sort((a, b) => b.length - a.length);
178 }
179
180 /** A function replacing every form of every secret value in a line with `***`. */
181 export function masker(values: readonly string[]): (line: string) => string {
182 const forms = [...new Set(values.flatMap(formsOf))].sort((a, b) => b.length - a.length);
183 return (line) => {
184 let out = line;
185 for (const f of forms) out = out.split(f).join("***");
186 return out;
187 };
188 }
189
190 /** A log line with every secret value of the environment replaced by `***`. */
191 export const mask = (values: readonly string[], line: string): string => masker(values)(line);
src/checks/job_environment.ts added +54
@@ -0,0 +1,54 @@
1 /**
2 * What a claimed job receives of its environment (#18257), and what its log never shows of it.
3 *
4 * The spec on the desk names an environment and holds no value. At claim the forge opens the
5 * entries the rule allows (`environment.ts` `received`) and sends them in the claim's reply only,
6 * for that run; every log line a runner reports on the job goes through `maskFor` first.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import { masker, received, runnerTrusted, secretValues, type Lane } from "./environment.ts";
11 import type { RunnerJob } from "./runner_jobs.ts";
12
13 /**
14 * The job as the runner is sent it, with its environment's entries in `env`, and the log line
15 * saying which names.
16 */
17 export function withEnvironment(
18 db: Database,
19 dataDir: string,
20 job: RunnerJob,
21 runnerId: string,
22 ): { job: RunnerJob; said: string | undefined } {
23 if (job.environment === undefined) return { job, said: undefined };
24 const row = db.query<{ repo_id: string }, [string]>("SELECT repo_id FROM check_job WHERE id = ?1").get(job.id);
25 if (row === null) return { job, said: undefined };
26 const got = received(db, dataDir, { repoId: row.repo_id, env: job.environment, lane: (job.lane ?? "pull") as Lane, trusted: runnerTrusted(db, runnerId) });
27 const held = got.withheld.map((w) => `${w.name} (${w.why})`);
28 const said = `environment ${job.environment}: received ${got.names.length === 0 ? "nothing" : got.names.join(", ")}${held.length === 0 ? "" : `; withheld ${held.join("; ")}`}`;
29 // The job's own `CI` and `FORGE_*` come last: an entry never shadows them (`RESERVED`).
30 return { job: { ...job, env: { ...got.env, ...job.env } }, said };
31 }
32
33 /**
34 * A function that masks the secret values of the job's environment, or undefined when it holds
35 * none. It masks every secret the environment holds, not only those this runner was given: taking
36 * trust back or changing a scope while a job runs must not unmask what the runner already holds.
outdated

The mask set is re-derived from current trust and entries. Revoking trust or rotating the secret mid-run drops the value from the mask while the runner still holds it. Fix as in point 1.

37 * Values are opened again at each report, so nothing of them is kept in memory.
38 */
39 export function maskFor(db: Database, dataDir: string, job: RunnerJob | undefined, jobId: string): ((line: string) => string) | undefined {
40 if (job?.environment === undefined) return undefined;
41 const row = db.query<{ repo_id: string }, [string]>("SELECT repo_id FROM check_job WHERE id = ?1").get(jobId);
42 if (row === null) return undefined;
43 const secrets = secretValues(db, dataDir, row.repo_id, job.environment);
44 return secrets.length === 0 ? undefined : masker(secrets);
45 }
46
47 /**
48 * Where a check's commit came from: the default branch's own push is `main`, an outside
49 * contributor's pull is `fork`, every other is `pull`. Only `main` is sent secrets.
50 */
51 export function laneOf(input: { pull: boolean; keep: boolean; outside: boolean }): Lane {
52 if (input.outside) return "fork";
53 return !input.pull && input.keep ? "main" : "pull";
54 }
src/checks/runner_jobs.ts +12 −1
@@ -94,6 +94,13 @@ export interface RunnerJob {
9494 readonly hands?: readonly string[];
9595 /** The label `forge.json`'s check names: only a runner that holds it takes this job (#18037). */
9696 readonly label?: string;
97 /**
98 * The environment `forge.json` names (#18257): variables and secrets the runner is given at
99 * claim, never stored here (`environment.ts` `received`). `lane` is where the commit came from;
100 * absent is a pull's head, which is never given a secret.
101 */
102 readonly environment?: string;
103 readonly lane?: "main" | "pull" | "fork";
97104 }
98105
99106 /**
@@ -156,6 +163,8 @@ export interface Enrolled {
156163 readonly repos: readonly string[];
157164 /** What it last said in its heartbeat: `idle`, `busy` or `paused`; "" before one. */
158165 readonly state: string;
166 /** Whether a site admin marked it trusted for secrets (`environment.ts`). */
167 readonly trusted: boolean;
159168 }
160169
161170 type RunnerRow = {
@@ -176,8 +185,9 @@ type RunnerRow = {
176185 labels: string;
177186 repos: string;
178187 state: string;
188 trusted_at: number;
179189 };
180 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";
190 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";
181191
182192 /** A JSON array of strings as kept in a column; anything else is none. */
183193 const stringList = (raw: string): string[] => {
@@ -207,6 +217,7 @@ const toEnrolled = (r: RunnerRow, now: number = Date.now()): Enrolled => {
207217 labels: stringList(r.labels),
208218 repos: stringList(r.repos),
209219 state: r.state,
220 trusted: r.trusted_at > 0,
210221 };
211222 };
212223
src/checks/tier_runner.ts +3
@@ -12,6 +12,7 @@ import { capacityEnv, checkShardCpus, egressSetting, shardsInForce, shardsLine }
1212 import { resolveLimits, STEP_HOSTS } from "../apps/contain.ts";
1313 import { HANDED_OVER, runRunnerStep, runnerTakes, runnerVerdict, type RunnerRed } from "./runner_step.ts";
1414 import type { CheckOutcome } from "./runner.ts";
15 import { laneOf } from "./job_environment.ts";
1516 import type { LaneState } from "./lane_state.ts";
1617 import type { Execution } from "./local_runner.ts";
1718 import type { CheckManifest } from "../apps/manifest.ts";
@@ -170,6 +171,8 @@ export async function tryRunner(
170171 // Main's whole verification hands back what it measured (`runner_hands.ts`).
171172 ...(handsTimesBack(x) ? { hands: HAND_FILES } : {}),
172173 ...(label === "" ? {} : { label }),
174 ...(manifest.environment === undefined ? {} : { environment: manifest.environment }),
175 lane: laneOf({ pull: x.pull !== undefined, keep: x.keep === true, outside }),
173176 },
174177 log: write,
175178 output: lines,
src/contract/openapi/routes/deleteApiV1ReposOwnerNameEnvironmentsEnvEntry.ts added +12
@@ -0,0 +1,12 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "delete",
5 path: `${REPO}/environments/{env}/{entry}`,
6 summary: "Remove one environment entry",
7 detail: "Repository administrator, rw scope; 404 when there is no such entry or the caller does not administer the repository",
8 auth: true,
9 role: "member",
10 reply: {},
11 refuses: [401, 403, 404],
12 };
src/contract/openapi/routes/getApiV1ReposOwnerNameEnvironments.ts added +13
@@ -0,0 +1,13 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "get",
5 path: `${REPO}/environments`,
6 summary: "List a repository's environment entries: variables with values, secrets by name",
7 detail:
8 "The repository administrator's list: { entries: [{ env, name, kind var|secret, scope any|trusted, setBy, setAt, value (a variable only) }] }. A secret's value is never returned, here or anywhere; 404 for anyone who does not administer the repository",
9 auth: true,
10 role: "member",
11 reply: { entries: "array" },
12 refuses: [401, 404],
13 };
src/contract/openapi/routes/index.ts +4
@@ -31,6 +31,7 @@ export { route as deleteApiV1ReposOwnerNameDemo } from "./deleteApiV1ReposOwnerN
3131 export { route as deleteApiV1ReposOwnerNameDeskId } from "./deleteApiV1ReposOwnerNameDeskId.ts";
3232 export { route as deleteApiV1ReposOwnerNameDropFile } from "./deleteApiV1ReposOwnerNameDropFile.ts";
3333 export { route as deleteApiV1ReposOwnerNameEgressGrants } from "./deleteApiV1ReposOwnerNameEgressGrants.ts";
34 export { route as deleteApiV1ReposOwnerNameEnvironmentsEnvEntry } from "./deleteApiV1ReposOwnerNameEnvironmentsEnvEntry.ts";
3435 export { route as deleteApiV1ReposOwnerNameHooksId } from "./deleteApiV1ReposOwnerNameHooksId.ts";
3536 export { route as deleteApiV1ReposOwnerNameIssuesNumberDependenciesBlocker } from "./deleteApiV1ReposOwnerNameIssuesNumberDependenciesBlocker.ts";
3637 export { route as deleteApiV1ReposOwnerNameLabelsId } from "./deleteApiV1ReposOwnerNameLabelsId.ts";
@@ -203,6 +204,7 @@ export { route as getApiV1ReposOwnerNameDesk } from "./getApiV1ReposOwnerNameDes
203204 export { route as getApiV1ReposOwnerNameDrop } from "./getApiV1ReposOwnerNameDrop.ts";
204205 export { route as getApiV1ReposOwnerNameDropFile } from "./getApiV1ReposOwnerNameDropFile.ts";
205206 export { route as getApiV1ReposOwnerNameEgressGrants } from "./getApiV1ReposOwnerNameEgressGrants.ts";
207 export { route as getApiV1ReposOwnerNameEnvironments } from "./getApiV1ReposOwnerNameEnvironments.ts";
206208 export { route as getApiV1ReposOwnerNameEvents } from "./getApiV1ReposOwnerNameEvents.ts";
207209 export { route as getApiV1ReposOwnerNameFamily } from "./getApiV1ReposOwnerNameFamily.ts";
208210 export { route as getApiV1ReposOwnerNameFlags } from "./getApiV1ReposOwnerNameFlags.ts";
@@ -367,6 +369,7 @@ export { route as postApiV1AdminRunners } from "./postApiV1AdminRunners.ts";
367369 export { route as postApiV1AdminRunnersIdPause } from "./postApiV1AdminRunnersIdPause.ts";
368370 export { route as postApiV1AdminRunnersIdResume } from "./postApiV1AdminRunnersIdResume.ts";
369371 export { route as postApiV1AdminRunnersIdRevoke } from "./postApiV1AdminRunnersIdRevoke.ts";
372 export { route as postApiV1AdminRunnersIdTrust } from "./postApiV1AdminRunnersIdTrust.ts";
370373 export { route as postApiV1Agents } from "./postApiV1Agents.ts";
371374 export { route as postApiV1Apps } from "./postApiV1Apps.ts";
372375 export { route as postApiV1AppsOwnerNameCrashReports } from "./postApiV1AppsOwnerNameCrashReports.ts";
@@ -569,6 +572,7 @@ export { route as putApiV1ReposOwnerNameAppRegistryItem } from "./putApiV1ReposO
569572 export { route as putApiV1ReposOwnerNameCrewUsername } from "./putApiV1ReposOwnerNameCrewUsername.ts";
570573 export { route as putApiV1ReposOwnerNameDemo } from "./putApiV1ReposOwnerNameDemo.ts";
571574 export { route as putApiV1ReposOwnerNameDisplayBuilds } from "./putApiV1ReposOwnerNameDisplayBuilds.ts";
575 export { route as putApiV1ReposOwnerNameEnvironmentsEnvEntry } from "./putApiV1ReposOwnerNameEnvironmentsEnvEntry.ts";
572576 export { route as putApiV1ReposOwnerNameFlagsFlag } from "./putApiV1ReposOwnerNameFlagsFlag.ts";
573577 export { route as putApiV1ReposOwnerNameIssuesNumberAssignee } from "./putApiV1ReposOwnerNameIssuesNumberAssignee.ts";
574578 export { route as putApiV1ReposOwnerNameIssuesNumberLabels } from "./putApiV1ReposOwnerNameIssuesNumberLabels.ts";
src/contract/openapi/routes/postApiV1AdminRunnersIdTrust.ts added +16
@@ -0,0 +1,16 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: "/api/v1/admin/runners/{id}/trust",
6 summary: "Mark a runner trusted for secrets, or take that back",
7 detail:
8 "Admin scope: { trusted: boolean }. Only a trusted runner is given a secret, and only for a job on main; it records who set it and when. 422 local for the forge's own local-N runner; 404 when there is none",
9 auth: true,
10 role: "admin",
11 body: { trusted: "boolean" },
12 reply: { id: "string", name: "string", trusted: "boolean" },
13 refuses: [404],
14 errorStatus: { 422: "the runner is the forge's own (local)" },
15 refusals: { local: "a local-N runner is the forge's own; trust is for other machines" },
16 };
src/contract/openapi/routes/putApiV1ReposOwnerNameEnvironmentsEnvEntry.ts added +15
@@ -0,0 +1,15 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "put",
5 path: `${REPO}/environments/{env}/{entry}`,
6 summary: "Set one environment entry: a variable or a sealed, write-only secret",
7 detail:
8 "Repository administrator, rw scope. kind var or secret; scope any (any runner) or trusted (trusted runners only): a variable defaults to any, a secret to trusted, and a secret for any runner needs confirm set to its own name. A secret is sealed and never read back; a job receives it only on main and only on a runner a site admin marked trusted. 422 bad_env, bad_name, reserved, bad_kind, bad_scope, bad_value, too_many, confirm",
9 auth: true,
10 role: "member",
11 body: { kind: "string", value: "string", scope: "string", confirm: "string" },
12 reply: { env: "string", name: "string", kind: "string", scope: "string" },
13 refuses: [401, 403, 404],
14 errorStatus: { 422: "the environment, name, kind, scope or value is invalid, or a secret for any runner lacks its confirm" },
15 };
src/contract/tags.ts +1
@@ -122,6 +122,7 @@ const ALIAS: Readonly<Record<string, string>> = {
122122 deepsec: "reports",
123123 status: "reports",
124124 envelope: "apps",
125 environments: "apps",
125126 otlp: "apps",
126127 dependencies: "repos",
127128 };
src/core/account_purge.ts +6
@@ -78,6 +78,8 @@ export const COVERED: Readonly<Record<string, Coverage>> = {
7878 "crew_device.granted_by": FORMER,
7979 "degraded_span.touched_by": { do: "none", why: "a username, not an id: `purgeAccount` rewrites it to the placeholder's name" },
8080 "dep_accept.by_name": { do: "none", why: "a username, not an id: `purgeAccount` rewrites it to the placeholder's name" },
81 "repo_env.set_by": { do: "none", why: "a username, not an id: `purgeAccount` rewrites it to the placeholder's name" },
82 "check_runner.trusted_by": { do: "none", why: "a username, not an id: `purgeAccount` rewrites it to the placeholder's name" },
8183 "repo_review.by": FORMER,
8284 "review_request.requested_by": FORMER,
8385 "review_request.reviewer_id": FORMER,
@@ -396,6 +398,10 @@ export function purgeAccount(db: Database, userId: string, now: Date, dataDir =
396398 // `dep_accept.by_name` holds a username: an accepted advisory keeps its reason, as the
397399 // placeholder's.
398400 if (name !== "") kept += db.query("UPDATE dep_accept SET by_name = ?2 WHERE by_name = ?1").run(name, FORMER_NAME).changes;
401 // `repo_env.set_by` and `check_runner.trusted_by` hold usernames: the entry and the trust stay,
402 // as the former account's.
403 if (name !== "") kept += db.query("UPDATE repo_env SET set_by = ?2 WHERE set_by = ?1").run(name, FORMER_NAME).changes;
404 if (name !== "") kept += db.query("UPDATE check_runner SET trusted_by = ?2 WHERE trusted_by = ?1").run(name, FORMER_NAME).changes;
399405 // `entitlement.payer` is an address, not an id: an ended plan forgets who paid.
400406 const email = db.query<{ email: string }, [string]>("SELECT email FROM user WHERE id = ?1").get(userId)?.email ?? "";
401407 if (email !== "") kept += db.query("UPDATE entitlement SET payer = '' WHERE payer = ?1 COLLATE NOCASE").run(email).changes;
src/core/event_audience.ts +2
@@ -267,6 +267,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined {
267267 kind.startsWith("drill.") ||
268268 // Which machines take this forge's checks is its admin's (`actions/runners.ts`).
269269 kind.startsWith("runner.") ||
270 // An environment entry set or removed is its repo admin's (`actions/environments.ts`).
271 kind.startsWith("environment.") ||
270272 // A shell on a game box and everything it said: its owner's, the forge admin's (`games/shell.ts`).
271273 kind.startsWith("game.shell.") ||
272274 // A mod set installed on or taken back from a server: the admins' record
src/core/migration-pins/20261204140000-repo-environment.pin added +1
@@ -0,0 +1,1 @@
1 6a14070facc2abe77ad1f56755a766e90f3d5443d799d303f93a031a111a8d01
src/core/migrations/20261204140000-repo-environment.ts added +19
@@ -0,0 +1,19 @@
1 // Environments (#18257): a repository's named sets of variables (plain) and secrets (sealed,
2 // write-only), each entry saying who may receive it: 'any' runner or 'trusted' runners only. And
3 // the runner side: who marked a runner trusted for secrets, and when ('' / 0 for untrusted).
4 // Additive.
5 export default `
6 CREATE TABLE repo_env (
7 repo_id TEXT NOT NULL,
8 env TEXT NOT NULL,
9 name TEXT NOT NULL,
10 kind TEXT NOT NULL CHECK (kind IN ('var', 'secret')),
11 value TEXT NOT NULL,
12 scope TEXT NOT NULL CHECK (scope IN ('any', 'trusted')),
13 set_by TEXT NOT NULL,
14 set_at INTEGER NOT NULL,
15 PRIMARY KEY (repo_id, env, name)
16 );
17 ALTER TABLE check_runner ADD COLUMN trusted_by TEXT NOT NULL DEFAULT '';
18 ALTER TABLE check_runner ADD COLUMN trusted_at INTEGER NOT NULL DEFAULT 0;
19 `;
src/core/repos.ts +1
@@ -1364,6 +1364,7 @@ async function removeRepo(
13641364 // the repository gone no page could remove them, and they would stay sealed
13651365 // in the index and in every backup of it.
13661366 db.query("DELETE FROM secret WHERE scope = 'repo' AND scope_id = ?1").run(repo.id);
1367 db.query("DELETE FROM repo_env WHERE repo_id = ?1").run(repo.id);
13671368 forgetAppFilters(db, repo.id);
13681369 db.query("DELETE FROM repo WHERE id = ?1").run(repo.id);
13691370 forgetRepoCursors(db, repo.id);
src/http/api.ts +2
@@ -349,6 +349,7 @@ import { tokenRoutes } from "./api/tokens.ts";
349349 import { accountAdmin, adminRoutes } from "./api/admin.ts";
350350 import { arcadeRoutes } from "./api/arcade.ts";
351351 import { runnerRoutes } from "./api/runners.ts";
352 import { environmentRoutes } from "./api/environments.ts";
352353 import { maintenanceRoutes } from "./api/maintenance.ts";
353354 import { maintenanceRunsRoutes } from "./api/maintenance_runs.ts";
354355 import { diskReadingRoutes } from "./api/disk_readings.ts";
@@ -1294,6 +1295,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
12941295 forgeOriginRoutes(router);
12951296 adminRoutes(router);
12961297 runnerRoutes(router);
1298 environmentRoutes(router);
12971299 arcadeRoutes(router);
12981300 gamesApiRoutes(router);
12991301 maintenanceRoutes(router);
src/http/api/environments.ts added +76
@@ -0,0 +1,76 @@
1 /**
2 * A repository's environments over the API (#18257): list (variables with values, secrets by
3 * name only), set one entry, remove one; and a runner's trust for secrets. Entries are the
4 * repository administrator's; trust is a site admin's. No route returns a secret's value.
5 */
6
7 import { removeEnvironmentEntry, setEnvironmentEntry, setRunnerTrust } from "../../actions/environments.ts";
8 import { ENTRY_RE, ENV_RE, listEntries, MAX_ENTRIES, VALUE_MAX } from "../../checks/environment.ts";
9 import { canAdmin } from "../../core/repos.ts";
10 import type { Handler } from "../context.ts";
11 import { apiError, body, json, notFound, requireScope, str } from "../respond.ts";
12 import type { Router } from "../router.ts";
13 import { loadRepo } from "../api.ts";
14 import { accountAdmin } from "./admin.ts";
15
16 const SAID = {
17 bad_env: "the environment is a lower-case name: letters, digits and -, at most 32",
18 bad_name: "the name is letters, digits and _, at most 64, not starting with a digit",
19 reserved: "CI, FORGE_*, PATH, HOME, BUN_*, NODE_*, LD_*, DYLD_*, GIT_*, SSH_* and the shell's own variables are set by the forge itself",
20 bad_value: `the value is at most ${VALUE_MAX} bytes, and a secret is at least 4 characters`,
21 too_many: `a repository holds at most ${MAX_ENTRIES} entries`,
22 confirm: "a secret for any runner needs confirm set to the secret's own name",
23 } as const;
24
25 export function environmentRoutes(router: Router<Handler>): void {
26 router.add("GET", "/api/v1/repos/:owner/:name/environments", (ctx) => {
27 const denied = requireScope(ctx, "ro");
28 if (denied) return denied;
29 const repo = loadRepo(ctx);
30 if (repo === undefined || !canAdmin(ctx.app.db, repo, ctx.auth.user)) return notFound();
31 return json({ entries: listEntries(ctx.app.db, repo.id) });
32 });
33
34 router.add("PUT", "/api/v1/repos/:owner/:name/environments/:env/:entry", async (ctx) => {
35 const denied = requireScope(ctx, "rw");
36 if (denied) return denied;
37 const repo = loadRepo(ctx);
38 if (repo === undefined) return notFound();
39 const env = ctx.params.env!;
40 const name = ctx.params.entry!;
41 if (!ENV_RE.test(env)) return apiError("bad_env", 422, SAID.bad_env);
42 if (!ENTRY_RE.test(name)) return apiError("bad_name", 422, SAID.bad_name);
43 const input = await body(ctx.request);
44 if (input.kind !== "var" && input.kind !== "secret") return apiError("bad_kind", 422, "kind is var or secret");
45 if (input.scope !== undefined && input.scope !== "any" && input.scope !== "trusted") return apiError("bad_scope", 422, "scope is any or trusted");
46 if (typeof input.value !== "string") return apiError("bad_value", 422, SAID.bad_value);
47 const done = setEnvironmentEntry(ctx.app, ctx.auth.user, repo, {
48 env,
49 name,
50 kind: input.kind,
51 value: input.value,
52 ...(input.scope === undefined ? {} : { scope: input.scope }),
53 confirm: str(input.confirm),
54 });
55 if (done.ok) return json({ env, name, kind: input.kind, scope: done.value.scope });
56 return done.error === "not_found" ? notFound() : apiError(done.error, 422, SAID[done.error]);
57 });
58
59 router.add("DELETE", "/api/v1/repos/:owner/:name/environments/:env/:entry", (ctx) => {
60 const denied = requireScope(ctx, "rw");
61 if (denied) return denied;
62 const repo = loadRepo(ctx);
63 if (repo === undefined) return notFound();
64 return removeEnvironmentEntry(ctx.app, ctx.auth.user, repo, ctx.params.env!, ctx.params.entry!).ok ? json({}) : notFound();
65 });
66
67 router.add("POST", "/api/v1/admin/runners/:id/trust", async (ctx) => {
68 const denied = accountAdmin(ctx, "admin");
69 if (denied) return denied;
70 const input = await body(ctx.request);
71 if (typeof input.trusted !== "boolean") return apiError("bad_trusted", 422, "trusted is true or false");
72 const done = setRunnerTrust(ctx.app, ctx.auth.user, ctx.params.id!, input.trusted);
73 if (done.ok) return json(done.value);
74 return done.error === "local" ? apiError("local", 422, "a local-N runner is the forge's own; trust is for other machines") : notFound();
75 });
76 }
src/http/api/runners.ts +13 −5
@@ -24,6 +24,7 @@ import {
2424 holdForAdoption,
2525 holdsClaim,
2626 jobByToken,
27 jobSpec,
2728 nextOffer,
2829 interruptJob,
2930 noteHeartbeat,
@@ -38,6 +39,7 @@ import {
3839 type RunnerResult,
3940 } from "../../checks/runner_jobs.ts";
4041 import { keepPause, pauseWords, readPause } from "../../checks/lent_pause.ts";
42 import { maskFor, withEnvironment } from "../../checks/job_environment.ts";
4143 import { readSeed } from "../../checks/runner_seeds.ts";
4244 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
4345 import { buildOf } from "../../kernel/version.ts";
@@ -67,7 +69,7 @@ const bearer = (request: Request): string =>
6769 const lease = { seconds: LEASE_MS / 1000 };
6870
6971 /** A report's result, read field by field: nothing a runner sends is kept as it came. */
70 function readResult(raw: unknown): RunnerResult | undefined {
72 function readResult(raw: unknown, mask: (line: string) => string = (l) => l): RunnerResult | undefined {
7173 if (typeof raw !== "object" || raw === null) return undefined;
7274 const from = raw as Record<string, unknown>;
7375 if (!Array.isArray(from.steps) || from.steps.length > 8) return undefined;
@@ -84,7 +86,7 @@ function readResult(raw: unknown): RunnerResult | undefined {
8486 name: s.name.slice(0, 40),
8587 ok: s.ok,
8688 ...(typeof s.error === "string"
87 ? { error: s.error.slice(0, 2_000) }
89 ? { error: mask(s.error.slice(0, 2_000)) }
8890 : {}),
8991 ms:
9092 typeof s.ms === "number" && Number.isFinite(s.ms)
@@ -95,7 +97,7 @@ function readResult(raw: unknown): RunnerResult | undefined {
9597 return {
9698 steps,
9799 contained: from.contained === true,
98 note: str(from.note).slice(0, 200),
100 note: mask(str(from.note).slice(0, 200)),
99101 };
100102 }
101103
@@ -273,8 +275,11 @@ export function runnerRoutes(router: Router<Handler>): void {
273275 );
274276 if (claim !== undefined) {
275277 if (claim.canary === true) hearCanary(ctx.app, claim.job.id);
278 // The environment's entries are opened here, for this run only, and named in its log.
279 const given = withEnvironment(ctx.app.db, ctx.app.config.dataDir, claim.job, runner.id);
280 if (given.said !== undefined) deskOf(ctx.app).ears.get(claim.job.id)?.lines("", [given.said]);
276281 deskOf(ctx.app).ears.get(claim.job.id)?.wake();
277 return json({ job: claim.job, token: claim.token, lease }, 200, { [RUNNER_VERSION_HEADER]: buildOf() });
282 return json({ job: given.job, token: claim.token, lease }, 200, { [RUNNER_VERSION_HEADER]: buildOf() });
278283 }
279284 const left = until - Date.now();
280285 if (left <= 0 || stop.aborted)
@@ -323,10 +328,13 @@ export function runnerRoutes(router: Router<Handler>): void {
323328 // below is bound to it.
324329 const token = bearer(ctx.request);
325330 if (!holdsClaim(ctx.app.db, mine.job.id, token)) return notFound();
331 // A secret the job was given never reaches the log: masked before anything keeps a line.
332 const masked = maskFor(ctx.app.db, ctx.app.config.dataDir, jobSpec(ctx.app.db, mine.job.id), mine.job.id) ?? ((l: string) => l);
326333 const lines = Array.isArray(input.lines)
327334 ? input.lines
328335 .filter((l): l is string => typeof l === "string")
329336 .slice(0, LINES_MAX)
337 .map(masked)
330338 : [];
331339 if (lines.length > 0) mine.ear.lines(str(input.step), lines);
332340 // A join froze a lent job (#17950): kept with its gap, said once in the check's log. Not a
@@ -345,7 +353,7 @@ export function runnerRoutes(router: Router<Handler>): void {
345353 return json({ ended: true });
346354 }
347355 if (input.done !== undefined) {
348 const result = readResult(input.done);
356 const result = readResult(input.done, masked);
349357 if (result === undefined)
350358 return apiError(
351359 "invalid_result",
src/http/lazy_lists.ts +6
@@ -31,6 +31,8 @@ export const SETTINGS_ROUTES = [
3131 ["POST", "/settings/runners/:id/revoke"],
3232 ["POST", "/settings/runners/:id/resume"],
3333 ["POST", "/settings/runners/:id/pause"],
34 ["POST", "/settings/runners/:id/trust"],
35 ["POST", "/settings/runners/:id/untrust"],
3436 ["POST", "/settings/runners/register"],
3537 ["GET", "/settings/runners/lending/live"],
3638 ["POST", "/settings/runners/lending"],
@@ -1344,6 +1346,10 @@ export const API_ROUTES = [
13441346 ["POST", "/api/v1/runner/jobs/:id/hand"],
13451347 ["GET", "/api/v1/runner/jobs/:id/git/info/refs"],
13461348 ["POST", "/api/v1/runner/jobs/:id/git/git-upload-pack"],
1349 ["GET", "/api/v1/repos/:owner/:name/environments"],
1350 ["PUT", "/api/v1/repos/:owner/:name/environments/:env/:entry"],
1351 ["DELETE", "/api/v1/repos/:owner/:name/environments/:env/:entry"],
1352 ["POST", "/api/v1/admin/runners/:id/trust"],
13471353 ["GET", "/api/v1/arcade/games"],
13481354 ["POST", "/api/v1/games/agent/sync"],
13491355 ["GET", "/api/v1/games/agent/script"],
src/http/marks/settings.json +2
@@ -7,6 +7,8 @@
77 "/settings/trusted/revert": "admin",
88 "/settings/trusted/:id/remove": "admin",
99 "/settings/runners": "open",
10 "/settings/runners/:id/trust": "admin",
11 "/settings/runners/:id/untrust": "admin",
1012 "/settings/runners/:id/remove": "open",
1113 "/settings/runners/:id/revoke": "open",
1214 "/settings/runners/:id/resume": "open",
src/http/settings_routes.ts +3 −1
@@ -25,7 +25,7 @@ import { paymentsCsv, paymentsPage } from "../web/pages/payments.ts";
2525 import { billingPage, billingChange, billingGrant, billingSetLinks, billingSetPortal, billingMakeCode, billingRevokeCode, stripeConnect, stripeDisconnect, stripeSecret, orderRetry } from "../web/pages/billing.ts";
2626 import { economicsPage, economicsSet } from "../web/pages/economics.ts";
2727 import { trustedAdd, trustedPage, trustedRemove, trustedRevert, trustedStop } from "../web/pages/trusted.ts";
28 import { lendingLive, lendingOffer, lendingResume, lendingStop, lendingStopNow, runnerPause, runnerRegister, runnerRemove, runnerResume, runnerRevoke, runnersPage } from "../web/pages/runners.ts";
28 import { lendingLive, lendingOffer, lendingResume, lendingStop, lendingStopNow, runnerPause, runnerRegister, runnerRemove, runnerResume, runnerRevoke, runnerTrust, runnersPage } from "../web/pages/runners.ts";
2929 import { usagePage } from "../web/pages/usage.ts";
3030 import { spendPage } from "../web/pages/spend-tab.ts";
3131 import { securityControlsPage } from "../web/pages/security_controls.ts";
@@ -179,6 +179,8 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
179179 router.add("POST", "/settings/runners/:id/revoke", runnerRevoke);
180180 router.add("POST", "/settings/runners/:id/resume", runnerResume);
181181 router.add("POST", "/settings/runners/:id/pause", runnerPause);
182 router.add("POST", "/settings/runners/:id/trust", runnerTrust(true));
183 router.add("POST", "/settings/runners/:id/untrust", runnerTrust(false));
182184 router.add("POST", "/settings/runners/register", runnerRegister);
183185 router.add("GET", "/settings/runners/lending/live", lendingLive);
184186 router.add("POST", "/settings/runners/lending", lendingOffer);
src/tui/screens/environments.ts added +112
@@ -0,0 +1,112 @@
1 /**
2 * A repository's environments in the terminal (#18257), its administrator's: each entry by name,
3 * kind and who may receive it, never a secret's value; `a` sets one (a secret's value is asked in
4 * a masked prompt of its own), `x` removes the one under the cursor. The same actions as the API,
5 * refused in the same words.
6 */
7
8 import { removeEnvironmentEntry, setEnvironmentEntry } from "../../actions/environments.ts";
9 import { listEntries, type EntryKind, type EntryName, type SetError } from "../../checks/environment.ts";
10 import { canAdmin, type Repo } from "../../core/repos.ts";
11 import type { Ctx, Screen } from "../app/app.ts";
12 import { binding } from "../app/keys.ts";
13 import type { Command } from "../app/palette.ts";
14 import { style } from "../term/style.ts";
15 import { truncate } from "../term/width.ts";
16 import { fill, len, split } from "../ui/layout.ts";
17 import type { Session } from "../session.ts";
18 import { ListState, drawList, promptScreen, type ListRow } from "./common.ts";
19
20 const SAID: Record<SetError, string> = {
21 bad_env: "The environment is a lower-case name: letters, digits and -, at most 32.",
22 bad_name: "The name is letters, digits and _, at most 64, not starting with a digit.",
23 reserved: "That name is set by the forge itself (CI, FORGE_*, PATH, NODE_*, LD_*, GIT_* …).",
24 bad_value: "The value is at most 16 KiB, and a secret is at least 4 characters.",
25 too_many: "A repository holds at most 64 entries.",
26 confirm: "A secret for any runner needs its name typed as confirmation.",
27 };
28
29 /** The palette's "Environments", for an admin of a repository. */
30 export function environmentCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
31 if (repo === undefined || f.user === undefined || !canAdmin(f.app.db, repo, f.user)) return [];
32 return [
33 {
34 id: "environments",
35 title: `${repo.ownerName}/${repo.name} — Environments`,
36 hint: "variables and sealed secrets a check receives",
37 run: () => ctx.push(environmentsScreen(f, ctx, repo)),
38 },
39 ];
40 }
41
42 export function environmentsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
43 const state = new ListState();
44 const entries = (): EntryName[] => (f.user !== undefined && canAdmin(f.app.db, repo, f.user) ? listEntries(f.app.db, repo.id) : []);
45
46 const add = (): void => {
47 ctx.push(
48 promptScreen(ctx, screen, {
49 title: "Set an entry",
50 label: "Environment, name, and var or secret",
51 placeholder: "testflight ASC_KEY secret",
52 hint: "A secret is asked for next, hidden, and is never shown again.",
53 onSubmit: (value) => {
54 const [env, name, kind] = value.trim().split(/\s+/);
55 if (env === undefined || name === undefined || (kind !== "var" && kind !== "secret")) return "Three words: the environment, the name, and var or secret";
56 return Promise.resolve().then(() =>
57 ctx.push(
58 promptScreen(ctx, screen, {
59 title: `${env} ${name}`,
60 label: kind === "secret" ? "The secret's value" : "The variable's value",
61 placeholder: "",
62 mask: kind === "secret",
63 onSubmit: (v) => {
64 const done = setEnvironmentEntry(f.app, f.user, repo, { env, name, kind: kind as EntryKind, value: v });
65 if (!done.ok) return done.error === "not_found" ? "Only the repository's admin sets entries." : SAID[done.error];
66 ctx.toast(`${name} is set in ${env}.`, "success");
67 ctx.invalidate();
68 return undefined;
69 },
70 }),
71 ),
72 );
73 },
74 }),
75 );
76 };
77
78 const screen: Screen = {
79 title: "Environments",
80 keys: [binding(["j", "k"], "move cursor"), binding(["a"], "set an entry"), binding(["x"], "remove the entry")],
81 render(area, s) {
82 const c = ctx.theme.c;
83 const all = entries();
84 const [head, body] = split(area, "v", [len(1), fill(1)]);
85 const text = all.length === 0 ? "No entry yet; a sets one." : `${all.length} for ${repo.ownerName}/${repo.name}; a secret's value is never shown.`;
86 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
87 const rows: ListRow[] = all.map((e) => ({
88 title: `${e.env} ${e.name}`,
89 meta: `${e.kind}${e.value === undefined ? "" : ` = ${truncate(e.value, 40)}`} · ${e.scope === "trusted" ? "trusted runners only" : "any runner"} · set by ${e.setBy}`,
90 }));
91 drawList(s, body!, c, state, rows);
92 },
93 key(e) {
94 const all = entries();
95 if (state.key(e, all.length)) return true;
96 if (e.ctrl || e.alt) return false;
97 if (e.key === "a") {
98 add();
99 return true;
100 }
101 const at = all[state.index];
102 if (e.key === "x" && at !== undefined) {
103 const done = removeEnvironmentEntry(f.app, f.user, repo, at.env, at.name);
104 ctx.toast(done.ok ? `${at.name} is removed from ${at.env}.` : "That entry is not there.", done.ok ? "success" : "danger");
105 ctx.invalidate();
106 return true;
107 }
108 return false;
109 },
110 };
111 return screen;
112 }
src/tui/screens/runners.ts +10 −1
@@ -6,6 +6,7 @@
66 * offered it.
77 */
88
9 import { setRunnerTrust } from "../../actions/environments.ts";
910 import { enrol, list, pause, removeHandMade, resume, revoke, runnerState } from "../../actions/runners.ts";
1011 import { isLocal } from "../../checks/runner_pool.ts";
1112 import { listLending, offerLending, resumeLending, stopLending, type LendView } from "../../actions/lending.ts";
@@ -77,7 +78,7 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen {
7778 const machine = runnerMachineWords(r);
7879 const asked = r.seenAt === 0 ? "has not asked for work" : `last asked ${new Date(r.seenAt).toISOString().slice(0, 16).replace("T", " ")}`;
7980 return {
80 title: `${r.name} ${stateWords(r, now)}${isLocal(r) ? " (the forge's own)" : ""}`,
81 title: `${r.name} ${stateWords(r, now)}${r.trusted ? " trusted for secrets" : ""}${isLocal(r) ? " (the forge's own)" : ""}`,
8182 meta: `${asked}${machine === "" ? "" : ` · ${machine}`}${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)}` : ""}`,
8283 // Under the row, where a narrow screen never gives it up as it does the meta's pieces.
8384 ...(proofs.has(r.id) ? { note: proofWords(proofs.get(r.id)) } : {}),
@@ -176,6 +177,7 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen {
176177 keys: [
177178 binding(["j", "k"], "move cursor"),
178179 binding(["x"], "revoke or remove a runner"),
180 binding(["t"], "trust or untrust for secrets"),
179181 binding(["p"], "pause"),
180182 binding(["u"], "resume"),
181183 binding(["n"], "register an outside runner"),
@@ -212,6 +214,13 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen {
212214 const picked = all[state.index];
213215 if (picked?.kind === "offer") return e.key === "s" || e.key === "S" || e.key === "u" ? onOffer(picked.o, e.key) : false;
214216 const at = picked?.r;
217 if (at !== undefined && e.key === "t") {
218 const done = setRunnerTrust(f.app, f.user, at.id, !at.trusted);
219 const why = { local: `${at.name} is the forge's own; trust is for machines it does not own.`, not_found: "That runner is not enrolled." };
220 ctx.toast(done.ok ? (done.value.trusted ? `Runner ${at.name} is sent a main job's secrets.` : `Runner ${at.name} is sent no secrets.`) : why[done.error], done.ok ? "success" : "danger");
221 ctx.invalidate();
222 return true;
223 }
215224 if (at === undefined || (e.key !== "x" && e.key !== "u" && e.key !== "p")) return false;
216225 if (e.key === "p") {
217226 const held = pause(f.app, f.user, at.id, "paused in the terminal");
src/tui/screens/workspace.ts +2
@@ -154,6 +154,7 @@ import { iterationsCommands } from "./iterations.ts";
154154 import { labelsCommands } from "./labels.ts";
155155 import { appEnvCommands } from "./appenv.ts";
156156 import { appSecretCommands } from "./appsecrets.ts";
157 import { environmentCommands } from "./environments.ts";
157158 import { appFlagCommands } from "./appflags.ts";
158159 import { appRegistryCommands } from "./appregistry.ts";
159160 import { changesCommands } from "./app_changes.ts";
@@ -1405,6 +1406,7 @@ export function workspaceScreen(
14051406 ...displayCommands(f, ctx, repo),
14061407 ...appEnvCommands(f, ctx, repo),
14071408 ...appSecretCommands(f, ctx, repo),
1409 ...environmentCommands(f, ctx, repo),
14081410 ...appFlagCommands(f, ctx, repo),
14091411 ...appRegistryCommands(f, ctx, repo),
14101412 ...changesCommands(f, ctx, repo),
src/web/pages/runners.ts +19 −1
@@ -9,6 +9,7 @@
99 * check answers rather than the admin gate's 403.
1010 */
1111 import { listLending, offerLending, resumeLending, stopLending, type LendView } from "../../actions/lending.ts";
12 import { setRunnerTrust } from "../../actions/environments.ts";
1213 import { enrol, list, pause, removeHandMade, resume, revoke, runnerState } from "../../actions/runners.ts";
1314 import { isLocal } from "../../checks/runner_pool.ts";
1415 import { proofByRunner, proofWords } from "../../games/lent_proof.ts";
@@ -46,7 +47,7 @@ function runnerTrail(r: Enrolled) {
4647 ${btn(label, { size: "sm", variant: "outline", label: `${label} runner ${r.name}` })}
4748 </form>`;
4849 if ((r.scope === undefined && r.labels.length === 0) || r.revokedAt !== 0) return form("remove", "Remove");
49 return html`${r.paused === "" ? form("pause", "Pause") : form("resume", "Resume")}${form("revoke", "Revoke")}`;
50 return html`${r.trusted ? form("untrust", "Untrust") : form("trust", "Trust")}${r.paused === "" ? form("pause", "Pause") : form("resume", "Resume")}${form("revoke", "Revoke")}`;
5051 }
5152
5253 function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number, cannot: string, proof: string) {
@@ -305,6 +306,23 @@ export async function runnerRevoke(ctx: Ctx): Promise<Response> {
305306 );
306307 }
307308
309 // POST /settings/runners/:id/trust and /untrust: whether it is sent secrets
310 // (docs/features/environments.md)
311 export const runnerTrust = (trusted: boolean) => async (ctx: Ctx): Promise<Response> => {
312 const denied = admin(ctx);
313 if (denied) return denied;
314 const form = await readForm(ctx, "admin");
315 if (form instanceof Response) return form;
316 const done = setRunnerTrust(ctx.app, ctx.auth.user, ctx.params.id ?? "", trusted);
317 return flashTo(
318 ctx,
319 HERE,
320 done.ok
321 ? { message: trusted ? `Runner ${done.value.name} is sent a main job's secrets from its next claim.` : `Runner ${done.value.name} is sent no secrets from now on.` }
322 : { tone: "danger", message: done.error === "local" ? "That runner is the forge's own; trust is for machines it does not own." : "That runner is not enrolled." },
323 );
324 };
325
308326 // POST /settings/runners/:id/resume
309327 export async function runnerResume(ctx: Ctx): Promise<Response> {
310328 const denied = admin(ctx);
test/data-browser.test.ts +3
@@ -65,6 +65,9 @@ const AUDITED_CLEAR: string[] = [
6565 "payment.currency",
6666 "probe.said",
6767 "prompt_source.last_said",
68 // A variable (not a secret) is kept in the clear; a secret is sealed before it is stored
69 // (`checks/environment.ts`).
70 "repo_env.value",
6871 "repo_upstream_check.detail",
6972 "report.body",
7073 "review.body",
test/environments-masks.test.ts added +167
@@ -0,0 +1,167 @@
1 /**
2 * What an environment's log and cleanup hold to (#18257): a secret never reaches a stored line,
3 * whatever happened to the runner's trust meanwhile, multi-line and encoded secrets are masked
4 * line by line, the claim's log says what was received and withheld, a trusted-only variable is
5 * withheld from an untrusted runner, and a repository's entries and a person's names go cleanly.
6 */
7 import { beforeAll, describe, expect, test } from "bun:test";
8 import { deleteRepo } from "../src/core/repos.ts";
9 import { createRepo } from "../src/actions/repos.ts";
10 import { deskOf, enrolRunner, offerJob, viewJob, type RunnerJob } from "../src/checks/runner_jobs.ts";
11 import { setEntry, mask, trustRunner } from "../src/checks/environment.ts";
12 import { laneOf, withEnvironment } from "../src/checks/job_environment.ts";
13 import { purgeAccount } from "../src/core/account_purge.ts";
14 import { createRun } from "../src/core/runs.ts";
15 import { checksForge } from "./helpers/checks-forge.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19
20 const f = checksForge("forge-env-masks-");
21 const KEY = "p8-key-material-123";
22 const D = "-".repeat(5); // spelled in pieces so the tree scan does not flag this file
23 const PEM = `${D}BEGIN PRIVATE KEY${D}\nMIGTAgEAMBMGByqGSM49\n${D}END PRIVATE KEY${D}`;
24
25 beforeAll(async () => {
26 await f.checks.stop();
27 });
28
29 const set = (name: string, value: string, kind: "var" | "secret" = "secret", scope?: "any" | "trusted"): void => {
30 expect(setEntry(f.app.db, f.dataDir, f.repo.id, { env: "testflight", name, kind, value, ...(scope === undefined ? {} : { scope }), by: "alice" }, 1)).toBeUndefined();
31 };
32
33 function offer(lane: RunnerJob["lane"]): string {
34 const run = createRun(f.app.db, { repoId: f.repo.id, kind: "check", env: "main", commitOid: "a".repeat(40) });
35 return offerJob(f.app.db, {
36 runId: run.id,
37 repoId: f.repo.id,
38 dir: f.dataDir,
39 job: {
40 run: run.id,
41 repo: "alice/lib",
42 commit: "a".repeat(40),
43 depth: 1,
44 steps: [{ name: "check", command: "true" }],
45 env: { CI: "true" },
46 limits: {},
47 timeoutS: 60,
48 egress: [],
49 egressMode: "report",
50 cell: "preferred",
51 cache: { repo: f.repo.id, tree: "", base: "" },
52 environment: "testflight",
53 ...(lane === undefined ? {} : { lane }),
54 },
55 }).id;
56 }
57
58 const post = (path: string, token: string, body: unknown): Promise<Response> =>
59 fetch(`${f.servers.url}${path}`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify(body) });
60
61 /** A trusted runner holding a main job whose lines the test hears. */
62 async function holding(name: string): Promise<{ id: string; token: string; heard: string[]; runnerId: string }> {
63 f.app.db.query("DELETE FROM check_job").run();
64 const id = offer("main");
65 const r = enrolRunner(f.app.db, name, "admin");
66 trustRunner(f.app.db, r.runner.id, true, "admin", 5);
67 const claimed = await post("/api/v1/runner/claim", r.token, { wait: 0 });
68 expect(claimed.status).toBe(200);
69 const token = ((await claimed.json()) as { token: string }).token;
70 const heard: string[] = [];
71 deskOf(f.app).ears.set(id, { wake: () => {}, lines: (_step, lines) => heard.push(...lines) });
72 return { id, token, heard, runnerId: r.runner.id };
73 }
74
75 describe("masking at the report door", () => {
76 test("a line, a step's error and the note are masked, and so are the stored result and log", async () => {
77 set("ASC_KEY", KEY);
78 const h = await holding("mac-door");
79 const door = `/api/v1/runner/jobs/${h.id}`;
80 expect((await post(door, h.token, { step: "check", lines: [`uploading with ${KEY}`] })).status).toBe(200);
81 expect(h.heard).toEqual(["uploading with ***"]);
82 const done = await post(door, h.token, { done: { steps: [{ name: "check", ok: false, error: `bad ${KEY}`, ms: 1 }], contained: true, note: `used ${KEY}` } });
83 expect(done.status).toBe(200);
84 const stored = viewJob(f.app.db, h.id)!.result!;
85 expect(stored).not.toContain(KEY);
86 expect(stored).toContain("bad ***");
87 expect(stored).toContain("used ***");
88 });
89
90 test("taking trust back while the job runs does not unmask what the runner holds", async () => {
91 const h = await holding("mac-revoked");
92 trustRunner(f.app.db, h.runnerId, false, "admin", 6);
93 expect((await post(`/api/v1/runner/jobs/${h.id}`, h.token, { step: "check", lines: [`still ${KEY}`] })).status).toBe(200);
94 expect(h.heard).toEqual(["still ***"]);
95 });
96
97 test("a multi-line secret is masked line by line, and its base64 and URL forms too", async () => {
98 set("PEM", PEM);
99 const h = await holding("mac-pem");
100 const lines = ["MIGTAgEAMBMGByqGSM49", `${D}BEGIN PRIVATE KEY${D}`, Buffer.from("MIGTAgEAMBMGByqGSM49").toString("base64"), encodeURIComponent("MIGTAgEAMBMGByqGSM49 x")];
101 await post(`/api/v1/runner/jobs/${h.id}`, h.token, { step: "check", lines });
102 for (const line of h.heard) expect(line).not.toMatch(/MIGTAgEAMBMGByqGSM49|BEGIN PRIVATE|TUlHVEFnRUFNQk1HQnlxR1NNNDk/);
103 expect(mask([PEM], PEM)).toBe("***");
104 });
105
106 test("a secret under four characters is refused at set time", () => {
107 expect(setEntry(f.app.db, f.dataDir, f.repo.id, { env: "testflight", name: "TINY", kind: "secret", value: "abc", by: "alice" }, 1)).toBe("bad_value");
108 });
109
110 test("names that run code in a step are reserved, whatever the case", () => {
111 for (const name of ["NODE_OPTIONS", "ld_preload", "LD_LIBRARY_PATH", "BASH_ENV", "ENV", "DYLD_INSERT_LIBRARIES", "GIT_SSH_COMMAND", "SSH_ASKPASS"])
112 expect(setEntry(f.app.db, f.dataDir, f.repo.id, { env: "testflight", name, kind: "var", value: "x", by: "alice" }, 1)).toBe("reserved");
113 });
114 });
115
116 describe("the claim's log", () => {
117 test("says what was received and withheld, and a trusted-only variable waits for a trusted runner", () => {
118 set("ONLY_TRUSTED", "visible", "var", "trusted");
119 set("TEAM", "ABC123", "var");
120 f.app.db.query("DELETE FROM check_job").run();
121 const id = offer("main");
122 const stranger = enrolRunner(f.app.db, "mac-plain", "admin");
123 const spec = JSON.parse(f.app.db.query<{ spec: string }, [string]>("SELECT spec FROM check_job WHERE id = ?1").get(id)!.spec) as RunnerJob;
124 const plain = withEnvironment(f.app.db, f.dataDir, spec, stranger.runner.id);
125 expect(plain.job.env!["TEAM"]).toBe("ABC123");
126 expect(plain.job.env!["ONLY_TRUSTED"]).toBeUndefined();
127 expect(plain.job.env!["ASC_KEY"]).toBeUndefined();
128 expect(plain.said).toContain("received TEAM");
129 expect(plain.said).toContain("withheld");
130 expect(plain.said).toContain("ONLY_TRUSTED (for trusted runners only)");
131 expect(plain.said).toContain("ASC_KEY (this runner is not trusted for secrets)");
132 expect(plain.said).not.toContain(KEY);
133 trustRunner(f.app.db, stranger.runner.id, true, "admin", 7);
134 const trusted = withEnvironment(f.app.db, f.dataDir, spec, stranger.runner.id);
135 expect(trusted.job.env!["ONLY_TRUSTED"]).toBe("visible");
136 expect(trusted.job.env!["ASC_KEY"]).toBe(KEY);
137 });
138
139 test("only the default branch's own check is the main lane; a pull and an outsider never are", () => {
140 expect(laneOf({ pull: false, keep: true, outside: false })).toBe("main");
141 expect(laneOf({ pull: true, keep: true, outside: false })).toBe("pull");
142 expect(laneOf({ pull: false, keep: false, outside: false })).toBe("pull");
143 expect(laneOf({ pull: false, keep: true, outside: true })).toBe("fork");
144 });
145 });
146
147 describe("what goes with a repository and a person", () => {
148 test("a deleted repository's entries go with it", async () => {
149 const made = await createRepo(f.app, f.alice, { name: "gone", visibility: "public" });
150 if (!made.ok) throw new Error(String(made.error));
151 setEntry(f.app.db, f.dataDir, made.value.id, { env: "checks", name: "TOKEN", kind: "secret", value: "tokentoken", by: "alice" }, 1);
152 expect(f.app.db.query("SELECT COUNT(*) AS n FROM repo_env WHERE repo_id = ?1").get(made.value.id)).toEqual({ n: 1 });
153 await deleteRepo(f.app.db, f.app.reposRoot, made.value);
154 expect(f.app.db.query("SELECT COUNT(*) AS n FROM repo_env WHERE repo_id = ?1").get(made.value.id)).toEqual({ n: 0 });
155 });
156
157 test("an erased account's name on an entry and on a runner's trust becomes the placeholder's", () => {
158 f.app.db.query("UPDATE user SET close_requested_at = '2020-01-01T00:00:00.000Z' WHERE id = ?1").run(f.bob.id);
159 set("BOBS", "bobs-value", "var");
160 f.app.db.query("UPDATE repo_env SET set_by = 'bob' WHERE name = 'BOBS'").run();
161 const r = enrolRunner(f.app.db, "mac-bobs", "admin");
162 trustRunner(f.app.db, r.runner.id, true, "bob", 9);
163 purgeAccount(f.app.db, f.bob.id, new Date(), f.dataDir);
164 expect(f.app.db.query<{ s: string }, []>("SELECT set_by AS s FROM repo_env WHERE name = 'BOBS'").get()!.s).toBe("a former member");
165 expect(f.app.db.query<{ s: string }, [string]>("SELECT trusted_by AS s FROM check_runner WHERE id = ?1").get(r.runner.id)!.s).toBe("a former member");
166 });
167 });
test/environments.test.ts added +142
@@ -0,0 +1,142 @@
1 /**
2 * Environments and trust (#18257): variables are readable and secrets are sealed and write-only;
3 * a job receives a secret only on main, only on a runner a site admin marked trusted, and never
4 * in a log; a pull's head and a fork's get variables for any runner only.
5 */
6 import { beforeAll, describe, expect, test } from "bun:test";
7 import { enrolRunner, offerJob, type RunnerJob } from "../src/checks/runner_jobs.ts";
8 import { maskFor } from "../src/checks/job_environment.ts";
9 import { listEntries, mask } from "../src/checks/environment.ts";
10 import { createRun } from "../src/core/runs.ts";
11 import { createToken } from "../src/core/tokens.ts";
12 import { parseCheck } from "../src/apps/manifest.ts";
13 import { checksForge } from "./helpers/checks-forge.ts";
14 import { quietLogs } from "./helpers/globals.ts";
15
16 quietLogs();
17
18 const f = checksForge("forge-environments-");
19 let admin = "";
20 let bobToken = "";
21 const KEY = "p8-key-material-123";
22
23 beforeAll(async () => {
24 await f.checks.stop();
25 admin = createToken(f.app.db, f.alice.id, "admin", "admin").token;
26 bobToken = createToken(f.app.db, f.bob.id, "bob", "admin").token;
27 });
28
29 const call = (method: string, path: string, token: string, body?: unknown): Promise<Response> =>
30 fetch(`${f.servers.url}${path}`, {
31 method,
32 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
33 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
34 });
35 const entry = (env: string, name: string, token = admin) => `/api/v1/repos/alice/lib/environments/${env}/${name}`;
36
37 /** A job naming `environment`, on `lane`, offered for a fresh run. */
38 function offer(lane?: RunnerJob["lane"]): string {
39 const run = createRun(f.app.db, { repoId: f.repo.id, kind: "check", env: "main", commitOid: "a".repeat(40) });
40 return offerJob(f.app.db, {
41 runId: run.id,
42 repoId: f.repo.id,
43 dir: f.dataDir,
44 job: {
45 run: run.id,
46 repo: "alice/lib",
47 commit: "a".repeat(40),
48 depth: 1,
49 steps: [{ name: "check", command: "true" }],
50 env: { CI: "true" },
51 limits: {},
52 timeoutS: 60,
53 egress: [],
54 egressMode: "report",
55 cell: "preferred",
56 cache: { repo: f.repo.id, tree: "", base: "" },
57 environment: "testflight",
58 ...(lane === undefined ? {} : { lane }),
59 },
60 }).id;
61 }
62
63 /** What a runner of this trust is sent when it claims the one queued job. */
64 async function claimEnv(name: string, trust: boolean, lane?: RunnerJob["lane"]): Promise<Record<string, string>> {
65 f.app.db.query("DELETE FROM check_job").run();
66 offer(lane);
67 const enrolled = enrolRunner(f.app.db, name, "admin");
68 if (trust) expect((await call("POST", `/api/v1/admin/runners/${enrolled.runner.id}/trust`, admin, { trusted: true })).status).toBe(200);
69 const res = await call("POST", "/api/v1/runner/claim", enrolled.token, { wait: 0, cells: true });
70 expect(res.status).toBe(200);
71 return ((await res.json()) as { job: RunnerJob }).job.env as Record<string, string>;
72 }
73
74 describe("environment entries", () => {
75 test("a secret is sealed, listed by name, and its default is trusted-only", async () => {
76 expect((await call("PUT", entry("testflight", "ASC_KEY"), admin, { kind: "secret", value: KEY })).status).toBe(200);
77 expect((await call("PUT", entry("testflight", "TEAM"), admin, { kind: "var", value: "ABC123" })).status).toBe(200);
78 const listed = (await (await call("GET", "/api/v1/repos/alice/lib/environments", admin)).json()) as { entries: { name: string; scope: string; value?: string }[] };
79 expect(listed.entries.map((e) => [e.name, e.scope, e.value])).toEqual([["ASC_KEY", "trusted", undefined], ["TEAM", "any", "ABC123"]]);
80 const stored = f.app.db.query<{ value: string }, []>("SELECT value FROM repo_env WHERE name = 'ASC_KEY'").get()!;
81 expect(stored.value).not.toContain(KEY);
82 expect(JSON.stringify(listEntries(f.app.db, f.repo.id))).not.toContain(KEY);
83 });
84
85 test("a secret for any runner needs its name typed; reserved names and strangers are refused", async () => {
86 expect((await call("PUT", entry("testflight", "OPEN"), admin, { kind: "secret", value: "x1234", scope: "any" })).status).toBe(422);
87 expect((await call("PUT", entry("testflight", "OPEN"), admin, { kind: "secret", value: "x1234", scope: "any", confirm: "OPEN" })).status).toBe(200);
88 expect((await call("PUT", entry("testflight", "CI"), admin, { kind: "var", value: "no" })).status).toBe(422);
89 expect((await call("PUT", entry("Bad", "X"), admin, { kind: "var", value: "no" })).status).toBe(422);
90 // bob reads alice's repository but does not administer it.
91 expect((await call("PUT", entry("testflight", "X"), bobToken, { kind: "var", value: "no" })).status).toBe(404);
92 expect((await call("GET", "/api/v1/repos/alice/lib/environments", bobToken)).status).toBe(404);
93 expect((await call("DELETE", entry("testflight", "OPEN"), admin)).status).toBe(200);
94 });
95 });
96
97 describe("what a claim receives", () => {
98 test("main on a trusted runner gets the secret and the variable", async () => {
99 expect(await claimEnv("mac-trusted", true, "main")).toMatchObject({ ASC_KEY: KEY, TEAM: "ABC123", CI: "true" });
100 });
101 test("main on an untrusted runner gets the variable only", async () => {
102 const env = await claimEnv("mac-stranger", false, "main");
103 expect(env.TEAM).toBe("ABC123");
104 expect(env.ASC_KEY).toBeUndefined();
105 });
106 test("a pull's head and a fork's get no secret even on a trusted runner", async () => {
107 for (const lane of [undefined, "pull", "fork"] as const) {
108 const env = await claimEnv(`mac-t-${lane ?? "none"}`, true, lane);
109 expect(env.ASC_KEY).toBeUndefined();
110 expect(env.TEAM).toBe("ABC123");
111 }
112 });
113 test("trust is revoked by the same switch, and the forge's own runner cannot be marked", async () => {
114 const r = enrolRunner(f.app.db, "mac-switch", "admin");
115 await call("POST", `/api/v1/admin/runners/${r.runner.id}/trust`, admin, { trusted: true });
116 await call("POST", `/api/v1/admin/runners/${r.runner.id}/trust`, admin, { trusted: false });
117 expect(f.app.db.query<{ t: number }, [string]>("SELECT trusted_at AS t FROM check_runner WHERE id = ?1").get(r.runner.id)!.t).toBe(0);
118 const local = enrolRunner(f.app.db, "local-1", "admin");
119 expect((await call("POST", `/api/v1/admin/runners/${local.runner.id}/trust`, admin, { trusted: true })).status).toBe(422);
120 expect((await call("POST", `/api/v1/admin/runners/${r.runner.id}/trust`, bobToken, { trusted: true })).status).toBeGreaterThanOrEqual(403);
121 });
122 });
123
124 describe("logs and manifest", () => {
125 test("a held job's log lines are masked of the secrets it was given", async () => {
126 f.app.db.query("DELETE FROM check_job").run();
127 const id = offer("main");
128 const r = enrolRunner(f.app.db, "mac-masked", "admin");
129 await call("POST", `/api/v1/admin/runners/${r.runner.id}/trust`, admin, { trusted: true });
130 expect((await call("POST", "/api/v1/runner/claim", r.token, { wait: 0 })).status).toBe(200);
131 const job = f.app.db.query<{ spec: string }, [string]>("SELECT spec FROM check_job WHERE id = ?1").get(id)!;
132 const masked = maskFor(f.app.db, f.dataDir, JSON.parse(job.spec), id)!;
133 expect(masked(`uploading with ${KEY}!`)).toBe("uploading with ***!");
134 expect(mask([KEY], `a ${KEY} b ${KEY}`)).toBe("a *** b ***");
135 });
136
137 test("forge.json names an environment, and a wrong name is refused", () => {
138 const ok = parseCheck(`{"check":{"run":"true","environment":"testflight"}}`, undefined);
139 expect(ok.ok && ok.value?.environment).toBe("testflight");
140 expect(parseCheck(`{"check":{"run":"true","environment":"Bad Name"}}`, undefined).ok).toBe(false);
141 });
142 });
test/route-timing-coverage.test.ts +1
@@ -33,6 +33,7 @@ const UNTIMED: Record<string, string> = {
3333 "/api/v1/admin/plans": "an admin's plans with the measured median, two indexed reads; no page to phase",
3434 "/api/v1/admin/infra/code": "each app's infra.json read from its repo's main branch (cached per tip) and diffed read-only; no page to phase",
3535 "/api/v1/user/devices": "a person's own Apple devices, one indexed read; no page to phase",
36 "/api/v1/repos/:owner/:name/environments": "a repository admin's entry names, one indexed read; no page to phase",
3637 "/api/v1/arcade/games": "the arcade games and their builds, read from the pinned game heads; no page to phase",
3738 "/metrics": "Prometheus text exposition, scraped by token; not a page read",
3839 };

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

Keyboard shortcuts

Docs