Public: anyone can read this; the crew can change it.
A deploy's build as a cluster Job #1906
scout/forge:scout/1427-a-deploy-s-build-as-a-cluster-job → main 4 commits fork 4 threads · 4 unresolved
11 files
changed +803
−13
docs/APPS.md +16
| @@ -375,6 +375,21 @@ run is recorded as uncontained ("egress not enforced on a cluster job"), and | ||
| 375 | 375 | the pod carries the label `forge-check=true` so an operator's NetworkPolicy |
| 376 | 376 | can select it and hold what `egress` declares. |
| 377 | 377 | |
| 378 | **Build placement.** `FORGE_BUILD_PLACEMENT=job` runs a deploy's install | |
| 379 | step as a Kubernetes Job instead of in a cell; the app itself still runs in | |
| 380 | the forge. It reads `FORGE_BUILD_IMAGE`, `FORGE_BUILD_CLAIM` (a | |
| 381 | ReadWriteMany claim holding `<data>/builds`, mounted at the same path), | |
| 382 | `FORGE_BUILD_NODE_SELECTOR` and `FORGE_BUILD_TOLERATIONS` as checks do; a | |
| 383 | malformed setting leaves `process`. The forge copies the checkout to | |
| 384 | `builds/<run>`, the Job (pod label `forge-build=true`, same hardening as a | |
| 385 | check's) runs the install there and pipes `tar` of the result to | |
| 386 | `POST /-/build/<run>/tree` with a one-time bearer token, which the forge | |
| 387 | unpacks over the checkout (`src/apps/tar.ts`: no absolute or `..` names, no | |
| 388 | write through a link, no devices). The image needs `sh`, `tar` and `curl` and | |
| 389 | must reach the forge's URL; the door takes one tree up to 256 MiB (150k entries), once, and the forge unpacks it yielding to requests as it goes. The Job gets `CI` and `FORGE_APP_ENV`, the same declared step environment as an in-cell install (not the app's variables). | |
| 390 | Egress is not enforced by the forge on a Job. Warm starts and wakes never | |
| 391 | build, so they never use a Job. | |
| 392 | ||
| 378 | 393 | Checks share `FORGE_CHECKS_CONCURRENCY` slots (default `1`), and when one |
| 379 | 394 | frees, it goes to the most recently requested check waiting, not the one |
| 380 | 395 | queued longest — a fresh push is never stuck behind pulls that queued hours |
| @@ -1097,6 +1112,7 @@ a link to the milestone (`docs/PLANNING.md`); its progress never does. | ||
| 1097 | 1112 | | `FORGE_CREW_CONCURRENCY` | `2` | agent runs at once (live: Settings → Capacity) | |
| 1098 | 1113 | | `FORGE_CHECKS_CONCURRENCY` | `1` | checks at once (live: Settings → Capacity) | |
| 1099 | 1114 | | `FORGE_CHECKS_PLACEMENT` | `process` | `job` runs a check's commands as a cluster Job (see Placement above) | |
| 1115 | | `FORGE_BUILD_PLACEMENT` | `process` | `job` runs a deploy's install step as a cluster Job (see Build placement) | | |
| 1100 | 1116 | | `FORGE_CHECKS_DRAIN_S` | `300` | seconds a roll lets running checks finish first | |
| 1101 | 1117 | | `FORGE_CHECK_SHARDS` | the machine's cores | test shards per check (live: Settings → Capacity) | |
| 1102 | 1118 | | `FORGE_CELLS_EGRESS` | `enforce` | `report` lets undeclared egress through on 80/443 (live: Settings → Capacity) | |
scripts/gate.ts +2
| @@ -55,6 +55,8 @@ export const GATE: readonly string[] = [ | ||
| 55 | 55 | "test/flow-card.test.ts", |
| 56 | 56 | "test/cluster-jobs.test.ts", |
| 57 | 57 | "test/checks-placement.test.ts", |
| 58 | "test/build-placement.test.ts", | |
| 59 | "test/build-wiring.test.ts", | |
| 58 | 60 | "test/checks-job-vanish.test.ts", |
| 59 | 61 | "test/fuzz-found.test.ts", |
| 60 | 62 | "test/fuzz-parsers.test.ts", |
src/apps/build_door.ts added +56
| @@ -0,0 +1,56 @@ | ||
| 1 | /** | |
| 2 | * The door a build Job returns its tree through: `POST /-/build/:id/tree`, | |
| 3 | * the body a tar. The forge opens a door for one build and hands the Job its | |
| 4 | * token; the door takes one tree, once, before it expires, and shuts. The | |
| 5 | * credential is the token alone (no cookie is read, so there is nothing for | |
| 6 | * a cross-origin page to ride), compared in constant time against a hash. | |
| 7 | */ | |
| 8 | import { createHash, randomBytes, timingSafeEqual } from "node:crypto"; | |
| 9 | import { readBounded } from "../http/limits.ts"; | |
| 10 | ||
| 11 | /** The largest tree a build may send back. */ | |
| 12 | export const TREE_MAX = 256 * 1024 * 1024; | |
| 13 | ||
| 14 | type Door = { hash: Buffer; deliver: (tar: Uint8Array) => void; timer: ReturnType<typeof setTimeout> }; | |
| 15 | ||
| 16 | const doors = new Map<string, Door>(); | |
| 17 | const hashOf = (token: string): Buffer => createHash("sha256").update(token).digest(); | |
| 18 | ||
| 19 | export type Expected = { | |
| 20 | token: string; | |
| 21 | /** The tree, once it comes; never settles if the door closes first. */ | |
| 22 | arrived: Promise<Uint8Array>; | |
| 23 | close(): void; | |
| 24 | }; | |
| 25 | ||
| 26 | /** Open a door for build `id`; it shuts by itself after `ttlMs`. */ | |
| 27 | export function expectTree(id: string, ttlMs: number): Expected { | |
| 28 | const token = randomBytes(32).toString("base64url"); | |
| 29 | let deliver!: (tar: Uint8Array) => void; | |
| 30 | const arrived = new Promise<Uint8Array>((resolve) => (deliver = resolve)); | |
| 31 | const close = (): void => { | |
| 32 | const door = doors.get(id); | |
| 33 | if (door === undefined) return; | |
| 34 | clearTimeout(door.timer); | |
| 35 | doors.delete(id); | |
| 36 | }; | |
| 37 | doors.set(id, { hash: hashOf(token), deliver, timer: setTimeout(close, ttlMs) }); | |
| 38 | return { token, arrived, close }; | |
| 39 | } | |
| 40 | ||
| 41 | /** Answer one request at the door. */ | |
| 42 | export async function treeDoor(request: Request, id: string): Promise<Response> { | |
| 43 | const header = request.headers.get("authorization") ?? ""; | |
| 44 | const given = header.startsWith("Bearer ") ? hashOf(header.slice(7)) : undefined; | |
| 45 | const door = doors.get(id); | |
| 46 | // Unknown, expired and wrong-token are one answer. | |
| 47 | if (door === undefined || given === undefined || !timingSafeEqual(given, door.hash)) | |
| 48 | return new Response("forbidden", { status: 403 }); | |
| 49 | const body = await readBounded(request, TREE_MAX); | |
| 50 | if (body === "too_large") return new Response("too large", { status: 413 }); | |
| 51 | // Taken: a second post finds no door. | |
| 52 | clearTimeout(door.timer); | |
| 53 | doors.delete(id); | |
| 54 | door.deliver(body); | |
| 55 | return new Response(null, { status: 204 }); | |
| 56 | } |
src/apps/build_job.ts added +103
| @@ -0,0 +1,103 @@ | ||
| 1 | /** | |
| 2 | * A deploy's install step as one cluster Job (`FORGE_BUILD_PLACEMENT=job`). | |
| 3 | * The checkout is copied under the builds root the claim holds, the Job | |
| 4 | * installs in it and posts the whole tree back as a tar through the token | |
| 5 | * door (`build_door.ts`), and the forge unpacks it over the checkout | |
| 6 | * (`tar.ts`). The app itself still starts in the forge. The Job's image | |
| 7 | * needs `sh`, `tar` and `curl`, and must reach the forge's URL. | |
| 8 | */ | |
| 9 | import { cpSync, mkdirSync, rmSync } from "node:fs"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { runJob, type JobOptions, type JobSpec } from "../cluster/jobs.ts"; | |
| 12 | import type { Placement } from "../checks/placement.ts"; | |
| 13 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 14 | import { expectTree } from "./build_door.ts"; | |
| 15 | import { extractTar } from "./tar.ts"; | |
| 16 | ||
| 17 | /** What a NetworkPolicy selects a build's pod by. */ | |
| 18 | export const BUILD_LABELS = { "forge-build": "true" }; | |
| 19 | ||
| 20 | /** Where a build's copy of the checkout lives; the claim holds this root. */ | |
| 21 | export const buildsRoot = (dataDir: string): string => join(dataDir, "builds"); | |
| 22 | ||
| 23 | export async function buildInJob( | |
| 24 | placement: Extract<Placement, { mode: "job" }>, | |
| 25 | input: { | |
| 26 | /** One word per build: a DNS-safe, unique id (the run's). */ | |
| 27 | id: string; | |
| 28 | dataDir: string; | |
| 29 | /** The exported checkout the tree is unpacked over. */ | |
| 30 | dir: string; | |
| 31 | install: string; | |
| 32 | /** The step environment the in-cell install would get, declared. */ | |
| 33 | stepEnv?: Record<string, string>; | |
| 34 | forgeUrl: string; | |
| 35 | log: (line: string) => void; | |
| 36 | signal: AbortSignal; | |
| 37 | timeoutMs: number; | |
| 38 | limits: { memoryMiB: number; cpus: number; diskMiB: number }; | |
| 39 | options?: JobOptions; | |
| 40 | /** How long to wait for a tree after the Job ends. @default 5000 */ | |
| 41 | treeWaitMs?: number; | |
| 42 | }, | |
| 43 | ): Promise<Result<void, string>> { | |
| 44 | const word = input.id.toLowerCase().replace(/[^a-z0-9]/g, ""); | |
| 45 | if (word === "") return err("build has no id"); | |
| 46 | const work = join(buildsRoot(input.dataDir), word); | |
| 47 | const door = expectTree(word, input.timeoutMs + 60_000); | |
| 48 | try { | |
| 49 | rmSync(work, { recursive: true, force: true }); | |
| 50 | mkdirSync(buildsRoot(input.dataDir), { recursive: true }); | |
| 51 | cpSync(input.dir, work, { recursive: true, verbatimSymlinks: true }); | |
| 52 | const spec: JobSpec = { | |
| 53 | name: `build-${word}`.slice(0, 53), | |
| 54 | image: placement.image, | |
| 55 | command: [ | |
| 56 | "/bin/sh", | |
| 57 | "-c", | |
| 58 | `set -e; ${input.install}; tar -cf - . | curl -fsS --data-binary @- -H "authorization: Bearer $FORGE_BUILD_TOKEN" "$FORGE_BUILD_URL"`, | |
| 59 | ], | |
| 60 | // Not the forge's environment: the step's own, and the way back. | |
| 61 | env: { | |
| 62 | CI: "1", | |
| 63 | ...input.stepEnv, | |
| 64 | FORGE_BUILD_URL: `${input.forgeUrl.replace(/\/+$/, "")}/-/build/${word}/tree`, | |
| 65 | FORGE_BUILD_TOKEN: door.token, | |
| 66 | }, | |
| 67 | nodeSelector: placement.nodeSelector, | |
| 68 | tolerations: placement.tolerations, | |
| 69 | volume: { claim: placement.claim, mountPath: work, subPath: word }, | |
| 70 | limits: input.limits, | |
| 71 | labels: BUILD_LABELS, | |
| 72 | }; | |
| 73 | input.log(`$ ${input.install} (as a cluster job)`); | |
| 74 | let result; | |
| 75 | try { | |
| 76 | result = await runJob(spec, { timeoutMs: input.timeoutMs, signal: input.signal, ...input.options }); | |
| 77 | } catch (error) { | |
| 78 | if (input.signal.aborted) return err("build cancelled"); | |
| 79 | return err(`build job could not run: ${error instanceof Error ? error.message : String(error)}`); | |
| 80 | } | |
| 81 | for (const line of result.lines) input.log(line); | |
| 82 | if (result.node) input.log(`built on ${result.node.replace(/[^\x21-\x7e]/g, "").slice(0, 253)}`); | |
| 83 | if (result.timedOut) return err(`install took longer than ${Math.round(input.timeoutMs / 1000)}s`); | |
| 84 | if (result.exitCode !== 0) return err(`install exited with code ${result.exitCode ?? "unknown"}`); | |
| 85 | // The post finished before the Job did; a tree that is not here is not coming. | |
| 86 | let timer: ReturnType<typeof setTimeout> | undefined; | |
| 87 | const tree = await Promise.race([ | |
| 88 | door.arrived, | |
| 89 | new Promise<undefined>((r) => { | |
| 90 | timer = setTimeout(() => r(undefined), input.treeWaitMs ?? 5000); | |
| 91 | }), | |
| 92 | ]); | |
outdated
A synchronous unpack of up to 512 MiB / 500k entries on the forge's event loop, with bytes from repository code: every request waits for it. Move it to a Worker or yield as it goes. |
||
| 93 | clearTimeout(timer); | |
| 94 | if (tree === undefined) return err("the build finished but sent no tree back"); | |
| 95 | const unpacked = await extractTar(tree, input.dir); | |
| 96 | if (!unpacked.ok) return err(unpacked.error); | |
| 97 | input.log(`tree back from the job: ${unpacked.value} entries`); | |
| 98 | return ok(); | |
| 99 | } finally { | |
| 100 | door.close(); | |
| 101 | rmSync(work, { recursive: true, force: true }); | |
| 102 | } | |
| 103 | } |
src/apps/process.ts +15 −7
| @@ -68,6 +68,11 @@ export interface StartInput { | ||
| 68 | 68 | * start — the forge coming back, or an environment waking — only runs it. |
| 69 | 69 | */ |
| 70 | 70 | readonly warm?: boolean | undefined; |
| 71 | /** | |
| 72 | * Runs the install step somewhere else (a cluster Job) and leaves its | |
| 73 | * result in `dir`. Unset, `install` runs here in a cell. | |
| 74 | */ | |
| 75 | readonly install?: ((command: string) => Promise<Result<void, string>>) | undefined; | |
| 71 | 76 | } |
| 72 | 77 | |
| 73 | 78 | /** What a caller knows about a cell; the rest comes from the manifest. */ |
| @@ -341,13 +346,16 @@ export async function startProcess( | ||
| 341 | 346 | }); |
| 342 | 347 | |
| 343 | 348 | if (manifest.install !== null && input.warm !== true) { |
| 344 | const installed = await runStep("install", manifest.install, { | |
| 345 | cwd: input.dir, | |
| 346 | env: stepEnv, | |
| 347 | log, | |
| 348 | signal: input.signal, | |
| 349 | cell: stepCell(input), | |
| 350 | }); | |
| 349 | const installed = | |
| 350 | input.install !== undefined | |
No test covers this branch: without the |
||
| 351 | ? await input.install(manifest.install) | |
| 352 | : await runStep("install", manifest.install, { | |
| 353 | cwd: input.dir, | |
| 354 | env: stepEnv, | |
| 355 | log, | |
| 356 | signal: input.signal, | |
| 357 | cell: stepCell(input), | |
| 358 | }); | |
| 351 | 359 | if (!installed.ok) |
| 352 | 360 | return err({ stage: "install", message: installed.error }); |
| 353 | 361 | } |
src/apps/runtime.ts +39
| @@ -28,6 +28,9 @@ import { mintAppToken, renewAppToken, revokeAppToken } from "./token.ts"; | ||
| 28 | 28 | import type { ForgeEvent } from "../core/events.ts"; |
| 29 | 29 | import { announceRun } from "../actions/runs.ts"; |
| 30 | 30 | import { requeueAbandonedChecks } from "../checks/service.ts"; |
| 31 | import { buildPlacementFromEnv } from "../checks/placement.ts"; | |
| 32 | import type { JobOptions } from "../cluster/jobs.ts"; | |
| 33 | import { buildInJob } from "./build_job.ts"; | |
| 31 | 34 | import { getPull, listPulls, type Pull } from "../core/pulls.ts"; |
| 32 | 35 | import { pullMayRun } from "../core/pull_trust.ts"; |
| 33 | 36 | import { canEnterApp, getRepoById, type Repo } from "../core/repos.ts"; |
| @@ -98,6 +101,14 @@ import { | ||
| 98 | 101 | const log = createLog("apps"); |
| 99 | 102 | |
| 100 | 103 | export interface RuntimeOptions { |
| 104 | /** | |
| 105 | * Where a deploy's install step runs (`FORGE_BUILD_PLACEMENT`): `process` | |
| 106 | * here in a cell, or `job` as a cluster Job whose tree comes back | |
| 107 | * (`apps/build_job.ts`). @default from the environment: `process`. | |
| 108 | */ | |
| 109 | readonly buildPlacement?: import("../checks/placement.ts").Placement | undefined; | |
| 110 | /** The kube client a `job` build speaks through; tests stand one in. */ | |
| 111 | readonly buildJob?: JobOptions | undefined; | |
| 101 | 112 | /** The domain app hostnames hang off: `<slug>.<domain>`. */ |
| 102 | 113 | readonly domain: string; |
| 103 | 114 | /** `http` or `https` — what the public URL of an app starts with. */ |
| @@ -1163,6 +1174,33 @@ export class AppsRuntime { | ||
| 1163 | 1174 | } |
| 1164 | 1175 | } |
| 1165 | 1176 | |
| 1177 | /** The install step as a cluster Job, when builds are placed so. */ | |
| 1178 | private buildInstall( | |
| 1179 | runId: string, | |
| 1180 | env: string, | |
| 1181 | dir: string, | |
| 1182 | signal: AbortSignal, | |
| 1183 | log: (line: string) => void, | |
| 1184 | timeoutS: number, | |
| 1185 | ): StartInput["install"] { | |
| 1186 | const placement = this.options.buildPlacement ?? buildPlacementFromEnv(); | |
| 1187 | if (placement.mode !== "job") return undefined; | |
| 1188 | return (install) => | |
| 1189 | buildInJob(placement, { | |
| 1190 | id: runId, | |
| 1191 | dataDir: this.app.config.dataDir, | |
| 1192 | dir, | |
| 1193 | install, | |
| 1194 | stepEnv: { FORGE_APP_ENV: env === "production" ? "production" : "preview" }, | |
| 1195 | forgeUrl: this.options.forgeUrl, | |
| 1196 | log, | |
| 1197 | signal, | |
| 1198 | timeoutMs: timeoutS * 1000, | |
| 1199 | limits: resolveLimits("step", undefined), | |
| 1200 | ...(this.options.buildJob === undefined ? {} : { options: this.options.buildJob }), | |
| 1201 | }); | |
| 1202 | } | |
| 1203 | ||
| 1166 | 1204 | private async bringUp( |
| 1167 | 1205 | state: Environment, |
| 1168 | 1206 | repo: Repo, |
| @@ -1254,6 +1292,7 @@ export class AppsRuntime { | ||
| 1254 | 1292 | log: write, |
| 1255 | 1293 | warm, |
| 1256 | 1294 | cell: this.cellFor(state.app, state.env), |
| 1295 | install: this.buildInstall(run.id, state.env, dir, signal, write, 1200), | |
| 1257 | 1296 | }; |
| 1258 | 1297 | this.noteCell(run.id, write); |
| 1259 | 1298 | clock.lap("setup"); |
src/apps/tar.ts added +170
| @@ -0,0 +1,170 @@ | ||
| 1 | /** | |
| 2 | * Unpack a tar a cluster Job sent back, without trusting it. The bytes come | |
| 3 | * from a pod running repository code, so nothing here shells out to `tar`: | |
| 4 | * the archive is read in-process and only directories, regular files, | |
| 5 | * symlinks and hard links are made. An entry is refused when its name is | |
| 6 | * absolute or climbs out with `..`, or when any directory on its way is a | |
| 7 | * symlink — so a link made by one entry is never written through by the | |
| 8 | * next. Plain data in (bytes and a directory), a count or a reason out. It yields to the event loop every few | |
| 9 | * hundred entries, so one large tree never stalls the forge's requests. | |
| 10 | */ | |
| 11 | import { | |
| 12 | chmodSync, | |
| 13 | copyFileSync, | |
| 14 | lstatSync, | |
| 15 | mkdirSync, | |
| 16 | rmSync, | |
| 17 | symlinkSync, | |
| 18 | writeFileSync, | |
| 19 | } from "node:fs"; | |
| 20 | import { join } from "node:path"; | |
| 21 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 22 | ||
| 23 | const BLOCK = 512; | |
| 24 | const MAX_ENTRIES = 150_000; | |
| 25 | /** Entries unpacked between yields to the event loop. */ | |
| 26 | const BATCH = 200; | |
| 27 | const MAX_NAME = 4096; | |
| 28 | ||
| 29 | const text = (b: Uint8Array, from: number, to: number): string => { | |
| 30 | let end = from; | |
| 31 | while (end < to && b[end] !== 0) end++; | |
| 32 | return new TextDecoder().decode(b.subarray(from, end)); | |
| 33 | }; | |
| 34 | ||
| 35 | function number(b: Uint8Array, from: number, to: number): number { | |
| 36 | if ((b[from] ?? 0) & 0x80) { | |
| 37 | // base-256, for a size past what octal holds | |
| 38 | let n = (b[from] ?? 0) & 0x7f; | |
| 39 | for (let i = from + 1; i < to; i++) n = n * 256 + (b[i] ?? 0); | |
| 40 | return n; | |
| 41 | } | |
| 42 | const s = text(b, from, to).trim(); | |
| 43 | return s === "" ? 0 : /^[0-7]+$/.test(s) ? parseInt(s, 8) : Number.NaN; | |
| 44 | } | |
| 45 | ||
| 46 | function checksumOk(b: Uint8Array, at: number): boolean { | |
| 47 | let sum = 0; | |
| 48 | for (let i = 0; i < BLOCK; i++) sum += i >= 148 && i < 156 ? 32 : (b[at + i] ?? 0); | |
| 49 | return sum === number(b, at + 148, at + 156); | |
| 50 | } | |
| 51 | ||
| 52 | /** The `path`, `linkpath` and `size` a pax header carries. */ | |
| 53 | function pax(body: string): Record<string, string> { | |
| 54 | const out: Record<string, string> = {}; | |
| 55 | const bytes = new TextEncoder().encode(body); | |
| 56 | let at = 0; | |
| 57 | while (at < bytes.length) { | |
| 58 | const space = bytes.indexOf(32, at); | |
| 59 | const len = Number(new TextDecoder().decode(bytes.subarray(at, space))); | |
| 60 | if (space < 0 || !Number.isInteger(len) || len < 1 || at + len > bytes.length) break; | |
| 61 | const record = new TextDecoder().decode(bytes.subarray(space + 1, at + len - 1)); | |
| 62 | const eq = record.indexOf("="); | |
| 63 | if (eq > 0) out[record.slice(0, eq)] = record.slice(eq + 1); | |
| 64 | at += len; | |
| 65 | } | |
| 66 | return out; | |
| 67 | } | |
| 68 | ||
| 69 | /** The entry's path relative to the root, or why it is refused. */ | |
| 70 | function clean(name: string): Result<string[], string> { | |
| 71 | if (name.length > MAX_NAME || /[\0-\x1f]/.test(name)) return err(`bad name in the tree`); | |
| 72 | const parts = name.split("/").filter((p) => p !== "" && p !== "."); | |
| 73 | if (name.startsWith("/") || parts.includes("..")) return err(`the tree names ${name.slice(0, 80)} outside itself`); | |
| 74 | return ok(parts); | |
| 75 | } | |
| 76 | ||
| 77 | /** `dest` must be a directory that exists; the archive is unpacked into it. */ | |
| 78 | export async function extractTar(data: Uint8Array, dest: string): Promise<Result<number, string>> { | |
| 79 | let at = 0; | |
| 80 | let entries = 0; | |
| 81 | let longName: string | undefined; | |
| 82 | let longLink: string | undefined; | |
| 83 | let next: Record<string, string> = {}; | |
| 84 | const checked = new Set<string>(); | |
| 85 | ||
| 86 | /** Every directory above `parts` exists as a real directory, never a link. */ | |
| 87 | const parents = (parts: string[]): Result<string, string> => { | |
| 88 | let cur = dest; | |
| 89 | for (const p of parts.slice(0, -1)) { | |
| 90 | cur = join(cur, p); | |
| 91 | if (checked.has(cur)) continue; | |
| 92 | let st = lstatSync(cur, { throwIfNoEntry: false }); | |
| 93 | if (st === undefined) { | |
| 94 | mkdirSync(cur); | |
| 95 | st = lstatSync(cur); | |
| 96 | } | |
| 97 | if (!st.isDirectory()) return err("the tree writes through a link"); | |
| 98 | checked.add(cur); | |
| 99 | } | |
| 100 | return ok(join(cur, parts[parts.length - 1] ?? "")); | |
| 101 | }; | |
| 102 | ||
| 103 | try { | |
| 104 | while (at + BLOCK <= data.length) { | |
| 105 | if (data.subarray(at, at + BLOCK).every((x) => x === 0)) break; | |
| 106 | if (!checksumOk(data, at)) return err("the tree is not a tar"); | |
| 107 | const type = String.fromCharCode(data[at + 156] ?? 0); | |
| 108 | let size = number(data, at + 124, at + 136); | |
| 109 | const attrs = next; | |
| 110 | if (attrs["size"] !== undefined && Number.isInteger(Number(attrs["size"]))) size = Number(attrs["size"]); | |
| 111 | if (!Number.isFinite(size) || size < 0 || at + BLOCK + size > data.length) return err("the tree is cut short"); | |
| 112 | const head = at; | |
| 113 | const body = data.subarray(at + BLOCK, at + BLOCK + size); | |
| 114 | at += BLOCK + Math.ceil(size / BLOCK) * BLOCK; | |
| 115 | ||
| 116 | if (type === "L") { longName = text(body, 0, body.length); continue; } | |
| 117 | if (type === "K") { longLink = text(body, 0, body.length); continue; } | |
| 118 | if (type === "x") { next = pax(new TextDecoder().decode(body)); continue; } | |
| 119 | if (type === "g") continue; | |
| 120 | next = {}; | |
| 121 | ||
| 122 | const prefix = text(data, head + 345, head + 500); | |
| 123 | const base = text(data, head, head + 100); | |
| 124 | const name = attrs["path"] ?? longName ?? (prefix === "" ? base : `${prefix}/${base}`); | |
| 125 | const link = attrs["linkpath"] ?? longLink ?? text(data, head + 157, head + 257); | |
| 126 | longName = longLink = undefined; | |
| 127 | const mode = number(data, head + 100, head + 108); | |
| 128 | ||
| 129 | if (++entries > MAX_ENTRIES) return err("the tree has too many entries"); | |
| 130 | // Hand the loop back now and then: the forge serves requests meanwhile. | |
| 131 | if (entries % BATCH === 0) await new Promise<void>((r) => setImmediate(r)); | |
| 132 | const parts = clean(name); | |
| 133 | if (!parts.ok) return parts; | |
| 134 | if (parts.value.length === 0) continue; | |
| 135 | const target = parents(parts.value); | |
| 136 | if (!target.ok) return target; | |
| 137 | const path = target.value; | |
| 138 | const present = lstatSync(path, { throwIfNoEntry: false }); | |
| 139 | // What stood here is replaced, so nothing under it is vouched for. | |
| 140 | if (present !== undefined && type !== "5") | |
| 141 | for (const c of checked) if (c === path || c.startsWith(`${path}/`)) checked.delete(c); | |
| 142 | ||
| 143 | if (type === "5") { | |
| 144 | if (present !== undefined && !present.isDirectory()) rmSync(path, { force: true }); | |
| 145 | mkdirSync(path, { recursive: true }); | |
| 146 | checked.add(path); | |
| 147 | chmodSync(path, ((Number.isFinite(mode) ? mode : 0o755) & 0o777) | 0o700); | |
| 148 | } else if (type === "0" || type === "\0" || type === "7") { | |
| 149 | if (present !== undefined) rmSync(path, { recursive: true, force: true }); | |
| 150 | writeFileSync(path, body); | |
| 151 | chmodSync(path, (Number.isFinite(mode) ? mode : 0o644) & 0o777 | 0o600); | |
| 152 | } else if (type === "2") { | |
| 153 | if (present !== undefined) rmSync(path, { recursive: true, force: true }); | |
| 154 | symlinkSync(link, path); | |
| 155 | } else if (type === "1") { | |
| 156 | const from = clean(link); | |
| 157 | if (!from.ok) return from; | |
| 158 | const source = parents(from.value); | |
| 159 | if (!source.ok) return source; | |
| 160 | if (present !== undefined) rmSync(path, { recursive: true, force: true }); | |
| 161 | if (!lstatSync(source.value, { throwIfNoEntry: false })?.isFile()) return err("the tree links to a file it lacks"); | |
| 162 | copyFileSync(source.value, path); | |
| 163 | } | |
| 164 | // Devices, fifos and the rest are not made. | |
| 165 | } | |
| 166 | } catch (error) { | |
| 167 | return err(`the tree could not be unpacked: ${error instanceof Error ? error.message : String(error)}`); | |
| 168 | } | |
| 169 | return ok(entries); | |
| 170 | } |
src/checks/placement.ts +18 −6
| @@ -66,17 +66,29 @@ export function parseTolerations(text: string): Toleration[] | undefined { | ||
| 66 | 66 | return out; |
| 67 | 67 | } |
| 68 | 68 | |
| 69 | export function placementFromEnv(env: Record<string, string | undefined> = process.env): Placement { | |
| 70 | if (env["FORGE_CHECKS_PLACEMENT"]?.trim() !== "job") return { mode: "process" }; | |
| 71 | const image = env["FORGE_CHECKS_IMAGE"]?.trim() ?? ""; | |
| 72 | const claim = env["FORGE_CHECKS_CLAIM"]?.trim() ?? ""; | |
| 73 | const nodeSelector = parseSelector(env["FORGE_CHECKS_NODE_SELECTOR"] ?? ""); | |
| 74 | const tolerations = parseTolerations(env["FORGE_CHECKS_TOLERATIONS"]?.trim() || "[]"); | |
| 69 | /** | |
| 70 | * The placement `prefix`_PLACEMENT, _IMAGE, _CLAIM, _NODE_SELECTOR and | |
| 71 | * _TOLERATIONS name. Checks read `FORGE_CHECKS`; a deploy's build reads | |
| 72 | * `FORGE_BUILD` the same way. | |
| 73 | */ | |
| 74 | export function placementFromEnv( | |
| 75 | env: Record<string, string | undefined> = process.env, | |
| 76 | prefix: "FORGE_CHECKS" | "FORGE_BUILD" = "FORGE_CHECKS", | |
| 77 | ): Placement { | |
| 78 | if (env[`${prefix}_PLACEMENT`]?.trim() !== "job") return { mode: "process" }; | |
| 79 | const image = env[`${prefix}_IMAGE`]?.trim() ?? ""; | |
| 80 | const claim = env[`${prefix}_CLAIM`]?.trim() ?? ""; | |
| 81 | const nodeSelector = parseSelector(env[`${prefix}_NODE_SELECTOR`] ?? ""); | |
| 82 | const tolerations = parseTolerations(env[`${prefix}_TOLERATIONS`]?.trim() || "[]"); | |
| 75 | 83 | // A job placement that cannot be built is not guessed at. |
| 76 | 84 | if (image === "" || /\s/.test(image) || claim === "" || !nodeSelector || !tolerations) return { mode: "process" }; |
| 77 | 85 | return { mode: "job", image, claim, nodeSelector, tolerations }; |
| 78 | 86 | } |
| 79 | 87 | |
| 88 | /** Where a deploy's install step runs; `FORGE_BUILD_*` in place of `FORGE_CHECKS_*`. */ | |
| 89 | export const buildPlacementFromEnv = (env: Record<string, string | undefined> = process.env): Placement => | |
| 90 | placementFromEnv(env, "FORGE_BUILD"); | |
| 91 | ||
| 80 | 92 | /** |
| 81 | 93 | * Where a run ran, in plain words, for a person to read. Nothing for the |
| 82 | 94 | * default `process` or a run that predates the record: only the unusual is |
src/http/server.ts +3
| @@ -435,6 +435,7 @@ import { sseStream, viewerStream } from "./sse.ts"; | ||
| 435 | 435 | import { Router } from "./router.ts"; |
| 436 | 436 | import { getUserById } from "../core/users.ts"; |
| 437 | 437 | import { appsRuntime } from "../apps/runtime.ts"; |
| 438 | import { treeDoor } from "../apps/build_door.ts"; | |
| 438 | 439 | import { |
| 439 | 440 | appWebSocket, |
| 440 | 441 | type AppSocket, |
| @@ -619,6 +620,8 @@ export function buildRouter(): Router<Handler> { | ||
| 619 | 620 | // The JS-free half of every destructive action. Two literal segments, so it |
| 620 | 621 | // is registered before /:owner/:name can claim the shape. |
| 621 | 622 | router.add("GET", "/-/confirm", confirmPage); |
| 623 | // A build Job's tree coming back, behind a one-time token (apps/build_door.ts). | |
| 624 | router.add("POST", "/-/build/:id/tree", (ctx) => treeDoor(ctx.request, ctx.params.id ?? "")); | |
| 622 | 625 | router.add("GET", "/new", newRepoPage); |
| 623 | 626 | router.add("GET", "/audit", auditPage); |
| 624 | 627 | router.add("GET", "/audit.csv", auditCsv); |
test/build-placement.test.ts added +201
| @@ -0,0 +1,201 @@ | ||
| 1 | /** | |
| 2 | * `FORGE_BUILD_PLACEMENT=job` (#1427): a deploy's install runs as a cluster | |
| 3 | * Job through a stand-in kube client, and its tree comes back as a tar | |
| 4 | * through the token door. The tar reader is proven against hostile archives. | |
| 5 | */ | |
| 6 | import { expect, test } from "bun:test"; | |
| 7 | import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, writeFileSync } from "node:fs"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { buildInJob } from "../src/apps/build_job.ts"; | |
| 10 | import { expectTree, treeDoor } from "../src/apps/build_door.ts"; | |
| 11 | import { extractTar } from "../src/apps/tar.ts"; | |
| 12 | import { buildPlacementFromEnv } from "../src/checks/placement.ts"; | |
| 13 | ||
| 14 | const tmp = (): string => mkdtempSync(join(process.env.TMPDIR ?? "/tmp", "build-")); | |
| 15 | ||
| 16 | /** A minimal ustar writer: [name, type, body or link target, mode]. */ | |
| 17 | function tar(entries: [string, string, string, number?][]): Uint8Array { | |
| 18 | const parts: Uint8Array[] = []; | |
| 19 | const enc = new TextEncoder(); | |
| 20 | for (const [name, type, content, mode = 0o644] of entries) { | |
| 21 | const head = new Uint8Array(512); | |
| 22 | const put = (s: string, at: number) => head.set(enc.encode(s), at); | |
| 23 | const body = type === "0" ? enc.encode(content) : new Uint8Array(); | |
| 24 | put(name, 0); | |
| 25 | put(mode.toString(8).padStart(7, "0"), 100); | |
| 26 | put(body.length.toString(8).padStart(11, "0"), 124); | |
| 27 | head[156] = type.charCodeAt(0); | |
| 28 | if (type === "2" || type === "1") put(content, 157); | |
| 29 | put("ustar", 257); | |
| 30 | put(" ", 148); | |
| 31 | put(head.reduce((a, b) => a + b, 0).toString(8).padStart(6, "0") + "\0 ", 148); | |
| 32 | parts.push(head, body, new Uint8Array((512 - (body.length % 512)) % 512)); | |
| 33 | } | |
| 34 | parts.push(new Uint8Array(1024)); | |
| 35 | return Buffer.concat(parts); | |
| 36 | } | |
| 37 | ||
| 38 | test("build placement reads FORGE_BUILD_*, and malformed leaves process", () => { | |
| 39 | const env = { FORGE_BUILD_PLACEMENT: "job", FORGE_BUILD_IMAGE: "oven/bun:1", FORGE_BUILD_CLAIM: "builds" }; | |
| 40 | expect(buildPlacementFromEnv({})).toEqual({ mode: "process" }); | |
| 41 | expect(buildPlacementFromEnv({ FORGE_CHECKS_PLACEMENT: "job", FORGE_CHECKS_IMAGE: "x", FORGE_CHECKS_CLAIM: "c" })).toEqual({ mode: "process" }); | |
| 42 | expect(buildPlacementFromEnv({ ...env, FORGE_BUILD_NODE_SELECTOR: "pool=ci" })).toEqual({ | |
| 43 | mode: "job", image: "oven/bun:1", claim: "builds", nodeSelector: { pool: "ci" }, tolerations: [], | |
| 44 | }); | |
| 45 | expect(buildPlacementFromEnv({ ...env, FORGE_BUILD_IMAGE: "" })).toEqual({ mode: "process" }); | |
| 46 | }); | |
| 47 | ||
| 48 | test("the tar reader makes files, directories, links and keeps the executable bit", async () => { | |
| 49 | const dir = tmp(); | |
| 50 | const r = await extractTar( | |
| 51 | tar([["app/", "5", ""], ["app/run.sh", "0", "echo hi", 0o755], ["app/ln", "2", "run.sh"], ["app/copy", "1", "app/run.sh"]]), | |
| 52 | dir, | |
| 53 | ); | |
| 54 | expect(r).toEqual({ ok: true, value: 4 }); | |
| 55 | expect(readFileSync(join(dir, "app/run.sh"), "utf8")).toBe("echo hi"); | |
| 56 | expect(lstatSync(join(dir, "app/run.sh")).mode & 0o111).not.toBe(0); | |
| 57 | expect(readlinkSync(join(dir, "app/ln"))).toBe("run.sh"); | |
| 58 | expect(readFileSync(join(dir, "app/copy"), "utf8")).toBe("echo hi"); | |
| 59 | }); | |
| 60 | ||
| 61 | test("the tar reader refuses names that leave the tree and writes through links", async () => { | |
| 62 | for (const name of ["../escape", "a/../../escape", "/abs"]) { | |
| 63 | const dir = tmp(); | |
| 64 | const r = await extractTar(tar([[name, "0", "x"]]), dir); | |
| 65 | expect(r.ok).toBe(false); | |
| 66 | } | |
| 67 | const root = tmp(); | |
| 68 | const dir = join(root, "tree"); | |
| 69 | const outside = join(root, "outside"); | |
| 70 | mkdirSync(dir); | |
| 71 | mkdirSync(outside); | |
| 72 | const r = await extractTar(tar([["evil", "2", outside], ["evil/pwned", "0", "x"]]), dir); | |
| 73 | expect(r).toEqual({ ok: false, error: "the tree writes through a link" }); | |
| 74 | expect(existsSync(join(outside, "pwned"))).toBe(false); | |
| 75 | // a link replaced by a directory of the same name is not trusted from before | |
| 76 | const again = await extractTar(tar([["d/", "5", ""], ["d/x", "0", "1"], ["d", "2", outside], ["d/pwned", "0", "x"]]), tmp()); | |
| 77 | expect(again.ok).toBe(false); | |
| 78 | expect(existsSync(join(outside, "pwned"))).toBe(false); | |
| 79 | }); | |
| 80 | ||
| 81 | test("the tar reader refuses what is not a tar and what is cut short", async () => { | |
| 82 | expect(await extractTar(new Uint8Array(512).fill(7), tmp())).toEqual({ ok: false, error: "the tree is not a tar" }); | |
| 83 | expect(await extractTar(tar([["a", "0", "x".repeat(2000)]]).subarray(0, 700), tmp())).toEqual({ ok: false, error: "the tree is cut short" }); | |
| 84 | }); | |
| 85 | ||
| 86 | test("the door takes one tree, once, for the right token only", async () => { | |
| 87 | const door = expectTree("abc", 60_000); | |
| 88 | const post = (token: string | null, id = "abc") => | |
| 89 | treeDoor(new Request("http://x/-/build/abc/tree", { method: "POST", body: "tree", headers: token === null ? {} : { authorization: `Bearer ${token}` } }), id); | |
| 90 | expect((await post(null)).status).toBe(403); | |
| 91 | expect((await post("wrong")).status).toBe(403); | |
| 92 | expect((await post(door.token, "other")).status).toBe(403); | |
| 93 | expect((await post(door.token)).status).toBe(204); | |
| 94 | expect(new TextDecoder().decode(await door.arrived)).toBe("tree"); | |
| 95 | expect((await post(door.token)).status).toBe(403); | |
| 96 | const late = expectTree("gone", 60_000); | |
| 97 | late.close(); | |
| 98 | expect((await treeDoor(new Request("http://x", { method: "POST", headers: { authorization: `Bearer ${late.token}` } }), "gone")).status).toBe(403); | |
| 99 | }); | |
| 100 | ||
| 101 | test("a body past the cap is refused and delivers nothing", async () => { | |
| 102 | const door = expectTree("big", 60_000); | |
| 103 | const r = await treeDoor( | |
| 104 | new Request("http://x", { method: "POST", body: "x", headers: { authorization: `Bearer ${door.token}`, "content-length": String(600 * 1024 * 1024) } }), | |
| 105 | "big", | |
| 106 | ); | |
| 107 | expect(r.status).toBe(413); | |
| 108 | door.close(); | |
| 109 | }); | |
| 110 | ||
| 111 | const placement = { mode: "job" as const, image: "oven/bun:1", claim: "builds", nodeSelector: { pool: "ci" }, tolerations: [] }; | |
| 112 | const limits = { memoryMiB: 512, cpus: 1, diskMiB: 512 }; | |
| 113 | ||
| 114 | /** A kube stand-in whose pod, once created, posts `tree` back as the Job's last step. */ | |
| 115 | function cluster(opts: { exit?: number; send?: (url: string, token: string) => Promise<void> }) { | |
| 116 | const created: any[] = []; | |
| 117 | const clock = { now: 0 }; | |
| 118 | const fetch = async (url: string, init: any) => { | |
| 119 | const path = new URL(url).pathname; | |
| 120 | if (init.method === "POST") { | |
| 121 | const job = JSON.parse(init.body); | |
| 122 | created.push(job); | |
| 123 | const env = Object.fromEntries(job.spec.template.spec.containers[0].env.map((e: any) => [e.name, e.value])); | |
| 124 | await opts.send?.(env.FORGE_BUILD_URL, env.FORGE_BUILD_TOKEN); | |
| 125 | return Response.json({}); | |
| 126 | } | |
| 127 | if (init.method === "DELETE") return Response.json({}); | |
| 128 | if (path.endsWith("/log")) return new Response("added 3 packages\n"); | |
| 129 | if (path.endsWith("/pods")) | |
| 130 | return Response.json({ items: [{ metadata: { name: "p" }, spec: { nodeName: "n1" }, status: { containerStatuses: [{ state: { terminated: { exitCode: opts.exit ?? 0 } } }] } }] }); | |
| 131 | return Response.json({ status: (opts.exit ?? 0) === 0 ? { succeeded: 1 } : { failed: 1 } }); | |
| 132 | }; | |
| 133 | return { created, options: { fetch, credentials: { server: "https://k", token: "t", namespace: "forge" }, now: () => clock.now, sleep: async () => {} } }; | |
| 134 | } | |
| 135 | const viaDoor = (bytes: Uint8Array) => async (url: string, token: string) => { | |
| 136 | const id = url.split("/")[5]!; | |
| 137 | const res = await treeDoor(new Request(url, { method: "POST", body: bytes, headers: { authorization: `Bearer ${token}` } }), id); | |
| 138 | expect(res.status).toBe(204); | |
| 139 | }; | |
| 140 | ||
| 141 | function input(dataDir: string, dir: string, extra: object) { | |
| 142 | const log: string[] = []; | |
| 143 | return { | |
| 144 | log, | |
| 145 | args: { id: "Run-1", dataDir, dir, install: "bun install", forgeUrl: "https://forge.test/", log: (l: string) => log.push(l), signal: new AbortController().signal, timeoutMs: 60_000, limits, ...extra }, | |
| 146 | }; | |
| 147 | } | |
| 148 | ||
| 149 | test("an install runs as a Job and its tree lands in the checkout", async () => { | |
| 150 | const dataDir = tmp(); | |
| 151 | const dir = join(dataDir, "checkout"); | |
| 152 | mkdirSync(dir); | |
| 153 | writeFileSync(join(dir, "package.json"), "{}"); | |
| 154 | const k = cluster({ send: viaDoor(tar([["package.json", "0", "{}"], ["node_modules/", "5", ""], ["node_modules/dep/index.js", "0", "module.exports=1"]])) }); | |
| 155 | const { args, log } = input(dataDir, dir, { options: k.options, stepEnv: { FORGE_APP_ENV: "preview" } }); | |
| 156 | const r = await buildInJob(placement, args); | |
| 157 | expect(r).toEqual({ ok: true, value: undefined }); | |
| 158 | expect(readFileSync(join(dir, "node_modules/dep/index.js"), "utf8")).toBe("module.exports=1"); | |
| 159 | expect(existsSync(join(dataDir, "builds", "run1"))).toBe(false); | |
| 160 | const pod = k.created[0].spec.template.spec; | |
| 161 | expect(k.created[0].metadata.name).toBe("build-run1"); | |
| 162 | expect(pod.nodeSelector).toEqual({ pool: "ci" }); | |
| 163 | expect(pod.volumes[0].persistentVolumeClaim.claimName).toBe("builds"); | |
| 164 | expect(pod.containers[0].volumeMounts[0]).toEqual({ name: "work", mountPath: join(dataDir, "builds", "run1"), subPath: "run1" }); | |
| 165 | const env = Object.fromEntries(pod.containers[0].env.map((e: any) => [e.name, e.value])); | |
| 166 | expect(env.FORGE_BUILD_URL).toBe("https://forge.test/-/build/run1/tree"); | |
| 167 | expect(Object.keys(env).sort()).toEqual(["CI", "FORGE_APP_ENV", "FORGE_BUILD_TOKEN", "FORGE_BUILD_URL"]); | |
| 168 | expect(pod.containers[0].command[2]).toContain("bun install"); | |
| 169 | expect(log).toContain("added 3 packages"); | |
| 170 | expect(log.some((l) => l.includes("on n1"))).toBe(true); | |
| 171 | }); | |
| 172 | ||
| 173 | test("a failing install fails the deploy and unpacks nothing", async () => { | |
| 174 | const dataDir = tmp(); | |
| 175 | const dir = join(dataDir, "checkout"); | |
| 176 | mkdirSync(dir); | |
| 177 | const k = cluster({ exit: 2 }); | |
| 178 | const { args } = input(dataDir, dir, { options: k.options }); | |
| 179 | expect(await buildInJob(placement, args)).toEqual({ ok: false, error: "install exited with code 2" }); | |
| 180 | expect(existsSync(join(dataDir, "builds", "run1"))).toBe(false); | |
| 181 | }); | |
| 182 | ||
| 183 | test("a Job that ends without sending a tree is a failed build", async () => { | |
| 184 | const dataDir = tmp(); | |
| 185 | const dir = join(dataDir, "checkout"); | |
| 186 | mkdirSync(dir); | |
| 187 | const k = cluster({}); | |
| 188 | const { args } = input(dataDir, dir, { options: k.options, treeWaitMs: 10 }); | |
| 189 | expect(await buildInJob(placement, args)).toEqual({ ok: false, error: "the build finished but sent no tree back" }); | |
| 190 | }); | |
| 191 | ||
| 192 | test("a hostile tree is refused and the build fails", async () => { | |
| 193 | const dataDir = tmp(); | |
| 194 | const dir = join(dataDir, "checkout"); | |
| 195 | mkdirSync(dir); | |
| 196 | const k = cluster({ send: viaDoor(tar([["../../escape", "0", "x"]])) }); | |
| 197 | const { args } = input(dataDir, dir, { options: k.options }); | |
| 198 | const r = await buildInJob(placement, args); | |
| 199 | expect(r.ok).toBe(false); | |
| 200 | expect(existsSync(join(dataDir, "escape"))).toBe(false); | |
| 201 | }); |
test/build-wiring.test.ts added +180
| @@ -0,0 +1,180 @@ | ||
| 1 | /** | |
| 2 | * The wiring of `FORGE_BUILD_PLACEMENT=job` (#1427): a deploy's install goes | |
| 3 | * to the Job and not to a cell, through `startProcess` and through the | |
| 4 | * runtime; a warm start builds nothing; a relative link survives the trip. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 7 | import { existsSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, symlinkSync, writeFileSync } from "node:fs"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { AppsRuntime } from "../src/apps/runtime.ts"; | |
| 11 | import { startProcess } from "../src/apps/process.ts"; | |
| 12 | import { treeDoor } from "../src/apps/build_door.ts"; | |
| 13 | import { buildInJob } from "../src/apps/build_job.ts"; | |
| 14 | import type { AppManifest } from "../src/apps/manifest.ts"; | |
| 15 | import { enableApp } from "../src/actions/apps.ts"; | |
| 16 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 17 | import { createUser, type User } from "../src/core/users.ts"; | |
| 18 | import { listRuns, type Run } from "../src/core/runs.ts"; | |
| 19 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 20 | import { readRunLog } from "../src/runs/log.ts"; | |
| 21 | ||
| 22 | const tmp = (): string => mkdtempSync(join(process.env.TMPDIR ?? "/tmp", "wire-")); | |
| 23 | ||
| 24 | function tar(entries: [string, string, string][]): Uint8Array { | |
| 25 | const parts: Uint8Array[] = []; | |
| 26 | const enc = new TextEncoder(); | |
| 27 | for (const [name, type, content] of entries) { | |
| 28 | const head = new Uint8Array(512); | |
| 29 | const put = (s: string, at: number) => head.set(enc.encode(s), at); | |
| 30 | const body = type === "0" ? enc.encode(content) : new Uint8Array(); | |
| 31 | put(name, 0); | |
| 32 | put("0000644", 100); | |
| 33 | put(body.length.toString(8).padStart(11, "0"), 124); | |
| 34 | head[156] = type.charCodeAt(0); | |
| 35 | if (type === "2") put(content, 157); | |
| 36 | put("ustar", 257); | |
| 37 | put(" ", 148); | |
| 38 | put(head.reduce((a, b) => a + b, 0).toString(8).padStart(6, "0") + "\0 ", 148); | |
| 39 | parts.push(head, body, new Uint8Array((512 - (body.length % 512)) % 512)); | |
| 40 | } | |
| 41 | parts.push(new Uint8Array(1024)); | |
| 42 | return Buffer.concat(parts); | |
| 43 | } | |
| 44 | ||
| 45 | const placement = { mode: "job" as const, image: "oven/bun:1", claim: "builds", nodeSelector: {}, tolerations: [] }; | |
| 46 | ||
| 47 | /** A kube stand-in: the pod posts `bytes` through the door, and `seen` keeps what ran. */ | |
| 48 | function cluster(bytes: Uint8Array, seen: { jobs: any[] } = { jobs: [] }) { | |
| 49 | const fetch = async (url: string, init: any) => { | |
| 50 | const path = new URL(url).pathname; | |
| 51 | if (init.method === "POST") { | |
| 52 | const job = JSON.parse(init.body); | |
| 53 | seen.jobs.push(job); | |
| 54 | const env = Object.fromEntries(job.spec.template.spec.containers[0].env.map((e: any) => [e.name, e.value])); | |
| 55 | const res = await treeDoor( | |
| 56 | new Request(env.FORGE_BUILD_URL, { method: "POST", body: bytes, headers: { authorization: `Bearer ${env.FORGE_BUILD_TOKEN}` } }), | |
| 57 | env.FORGE_BUILD_URL.split("/")[5], | |
| 58 | ); | |
| 59 | expect(res.status).toBe(204); | |
| 60 | return Response.json({}); | |
| 61 | } | |
| 62 | if (init.method === "DELETE") return Response.json({}); | |
| 63 | if (path.endsWith("/log")) return new Response(""); | |
| 64 | if (path.endsWith("/pods")) | |
| 65 | return Response.json({ items: [{ metadata: { name: "p" }, spec: { nodeName: "n1" }, status: { containerStatuses: [{ state: { terminated: { exitCode: 0 } } }] } }] }); | |
| 66 | return Response.json({ status: { succeeded: 1 } }); | |
| 67 | }; | |
| 68 | return { seen, options: { fetch, credentials: { server: "https://k", token: "t", namespace: "forge" }, now: () => 0, sleep: async () => {} } }; | |
| 69 | } | |
| 70 | ||
| 71 | test("a relative link in the checkout is copied as written and comes back as written", async () => { | |
| 72 | const dataDir = tmp(); | |
| 73 | const dir = join(dataDir, "checkout"); | |
| 74 | mkdirSync(join(dir, "sub"), { recursive: true }); | |
| 75 | writeFileSync(join(dir, "target"), "t"); | |
| 76 | symlinkSync("../target", join(dir, "sub", "rel")); | |
| 77 | const seen: { jobs: any[] } = { jobs: [] }; | |
| 78 | // The pod sees the copy: read the link from where the Job would mount it. | |
| 79 | let inPod = ""; | |
| 80 | const k = cluster(tar([["sub/", "5", ""], ["sub/rel", "2", "../target"]]), seen); | |
| 81 | const inner = k.options.fetch; | |
| 82 | k.options.fetch = async (url: string, init: any) => { | |
| 83 | if (init.method === "POST") inPod = readlinkSync(join(dataDir, "builds", "run1", "sub", "rel")); | |
| 84 | return inner(url, init); | |
| 85 | }; | |
| 86 | const r = await buildInJob(placement, { | |
| 87 | id: "run1", dataDir, dir, install: "true", forgeUrl: "https://forge.test", log: () => {}, | |
| 88 | signal: new AbortController().signal, timeoutMs: 60_000, limits: { memoryMiB: 512, cpus: 1, diskMiB: 512 }, options: k.options, | |
| 89 | }); | |
| 90 | expect(r.ok).toBe(true); | |
| 91 | expect(inPod).toBe("../target"); | |
| 92 | expect(readlinkSync(join(dir, "sub", "rel"))).toBe("../target"); | |
| 93 | }); | |
| 94 | ||
| 95 | const manifest: AppManifest = { | |
| 96 | run: "true", install: "echo in-cell-install", test: null, health: "/", ready: 2, tty: null, service: null, looks: ["/"], | |
| 97 | }; | |
| 98 | ||
| 99 | test("startProcess sends the install to the hook, and a warm start does not build", async () => { | |
| 100 | const dir = tmp(); | |
| 101 | const base = { | |
| 102 | dir, dataDir: dir, manifest, env: "production" as const, url: "http://app.test", commitOid: "0".repeat(40), | |
| 103 | forgeUrl: "http://forge.test", identityKey: "key", signal: new AbortController().signal, | |
| 104 | }; | |
| 105 | const calls: string[] = []; | |
| 106 | const log: string[] = []; | |
| 107 | const install = async (c: string) => { | |
| 108 | calls.push(c); | |
| 109 | return { ok: true as const, value: undefined }; | |
| 110 | }; | |
| 111 | await startProcess({ ...base, log: (l) => log.push(l), install }); | |
| 112 | expect(calls).toEqual(["echo in-cell-install"]); | |
| 113 | expect(log.some((l) => l.includes("$ echo in-cell-install"))).toBe(false); | |
| 114 | await startProcess({ ...base, log: () => {}, install, warm: true }); | |
| 115 | expect(calls).toHaveLength(1); | |
| 116 | // a failed hook fails the install stage | |
| 117 | const failed = await startProcess({ ...base, log: () => {}, install: async () => ({ ok: false as const, error: "no" }) }); | |
| 118 | expect(failed).toEqual({ ok: false, error: { stage: "install", message: "no" } }); | |
| 119 | }); | |
| 120 | ||
| 121 | let dataDir: string; | |
| 122 | let app: App; | |
| 123 | let servers: Servers; | |
| 124 | let runtime: AppsRuntime; | |
| 125 | let alice: User; | |
| 126 | const seen: { jobs: any[] } = { jobs: [] }; | |
| 127 | ||
| 128 | beforeAll(async () => { | |
| 129 | dataDir = tmp(); | |
| 130 | app = createApp({ dataDir, port: 0 }); | |
| 131 | servers = await serve(app); | |
| 132 | const k = cluster( | |
| 133 | tar([["run.sh", "0", "exec bun -e \"Bun.serve({port:Number(process.env.PORT),hostname:'127.0.0.1',fetch:()=>new Response('ok')})\"\n"]]), | |
| 134 | seen, | |
| 135 | ); | |
| 136 | runtime = new AppsRuntime(app, { | |
| 137 | domain: "wire.test", scheme: "http", publicPort: servers.port, forgeUrl: servers.url, concurrency: 1, | |
| 138 | buildPlacement: placement, buildJob: k.options, | |
| 139 | }); | |
| 140 | await runtime.start(); | |
| 141 | const created = await createUser(app.db, { trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 142 | if (!created.ok) throw new Error(created.error); | |
| 143 | alice = created.value; | |
| 144 | }, 30_000); | |
| 145 | ||
| 146 | afterAll(async () => { | |
| 147 | await runtime.stop(); | |
| 148 | servers.stop(); | |
| 149 | app.close(); | |
| 150 | }); | |
| 151 | ||
| 152 | test("a deploy through the runtime installs in the Job, not in a cell", async () => { | |
| 153 | const made = await createRepo(app, alice, { name: "jobbed", visibility: "public" }); | |
| 154 | if (!made.ok) throw new Error(made.error); | |
| 155 | const repo = made.value; | |
| 156 | await commitToBranch(app, alice, repo, { | |
| 157 | message: "An app", | |
| 158 | files: [{ path: "forge.json", content: JSON.stringify({ app: { run: "sh run.sh", install: "echo in-cell-install", health: "/", ready: 5 } }) }], | |
| 159 | }); | |
| 160 | expect(enableApp(app, alice, repo, {}).ok).toBe(true); | |
| 161 | let run: Run | undefined; | |
| 162 | const deadline = Date.now() + 40_000; | |
| 163 | while (Date.now() < deadline) { | |
| 164 | run = listRuns(app.db, repo.id, { kind: "deploy", limit: 5 }).find((r) => r.env === "production"); | |
| 165 | if (run && ["ok", "failed", "cancelled"].includes(run.state)) break; | |
| 166 | await Bun.sleep(50); | |
| 167 | } | |
| 168 | const text = readRunLog(dataDir, run!.id).lines.join("\n"); | |
| 169 | expect(run!.state).toBe("ok"); | |
| 170 | expect(seen.jobs).toHaveLength(1); | |
| 171 | const pod = seen.jobs[0].spec.template.spec.containers[0]; | |
| 172 | expect(pod.command[2]).toContain("echo in-cell-install"); | |
| 173 | // the run id names the door the pod posts to | |
| 174 | const word = run!.id.toLowerCase().replace(/[^a-z0-9]/g, ""); | |
| 175 | expect(pod.env.find((e: any) => e.name === "FORGE_BUILD_URL").value).toContain(`/-/build/${word}/tree`); | |
| 176 | expect(pod.env.find((e: any) => e.name === "FORGE_APP_ENV").value).toBe("production"); | |
| 177 | expect(text).toContain("(as a cluster job)"); | |
| 178 | expect(text).not.toContain("$ echo in-cell-install\n"); | |
| 179 | expect(existsSync(join(dataDir, "builds", word))).toBe(false); | |
| 180 | }, 60_000); |
new above
offline
Without
verbatimSymlinks: true, every relative symlink in the checkout is rewritten to an absolute path intoinput.dir. That path is missing in the pod and wrong after the tar comes back. AddverbatimSymlinks: trueand a round-trip test.