Public: anyone can read this; the crew can change it.
Hold a lane Job to its declared egress hosts, as a cell is #1947
scout/forge:scout/1428-hold-a-lane-job-to-its-declared-egress-h → main 4 commits fork
11 files
changed +495
−26
charts/app/templates/lane.yaml added +70
| @@ -0,0 +1,70 @@ | ||
| 1 | {{- if .Values.lane.egressProxy }} | |
| 2 | # A check placed as a Job (FORGE_CHECKS_PLACEMENT=job) is held to the hosts | |
| 3 | # its forge.json declares by the forge's egress proxy, which runs in a pod of | |
| 4 | # its own (FORGE_CHECKS_PROXY_IMAGE). Two policies make that the only way out: | |
| 5 | # the check's pod may reach the proxy's pod and nothing else, and the proxy's | |
| 6 | # pod may reach the public web and the forge (the proxy itself refuses | |
| 7 | # undeclared hosts and private addresses). Enable it only with the proxy image | |
| 8 | # set, or a Job has no way out at all. | |
| 9 | apiVersion: networking.k8s.io/v1 | |
| 10 | kind: NetworkPolicy | |
| 11 | metadata: | |
| 12 | name: {{ .Release.Name }}-lane-job | |
| 13 | spec: | |
| 14 | podSelector: | |
| 15 | matchLabels: | |
| 16 | forge-check: "true" | |
| 17 | policyTypes: [Ingress, Egress] | |
| 18 | egress: | |
| 19 | - to: | |
| 20 | - podSelector: | |
| 21 | matchLabels: | |
| 22 | forge-check-egress: "true" | |
| 23 | ports: | |
| 24 | - protocol: TCP | |
| 25 | port: 3128 | |
| 26 | ||
| 27 | apiVersion: networking.k8s.io/v1 | |
| 28 | kind: NetworkPolicy | |
| 29 | metadata: | |
| 30 | name: {{ .Release.Name }}-lane-proxy | |
| 31 | spec: | |
| 32 | podSelector: | |
| 33 | matchLabels: | |
| 34 | forge-check-egress: "true" | |
| 35 | policyTypes: [Ingress, Egress] | |
| 36 | ingress: | |
| 37 | - from: | |
| 38 | - podSelector: | |
| 39 | matchLabels: | |
| 40 | forge-check: "true" | |
| 41 | ports: | |
| 42 | - protocol: TCP | |
| 43 | port: 3128 | |
| 44 | egress: | |
| 45 | - to: | |
| 46 | - namespaceSelector: | |
| 47 | matchLabels: | |
| 48 | kubernetes.io/metadata.name: kube-system | |
| 49 | ports: | |
| 50 | - protocol: UDP | |
| 51 | port: 53 | |
| 52 | - protocol: TCP | |
| 53 | port: 53 | |
| 54 | - to: | |
| 55 | - podSelector: | |
| 56 | matchLabels: | |
| 57 | app: {{ .Release.Name }} | |
| 58 | ports: | |
| 59 | - protocol: TCP | |
| 60 | port: 8080 | |
| 61 | - to: | |
| 62 | - ipBlock: | |
| 63 | cidr: 0.0.0.0/0 | |
| 64 | except: [10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16, 100.64.0.0/10] | |
| 65 | ports: | |
| 66 | - protocol: TCP | |
| 67 | port: 80 | |
| 68 | - protocol: TCP | |
| 69 | port: 443 | |
| 70 | {{- end }} |
charts/app/values.yaml +6
| @@ -44,6 +44,12 @@ forge: | ||
| 44 | 44 | # App deploys at once. |
| 45 | 45 | appsConcurrency: 3 |
| 46 | 46 | |
| 47 | lane: | |
| 48 | # Hold a check placed as a Job to its declared egress: NetworkPolicies that | |
| 49 | # leave the check's pod only the forge's egress proxy pod (templates/lane.yaml). | |
| 50 | # Turn on together with FORGE_CHECKS_PROXY_IMAGE. | |
| 51 | egressProxy: false | |
| 52 | ||
| 47 | 53 | ssh: |
| 48 | 54 | # The platform edge's raw-TCP entrypoint this forge claims. Plain SSH has |
| 49 | 55 | # no SNI, so an entrypoint fronts exactly one backend. |
docs/APPS.md +13 −4
| @@ -370,10 +370,18 @@ records `placement` and the `node` its pod ran on. A malformed setting leaves | ||
| 370 | 370 | `process` in place. No cell wraps a Job. The pod mounts only its own |
| 371 | 371 | checkout (`subPath` = the run id), mounts no service-account token, runs |
| 372 | 372 | non-root without privilege escalation, and carries the check's limits as |
| 373 | `resources.limits`. **Egress is not enforced by the forge on a Job**: the | |
| 374 | run is recorded as uncontained ("egress not enforced on a cluster job"), and | |
| 375 | the pod carries the label `forge-check=true` so an operator's NetworkPolicy | |
| 376 | can select it and hold what `egress` declares. | |
| 373 | `resources.limits`. **Egress on a Job** is held when | |
| 374 | `FORGE_CHECKS_PROXY_IMAGE` (the forge's own image) is set: before the Job, the | |
| 375 | forge starts a pod of its own running the egress proxy | |
| 376 | (`src/apps/egress_proxy.ts`) with the declared hosts, the registry and the | |
| 377 | forge's origin, then makes the Job with `HTTP(S)_PROXY` pointing at that pod, | |
| 378 | and deletes both at the end. An undeclared host is refused, or, while | |
| 379 | `cells.egress` is `report`, let through and recorded as a cell's is. The proxy | |
| 380 | cannot make the pod's network closed by itself: the chart's `lane.egressProxy` | |
| 381 | policies (`charts/app/templates/lane.yaml`) leave the Job pod (`forge-check=true`) | |
| 382 | only the proxy pod (`forge-check-egress=true`) on port 3128. Without the proxy | |
| 383 | image the run is recorded as uncontained ("egress not enforced on a cluster | |
| 384 | job") and the `forge-check=true` label is all an operator's policy has. | |
| 377 | 385 | |
| 378 | 386 | Checks share `FORGE_CHECKS_CONCURRENCY` slots (default `1`), and when one |
| 379 | 387 | frees, it goes to the most recently requested check waiting, not the one |
| @@ -1097,6 +1105,7 @@ a link to the milestone (`docs/PLANNING.md`); its progress never does. | ||
| 1097 | 1105 | | `FORGE_CREW_CONCURRENCY` | `2` | agent runs at once (live: Settings → Capacity) | |
| 1098 | 1106 | | `FORGE_CHECKS_CONCURRENCY` | `1` | checks at once (live: Settings → Capacity) | |
| 1099 | 1107 | | `FORGE_CHECKS_PLACEMENT` | `process` | `job` runs a check's commands as a cluster Job (see Placement above) | |
| 1108 | | `FORGE_CHECKS_PROXY_IMAGE` | unset | the forge's image: a Job is held to its declared egress by a proxy pod | | |
| 1100 | 1109 | | `FORGE_CHECKS_DRAIN_S` | `300` | seconds a roll lets running checks finish first | |
| 1101 | 1110 | | `FORGE_CHECK_SHARDS` | the machine's cores | test shards per check (live: Settings → Capacity) | |
| 1102 | 1111 | | `FORGE_CELLS_EGRESS` | `enforce` | `report` lets undeclared egress through on 80/443 (live: Settings → Capacity) | |
scripts/gate.ts +1
| @@ -345,6 +345,7 @@ export const GATE: readonly string[] = [ | ||
| 345 | 345 | |
| 346 | 346 | export const EXCLUDED: readonly Exclusion[] = [ |
| 347 | 347 | { file: "test/crew-sandbox-real.test.ts", reason: "landed unlisted and red locally; the builder admits it", issue: 1238 }, |
| 348 | { file: "test/job-egress.test.ts", reason: "not yet admitted", issue: 1428 }, | |
| 348 | 349 | { file: "test/api-errors.test.ts", reason: "not yet admitted", issue: 261 }, |
| 349 | 350 | { file: "test/apps-api.test.ts", reason: "not yet admitted", issue: 261 }, |
| 350 | 351 | { |
src/apps/egress.ts +16 −12
| @@ -305,16 +305,17 @@ async function open( | ||
| 305 | 305 | } |
| 306 | 306 | } |
| 307 | 307 | |
| 308 | /** Listen at `path` and forward only what `policy` allows. */ | |
| 308 | /** | |
| 309 | * Listen at `path` (a Unix socket) or on a TCP port (a proxy in a pod of its | |
| 310 | * own, `apps/egress_proxy.ts`) and forward only what `policy` allows. | |
| 311 | */ | |
| 309 | 312 | export function startEgress( |
| 310 | path: string, | |
| 313 | path: string | { readonly tcp: number }, | |
| 311 | 314 | policy: EgressPolicy, |
| 312 | 315 | log: (line: string) => void = () => {}, |
| 313 | 316 | ): Egress { |
| 314 | const server = Bun.listen<Conn>({ | |
| 315 | unix: path, | |
| 316 | socket: { | |
| 317 | open(client) { | |
| 317 | const handlers = { | |
| 318 | open(client: Socket<Conn>) { | |
| 318 | 319 | client.data = { |
| 319 | 320 | head: new Uint8Array(0), |
| 320 | 321 | peer: undefined, |
| @@ -323,7 +324,7 @@ export function startEgress( | ||
| 323 | 324 | done: false, |
| 324 | 325 | }; |
| 325 | 326 | }, |
| 326 | data(client, chunk) { | |
| 327 | data(client: Socket<Conn>, chunk: Uint8Array) { | |
| 327 | 328 | const conn = client.data; |
| 328 | 329 | if (conn.peer !== undefined) { |
| 329 | 330 | send(conn.peer, conn.toPeer, chunk); |
| @@ -346,19 +347,22 @@ export function startEgress( | ||
| 346 | 347 | } |
| 347 | 348 | void open(client, policy, log); |
| 348 | 349 | }, |
| 349 | drain(client) { | |
| 350 | drain(client: Socket<Conn>) { | |
| 350 | 351 | flush(client, client.data.toClient); |
| 351 | 352 | }, |
| 352 | close(client) { | |
| 353 | close(client: Socket<Conn>) { | |
| 353 | 354 | client.data.done = true; |
| 354 | 355 | client.data.peer?.end(); |
| 355 | 356 | }, |
| 356 | error(client) { | |
| 357 | error(client: Socket<Conn>) { | |
| 357 | 358 | client.data.done = true; |
| 358 | 359 | client.data.peer?.end(); |
| 359 | 360 | }, |
| 360 | }, | |
| 361 | }); | |
| 361 | }; | |
| 362 | const server = | |
| 363 | typeof path === "string" | |
| 364 | ? Bun.listen<Conn>({ unix: path, socket: handlers }) | |
| 365 | : Bun.listen<Conn>({ hostname: "0.0.0.0", port: path.tcp, socket: handlers }); | |
| 362 | 366 | return { close: () => server.stop(true) }; |
| 363 | 367 | } |
| 364 | 368 |
src/apps/egress_proxy.ts added +76
| @@ -0,0 +1,76 @@ | ||
| 1 | /** | |
| 2 | * The egress proxy as a process of its own: what a cluster check's pod | |
| 3 | * reaches the world through (`cluster/jobs.ts`). Configured from the | |
| 4 | * environment, validated here at the boundary: | |
| 5 | * FORGE_EGRESS_HOSTS a JSON list of declared hosts (`apps/egress.ts` forms) | |
| 6 | * FORGE_EGRESS_ORIGINS a JSON list of `host:port` always reachable (the forge) | |
| 7 | * FORGE_EGRESS_MODE `enforce` (default) or `report` | |
| 8 | * FORGE_EGRESS_PORT the TCP port, 3128 by default | |
| 9 | * An undeclared host let through in `report` mode is written as one | |
| 10 | * `forge-reached {"host":…,"port":…}` line, which the forge reads back from | |
| 11 | * the pod's log when the check ends. | |
| 12 | */ | |
| 13 | import { startEgress, type EgressPolicy } from "./egress.ts"; | |
| 14 | ||
| 15 | export const REACHED_PREFIX = "forge-reached "; | |
| 16 | ||
| 17 | function list(text: string | undefined): string[] | undefined { | |
| 18 | try { | |
| 19 | const value: unknown = JSON.parse(text ?? "[]"); | |
| 20 | if (!Array.isArray(value) || value.length > 200) return undefined; | |
| 21 | if (!value.every((v) => typeof v === "string" && v.length < 256 && !/[\s\x00-\x1f]/.test(v))) return undefined; | |
| 22 | return value as string[]; | |
| 23 | } catch { | |
| 24 | return undefined; | |
| 25 | } | |
| 26 | } | |
| 27 | ||
| 28 | /** The policy an environment describes, or the reason it is refused. */ | |
| 29 | export function policyFromEnv( | |
| 30 | env: Record<string, string | undefined>, | |
| 31 | print: (line: string) => void = console.log, | |
| 32 | ): EgressPolicy | string { | |
| 33 | const hosts = list(env["FORGE_EGRESS_HOSTS"]); | |
| 34 | const raw = list(env["FORGE_EGRESS_ORIGINS"]); | |
| 35 | if (hosts === undefined) return "FORGE_EGRESS_HOSTS is not a list of host names"; | |
| 36 | if (raw === undefined) return "FORGE_EGRESS_ORIGINS is not a list of host:port"; | |
| 37 | const origins: { host: string; port: number }[] = []; | |
| 38 | for (const entry of raw) { | |
| 39 | const at = entry.lastIndexOf(":"); | |
| 40 | const port = Number(entry.slice(at + 1)); | |
| 41 | if (at < 1 || !Number.isInteger(port) || port < 1 || port > 65535) return `bad origin ${entry}`; | |
| 42 | origins.push({ host: entry.slice(0, at).replace(/^\[|\]$/g, ""), port }); | |
| 43 | } | |
| 44 | const report = | |
| 45 | env["FORGE_EGRESS_MODE"] === "report" | |
| 46 | ? (host: string, port: number) => print(`${REACHED_PREFIX}${JSON.stringify({ host, port })}`) | |
| 47 | : undefined; | |
| 48 | return { hosts, origins, report }; | |
| 49 | } | |
| 50 | ||
| 51 | /** The hosts a proxy's log says were reached undeclared. */ | |
| 52 | export function reachedFromLog(lines: readonly string[]): { host: string; port: number }[] { | |
| 53 | const out: { host: string; port: number }[] = []; | |
| 54 | for (const line of lines) { | |
| 55 | if (!line.startsWith(REACHED_PREFIX) || out.length >= 100) continue; | |
| 56 | try { | |
| 57 | const r = JSON.parse(line.slice(REACHED_PREFIX.length)) as { host?: unknown; port?: unknown }; | |
| 58 | if (typeof r.host === "string" && r.host.length < 256 && typeof r.port === "number" && Number.isInteger(r.port)) | |
| 59 | out.push({ host: r.host, port: r.port }); | |
| 60 | } catch { | |
| 61 | // a line that is not ours | |
| 62 | } | |
| 63 | } | |
| 64 | return out; | |
| 65 | } | |
| 66 | ||
| 67 | if (import.meta.main) { | |
| 68 | const policy = policyFromEnv(process.env); | |
| 69 | if (typeof policy === "string") { | |
| 70 | console.error(policy); | |
| 71 | process.exit(2); | |
| 72 | } | |
| 73 | const port = Number(process.env["FORGE_EGRESS_PORT"] ?? "3128"); | |
| 74 | startEgress({ tcp: port }, policy, (line) => console.log(line)); | |
| 75 | console.log(`egress proxy on :${port}`); | |
| 76 | } |
src/checks/job_step.ts +24
| @@ -10,6 +10,19 @@ import type { Placement } from "./placement.ts"; | ||
| 10 | 10 | |
| 11 | 11 | /** What a NetworkPolicy selects a check's pod by (docs/APPS.md, Placement). */ |
| 12 | 12 | export const JOB_LABELS = { "forge-check": "true" }; |
| 13 | /** What a NetworkPolicy selects the egress proxy's pod by. */ | |
| 14 | export const PROXY_LABELS = { "forge-check-egress": "true" }; | |
| 15 | ||
| 16 | /** The forge's own address as the `host:port` the proxy always lets through; none if it is not a URL. */ | |
| 17 | export function forgeOrigins(url: string): string[] { | |
| 18 | try { | |
| 19 | const u = new URL(url); | |
| 20 | const port = u.port || (u.protocol === "https:" ? "443" : "80"); | |
| 21 | return [`${u.hostname.replace(/^\[|\]$/g, "")}:${port}`]; | |
| 22 | } catch { | |
| 23 | return []; | |
| 24 | } | |
| 25 | } | |
| 13 | 26 | |
| 14 | 27 | /** The error a vanished Job answers with; the service queues the run again. */ |
| 15 | 28 | export const JOB_VANISHED = "the cluster job vanished"; |
| @@ -28,6 +41,10 @@ export async function runJobStep( | ||
| 28 | 41 | /** The Job's own output, apart from the echoed commands. */ |
| 29 | 42 | output: string[]; |
| 30 | 43 | onNode: (node: string) => void; |
| 44 | /** Held to these when the placement has a proxy image. */ | |
| 45 | egress?: { hosts: string[]; origins: string[]; mode: "enforce" | "report" }; | |
| 46 | /** Told each undeclared host the proxy let through while egress is only reported. */ | |
| 47 | onReached?: (host: string, port: number) => void; | |
| 31 | 48 | options?: JobOptions; |
| 32 | 49 | }, |
| 33 | 50 | ): Promise<Result<void, string>> { |
| @@ -44,6 +61,9 @@ export async function runJobStep( | ||
| 44 | 61 | volume: { claim: placement.claim, mountPath: input.dir, subPath: input.runId }, |
| 45 | 62 | limits: input.limits, |
| 46 | 63 | labels: JOB_LABELS, |
| 64 | ...(placement.proxyImage === undefined || input.egress === undefined | |
| 65 | ? {} | |
| 66 | : { proxy: { image: placement.proxyImage, labels: PROXY_LABELS, ...input.egress } }), | |
| 47 | 67 | }; |
| 48 | 68 | for (const c of input.commands) input.log(`$ ${c}`); |
| 49 | 69 | let result; |
| @@ -58,6 +78,10 @@ export async function runJobStep( | ||
| 58 | 78 | return err(`job could not run: ${error instanceof Error ? error.message : String(error)}`); |
| 59 | 79 | } |
| 60 | 80 | if (result.node) input.onNode(result.node); |
| 81 | for (const r of result.reached ?? []) { | |
| 82 | input.log(`egress reported: ${r.host}:${r.port} is not in forge.json "egress" (let through while egress is only reported)`); | |
| 83 | input.onReached?.(r.host, r.port); | |
| 84 | } | |
| 61 | 85 | for (const line of result.lines) { |
| 62 | 86 | input.output.push(line); |
| 63 | 87 | input.log(line); |
src/checks/placement.ts +8 −1
| @@ -8,6 +8,8 @@ | ||
| 8 | 8 | * FORGE_CHECKS_CLAIM a ReadWriteMany claim holding the checks root |
| 9 | 9 | * FORGE_CHECKS_NODE_SELECTOR key=value,key=value |
| 10 | 10 | * FORGE_CHECKS_TOLERATIONS a JSON list of tolerations |
| 11 | * FORGE_CHECKS_PROXY_IMAGE the forge's own image: with it, a Job is held | |
| 12 | * to its declared egress by a proxy pod | |
| 11 | 13 | */ |
| 12 | 14 | import type { Toleration } from "../cluster/jobs.ts"; |
| 13 | 15 | |
| @@ -19,6 +21,8 @@ export type Placement = | ||
| 19 | 21 | readonly claim: string; |
| 20 | 22 | readonly nodeSelector: Record<string, string>; |
| 21 | 23 | readonly tolerations: Toleration[]; |
| 24 | /** Set: the Job reaches only what it declared, through a proxy pod of this image. */ | |
| 25 | readonly proxyImage?: string; | |
| 22 | 26 | }; |
| 23 | 27 | |
| 24 | 28 | const LABEL = /^[A-Za-z0-9]([-A-Za-z0-9_./]{0,61}[A-Za-z0-9])?$/; |
| @@ -74,7 +78,10 @@ export function placementFromEnv(env: Record<string, string | undefined> = proce | ||
| 74 | 78 | const tolerations = parseTolerations(env["FORGE_CHECKS_TOLERATIONS"]?.trim() || "[]"); |
| 75 | 79 | // A job placement that cannot be built is not guessed at. |
| 76 | 80 | if (image === "" || /\s/.test(image) || claim === "" || !nodeSelector || !tolerations) return { mode: "process" }; |
| 77 | return { mode: "job", image, claim, nodeSelector, tolerations }; | |
| 81 | const proxyImage = env["FORGE_CHECKS_PROXY_IMAGE"]?.trim() ?? ""; | |
| 82 | // A proxy image that cannot be used is not run unheld: the placement falls back too. | |
| 83 | if (/\s/.test(proxyImage)) return { mode: "process" }; | |
| 84 | return { mode: "job", image, claim, nodeSelector, tolerations, ...(proxyImage === "" ? {} : { proxyImage }) }; | |
| 78 | 85 | } |
| 79 | 86 | |
| 80 | 87 | /** |
src/checks/service.ts +9 −2
| @@ -76,7 +76,7 @@ import { | ||
| 76 | 76 | import { summariseCheckFailure } from "./summary.ts"; |
| 77 | 77 | import type { Result } from "../kernel/result.ts"; |
| 78 | 78 | import { placementFromEnv, type Placement } from "./placement.ts"; |
| 79 | import { JOB_VANISHED, runJobStep } from "./job_step.ts"; | |
| 79 | import { forgeOrigins, JOB_VANISHED, runJobStep } from "./job_step.ts"; | |
| 80 | 80 | import type { JobOptions } from "../cluster/jobs.ts"; |
| 81 | 81 | import type { CheckDetail } from "../core/runs.ts"; |
| 82 | 82 | |
| @@ -723,9 +723,10 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle { | ||
| 723 | 723 | } else { |
| 724 | 724 | // The cluster holds a Job, but not as a cell does: the egress a |
| 725 | 725 | // check declared is not enforced here, and the run says so. |
| 726 | const held = job?.proxyImage !== undefined; | |
| 726 | 727 | if (x.runId !== undefined) |
| 727 | 728 | noteRunProgress(app.db, x.runId, { |
| 728 | sandbox: { enforced: false, note: "egress not enforced on a cluster job" }, | |
| 729 | sandbox: { enforced: held, note: held ? "" : "egress not enforced on a cluster job" }, | |
| 729 | 730 | }); |
| 730 | 731 | write("placement: job"); |
| 731 | 732 | } |
| @@ -782,6 +783,12 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle { | ||
| 782 | 783 | onNode: (node) => { |
| 783 | 784 | if (x.runId !== undefined) noteRunProgress(app.db, x.runId, { node }); |
| 784 | 785 | }, |
| 786 | egress: { | |
| 787 | hosts: [...STEP_HOSTS, ...manifest.egress], | |
| 788 | origins: forgeOrigins(options.forgeUrl), | |
| 789 | mode: egressSetting(app.db), | |
| 790 | }, | |
| 791 | onReached: (host, port) => noteReached(app.config.dataDir, repo.id, host, port), | |
| 785 | 792 | ...(options.job === undefined ? {} : { options: options.job }), |
| 786 | 793 | }); |
| 787 | 794 | } else { |
src/cluster/jobs.ts +137 −7
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | * injectable. Plain data in (a `JobSpec`), plain data out (a `JobResult`). |
| 7 | 7 | */ |
| 8 | 8 | import { readFileSync } from "node:fs"; |
| 9 | import { reachedFromLog } from "../apps/egress_proxy.ts"; | |
| 9 | 10 | |
| 10 | 11 | const SA_DIR = "/var/run/secrets/kubernetes.io/serviceaccount"; |
| 11 | 12 | const NAME = /^[a-z0-9]([-a-z0-9]{0,51}[a-z0-9])?$/; |
| @@ -32,8 +33,25 @@ export type JobSpec = { | ||
| 32 | 33 | limits?: { memoryMiB: number; cpus: number; diskMiB: number }; |
| 33 | 34 | /** Labels on the pod, for a NetworkPolicy to select it by. */ |
| 34 | 35 | labels?: Record<string, string>; |
| 36 | /** | |
| 37 | * Hold the Job to these hosts: a pod of its own runs the forge's egress | |
| 38 | * proxy (`apps/egress_proxy.ts`), the Job is pointed at it, and a | |
| 39 | * NetworkPolicy lets the Job's pod reach nothing else. | |
| 40 | */ | |
| 41 | proxy?: { | |
| 42 | /** An image holding the forge's `src/`, run from its working directory. */ | |
| 43 | image: string; | |
| 44 | hosts: string[]; | |
| 45 | /** `host:port` always reachable: the forge. */ | |
| 46 | origins: string[]; | |
| 47 | mode: "enforce" | "report"; | |
| 48 | /** Labels on the proxy's pod, for a NetworkPolicy to select it by. */ | |
| 49 | labels: Record<string, string>; | |
| 50 | }; | |
| 35 | 51 | }; |
| 36 | 52 | |
| 53 | export const PROXY_PORT = 3128; | |
| 54 | ||
| 37 | 55 | export type JobResult = { |
| 38 | 56 | /** The container's exit code; null when it never ran to the end. */ |
| 39 | 57 | exitCode: number | null; |
| @@ -41,6 +59,8 @@ export type JobResult = { | ||
| 41 | 59 | timedOut: boolean; |
| 42 | 60 | /** The node the Job's pod ran on; absent when it never reached one. */ |
| 43 | 61 | node?: string; |
| 62 | /** Undeclared hosts the proxy let through while egress is only reported. */ | |
| 63 | reached?: { host: string; port: number }[]; | |
| 44 | 64 | }; |
| 45 | 65 | |
| 46 | 66 | /** The Job, or the pod that carried it, is gone: evicted, deleted, its node lost. */ |
| @@ -77,12 +97,13 @@ export function serviceAccount(dir = SA_DIR, env: Record<string, string | undefi | ||
| 77 | 97 | } |
| 78 | 98 | |
| 79 | 99 | /** The Job manifest for a spec, or the reason it is refused. */ |
| 80 | export function manifest(spec: JobSpec): object { | |
| 100 | export function manifest(spec: JobSpec, proxyIp?: string): object { | |
| 81 | 101 | if (!NAME.test(spec.name ?? "")) throw new Error("job name must be a DNS label of at most 53 characters"); |
| 82 | 102 | if (typeof spec.image !== "string" || !spec.image || /\s/.test(spec.image)) throw new Error("image is required"); |
| 83 | 103 | if (!Array.isArray(spec.command) || !spec.command.length || spec.command.some((c) => typeof c !== "string")) |
| 84 | 104 | throw new Error("command must be a non-empty list of strings"); |
| 85 | const env = Object.entries(spec.env ?? {}).map(([name, value]) => { | |
| 105 | const via = proxyIp === undefined ? {} : proxyEnv(proxyIp); | |
| 106 | const env = Object.entries({ ...spec.env, ...via }).map(([name, value]) => { | |
| 86 | 107 | if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || typeof value !== "string") throw new Error(`bad env ${name}`); |
| 87 | 108 | return { name, value }; |
| 88 | 109 | }); |
| @@ -149,17 +170,75 @@ export function manifest(spec: JobSpec): object { | ||
| 149 | 170 | }; |
| 150 | 171 | } |
| 151 | 172 | |
| 173 | /** What points a client at the proxy; nothing is exempt from it. */ | |
| 174 | function proxyEnv(ip: string): Record<string, string> { | |
| 175 | if (!/^[0-9a-fA-F:.]+$/.test(ip)) throw new Error("bad proxy address"); | |
| 176 | const url = `http://${ip.includes(":") ? `[${ip}]` : ip}:${PROXY_PORT}`; | |
| 177 | return { HTTP_PROXY: url, HTTPS_PROXY: url, http_proxy: url, https_proxy: url, NO_PROXY: "", no_proxy: "" }; | |
| 178 | } | |
| 179 | ||
| 180 | /** The proxy's own pod: the forge's image, the declared hosts, no credential. */ | |
| 181 | export function proxyManifest(spec: JobSpec): object { | |
| 182 | const p = spec.proxy; | |
| 183 | if (!p) throw new Error("no proxy"); | |
| 184 | if (typeof p.image !== "string" || !p.image || /\s/.test(p.image)) throw new Error("proxy image is required"); | |
| 185 | const name = `${spec.name}-egress`; | |
| 186 | if (!NAME.test(name.slice(0, 63))) throw new Error("bad proxy name"); | |
| 187 | const labels: Record<string, string> = {}; | |
| 188 | for (const [k, v] of Object.entries(p.labels)) { | |
| 189 | if (!/^[A-Za-z0-9][-A-Za-z0-9_.\/]{0,62}$/.test(k) || !/^[A-Za-z0-9]?[-A-Za-z0-9_.]{0,62}$/.test(v)) throw new Error(`bad label ${k}`); | |
| 190 | labels[k] = v; | |
| 191 | } | |
| 192 | return { | |
| 193 | apiVersion: "v1", | |
| 194 | kind: "Pod", | |
| 195 | metadata: { name, labels: { ...labels, "job-name-egress": spec.name } }, | |
| 196 | spec: { | |
| 197 | restartPolicy: "Never", | |
| 198 | automountServiceAccountToken: false, | |
| 199 | securityContext: { runAsNonRoot: true }, | |
| 200 | nodeSelector: spec.nodeSelector ?? {}, | |
| 201 | tolerations: spec.tolerations ?? [], | |
| 202 | activeDeadlineSeconds: 7200, | |
| 203 | containers: [ | |
| 204 | { | |
| 205 | name: "egress", | |
| 206 | image: p.image, | |
| 207 | command: ["bun", "src/apps/egress_proxy.ts"], | |
| 208 | env: [ | |
| 209 | { name: "FORGE_EGRESS_HOSTS", value: JSON.stringify(p.hosts) }, | |
| 210 | { name: "FORGE_EGRESS_ORIGINS", value: JSON.stringify(p.origins) }, | |
| 211 | { name: "FORGE_EGRESS_MODE", value: p.mode }, | |
| 212 | { name: "FORGE_EGRESS_PORT", value: String(PROXY_PORT) }, | |
| 213 | ], | |
| 214 | ports: [{ containerPort: PROXY_PORT }], | |
| 215 | readinessProbe: { tcpSocket: { port: PROXY_PORT }, periodSeconds: 1 }, | |
| 216 | securityContext: { allowPrivilegeEscalation: false, capabilities: { drop: ["ALL"] } }, | |
| 217 | resources: { limits: { memory: "128Mi", cpu: "0.5" } }, | |
| 218 | }, | |
| 219 | ], | |
| 220 | }, | |
| 221 | }; | |
| 222 | } | |
| 223 | ||
| 152 | 224 | /** The few fields of the kube API's answers this module reads. */ |
| 153 | 225 | type Job = { status?: { succeeded?: number; failed?: number } }; |
| 154 | 226 | type Pod = { |
| 155 | 227 | metadata?: { name?: string }; |
| 156 | 228 | spec?: { nodeName?: string }; |
| 157 | status?: { reason?: string; containerStatuses?: { state?: { terminated?: { exitCode?: number } } }[] }; | |
| 229 | status?: { | |
| 230 | podIP?: string; | |
| 231 | phase?: string; | |
| 232 | reason?: string; | |
| 233 | conditions?: { type?: string; status?: string }[]; | |
| 234 | containerStatuses?: { state?: { terminated?: { exitCode?: number } } }[]; | |
| 235 | }; | |
| 158 | 236 | }; |
| 159 | 237 | type PodList = { items?: Pod[] }; |
| 160 | 238 | |
| 161 | 239 | export async function runJob(spec: JobSpec, opts: JobOptions = {}): Promise<JobResult> { |
| 162 | const body = JSON.stringify(manifest(spec)); | |
| 240 | manifest(spec); // refuse a bad spec before anything is made | |
| 241 | if (spec.proxy) proxyManifest(spec); | |
| 163 | 242 | const cred = opts.credentials ?? serviceAccount(); |
| 164 | 243 | const doFetch = opts.fetch ?? ((u, i) => fetch(u, i as RequestInit)); |
| 165 | 244 | const now = opts.now ?? Date.now; |
| @@ -188,8 +267,40 @@ export async function runJob(spec: JobSpec, opts: JobOptions = {}): Promise<JobR | ||
| 188 | 267 | }; |
| 189 | 268 | |
| 190 | 269 | const jobPath = `/apis/batch/v1/namespaces/${ns}/jobs/${name}`; |
| 270 | const proxyName = encodeURIComponent(`${spec.name}-egress`); | |
| 271 | const proxyPath = `/api/v1/namespaces/${ns}/pods/${proxyName}`; | |
| 191 | 272 | let created = false; |
| 273 | let proxyMade = false; | |
| 274 | const deadline = now() + timeoutMs; | |
| 192 | 275 | try { |
| 276 | let proxyIp: string | undefined; | |
| 277 | if (spec.proxy) { | |
| 278 | // The proxy comes up first; the Job is only made once it answers, and | |
| 279 | // is told its address, so there is no moment it runs unheld. | |
| 280 | let madeProxy: Response; | |
| 281 | try { | |
| 282 | madeProxy = await call("POST", `/api/v1/namespaces/${ns}/pods`, JSON.stringify(proxyManifest(spec))); | |
| 283 | } catch (e) { | |
| 284 | proxyMade = true; | |
| 285 | throw e; | |
| 286 | } | |
| 287 | if (!madeProxy.ok) { | |
| 288 | proxyMade = madeProxy.status >= 500; | |
| 289 | throw new Error(`kube POST ${madeProxy.status}`); | |
| 290 | } | |
| 291 | proxyMade = true; | |
| 292 | while (proxyIp === undefined) { | |
| 293 | if (opts.signal?.aborted) throw new Error("job cancelled"); | |
| 294 | const pod = await json<Pod>("GET", proxyPath); | |
| 295 | const ready = pod.status?.conditions?.some((c) => c.type === "Ready" && c.status === "True"); | |
| 296 | if (ready && pod.status?.podIP) proxyIp = pod.status.podIP; | |
| 297 | else if (pod.status?.phase === "Failed" || pod.status?.phase === "Succeeded") | |
| 298 | throw new Error("egress proxy stopped"); | |
| 299 | else if (now() >= deadline) throw new Error("egress proxy did not come up"); | |
| 300 | else await sleep(pollMs); | |
| 301 | } | |
| 302 | } | |
| 303 | const body = JSON.stringify(manifest(spec, proxyIp)); | |
| 193 | 304 | // Only a Job this call made is this call's to delete: a 4xx (409 |
| 194 | 305 | // AlreadyExists above all) means the API made nothing; anything else |
| 195 | 306 | // (a 5xx, a dropped connection) may have, so it is deleted. |
| @@ -206,7 +317,6 @@ export async function runJob(spec: JobSpec, opts: JobOptions = {}): Promise<JobR | ||
| 206 | 317 | } |
| 207 | 318 | created = true; |
| 208 | 319 | |
| 209 | const deadline = now() + timeoutMs; | |
| 210 | 320 | let done: "succeeded" | "failed" | null = null; |
| 211 | 321 | while (!done) { |
| 212 | 322 | if (opts.signal?.aborted) throw new Error("job cancelled"); |
| @@ -218,7 +328,7 @@ export async function runJob(spec: JobSpec, opts: JobOptions = {}): Promise<JobR | ||
| 218 | 328 | else if ((job.status?.failed ?? 0) > 0) done = "failed"; |
| 219 | 329 | else if (now() >= deadline) { |
| 220 | 330 | const pod = await findPod().catch(() => undefined); |
| 221 | return { exitCode: null, lines: await logLines(pod?.metadata?.name), timedOut: true, ...nodeOf(pod) }; | |
| 331 | return { exitCode: null, lines: await logLines(pod?.metadata?.name), timedOut: true, ...nodeOf(pod), ...(await reachedOf()) }; | |
| 222 | 332 | } |
| 223 | 333 | else await sleep(pollMs); |
| 224 | 334 | } |
| @@ -229,8 +339,15 @@ export async function runJob(spec: JobSpec, opts: JobOptions = {}): Promise<JobR | ||
| 229 | 339 | throw new JobVanished(pod ? "the job's pod was evicted" : "the job's pod is gone"); |
| 230 | 340 | const code: unknown = pod?.status?.containerStatuses?.[0]?.state?.terminated?.exitCode; |
| 231 | 341 | const exitCode = typeof code === "number" ? code : done === "succeeded" ? 0 : null; |
| 232 | return { exitCode, lines: await logLines(pod?.metadata?.name), timedOut: false, ...nodeOf(pod) }; | |
| 342 | return { exitCode, lines: await logLines(pod?.metadata?.name), timedOut: false, ...nodeOf(pod), ...(await reachedOf()) }; | |
| 233 | 343 | } finally { |
| 344 | if (proxyMade) { | |
| 345 | try { | |
| 346 | await call("DELETE", `${proxyPath}?gracePeriodSeconds=0`); | |
| 347 | } catch { | |
| 348 | // activeDeadlineSeconds reaps a proxy that could not be deleted | |
| 349 | } | |
| 350 | } | |
| 234 | 351 | if (created) { |
| 235 | 352 | try { |
| 236 | 353 | await call("DELETE", `${jobPath}?propagationPolicy=Background`); |
| @@ -240,6 +357,19 @@ export async function runJob(spec: JobSpec, opts: JobOptions = {}): Promise<JobR | ||
| 240 | 357 | } |
| 241 | 358 | } |
| 242 | 359 | |
| 360 | /** What the proxy let through undeclared, read from its log while it is still there. */ | |
| 361 | async function reachedOf(): Promise<{ reached?: { host: string; port: number }[] }> { | |
| 362 | if (spec.proxy?.mode !== "report" || !proxyMade) return {}; | |
| 363 | try { | |
| 364 | const res = await call("GET", `${proxyPath}/log?limitBytes=${max}`); | |
| 365 | if (!res.ok || !res.body) return {}; | |
| 366 | const found = reachedFromLog((await readCapped(res.body, max)).split("\n")); | |
| 367 | return found.length > 0 ? { reached: found } : {}; | |
| 368 | } catch { | |
| 369 | return {}; | |
| 370 | } | |
| 371 | } | |
| 372 | ||
| 243 | 373 | async function findPod(): Promise<Pod | undefined> { |
| 244 | 374 | const list = await json<PodList>("GET", `/api/v1/namespaces/${ns}/pods?labelSelector=${encodeURIComponent(`job-name=${spec.name}`)}`); |
| 245 | 375 | return list.items?.[0]; |
test/job-egress.test.ts added +135
| @@ -0,0 +1,135 @@ | ||
| 1 | /** | |
| 2 | * A Job held to its declared egress (#1428): a proxy pod comes up first, the | |
| 3 | * Job is made only after, pointed at it; the proxy refuses what was not | |
| 4 | * declared; what was reported comes back from its log. | |
| 5 | */ | |
| 6 | import { describe, expect, test } from "bun:test"; | |
| 7 | import { forgeOrigins } from "../src/checks/job_step.ts"; | |
| 8 | import { placementFromEnv } from "../src/checks/placement.ts"; | |
| 9 | import { PROXY_PORT, runJob, type JobSpec } from "../src/cluster/jobs.ts"; | |
| 10 | import { startEgress } from "../src/apps/egress.ts"; | |
| 11 | import { policyFromEnv, reachedFromLog } from "../src/apps/egress_proxy.ts"; | |
| 12 | ||
| 13 | const spec = (mode: "enforce" | "report"): JobSpec => ({ | |
| 14 | name: "check-r1", | |
| 15 | image: "oven/bun:1", | |
| 16 | command: ["/bin/sh", "-c", "true"], | |
| 17 | labels: { "forge-check": "true" }, | |
| 18 | proxy: { | |
| 19 | image: "forge:1", | |
| 20 | hosts: ["registry.npmjs.org"], | |
| 21 | origins: ["forge.test:443"], | |
| 22 | mode, | |
| 23 | labels: { "forge-check-egress": "true" }, | |
| 24 | }, | |
| 25 | }); | |
| 26 | ||
| 27 | function cluster(proxyLog = "") { | |
| 28 | const calls: { method: string; path: string; body?: any }[] = []; | |
| 29 | const fetch = async (url: string, init: RequestInit) => { | |
| 30 | const path = new URL(url).pathname; | |
| 31 | calls.push({ method: String(init.method), path, ...(typeof init.body === "string" ? { body: JSON.parse(init.body) } : {}) }); | |
| 32 | if (init.method === "POST" || init.method === "DELETE") return Response.json({}); | |
| 33 | if (path === "/api/v1/namespaces/forge/pods/check-r1-egress") | |
| 34 | return Response.json({ status: { phase: "Running", podIP: "10.1.2.3", conditions: [{ type: "Ready", status: "True" }] } }); | |
| 35 | if (path === "/api/v1/namespaces/forge/pods/check-r1-egress/log") return new Response(proxyLog); | |
| 36 | if (path.endsWith("/log")) return new Response("ok\n"); | |
| 37 | if (path.endsWith("/pods")) | |
| 38 | return Response.json({ items: [{ metadata: { name: "p1" }, status: { containerStatuses: [{ state: { terminated: { exitCode: 0 } } }] } }] }); | |
| 39 | return Response.json({ status: { succeeded: 1 } }); | |
| 40 | }; | |
| 41 | return { calls, opts: { fetch: fetch as never, credentials: { server: "https://k", token: "t", namespace: "forge" }, pollMs: 1 } }; | |
| 42 | } | |
| 43 | ||
| 44 | describe("a Job with a proxy", () => { | |
| 45 | test("the proxy pod is made first, the Job is pointed at it, both are deleted", async () => { | |
| 46 | const { calls, opts } = cluster(); | |
| 47 | const result = await runJob(spec("enforce"), opts); | |
| 48 | expect(result.exitCode).toBe(0); | |
| 49 | const posts = calls.filter((c) => c.method === "POST"); | |
| 50 | expect(posts.map((c) => c.body.kind)).toEqual(["Pod", "Job"]); | |
| 51 | const proxy = posts[0]!.body; | |
| 52 | expect(proxy.metadata.labels["forge-check-egress"]).toBe("true"); | |
| 53 | expect(proxy.spec.automountServiceAccountToken).toBe(false); | |
| 54 | const env = Object.fromEntries(proxy.spec.containers[0].env.map((e: any) => [e.name, e.value])); | |
| 55 | expect(JSON.parse(env.FORGE_EGRESS_HOSTS)).toEqual(["registry.npmjs.org"]); | |
| 56 | expect(env.FORGE_EGRESS_MODE).toBe("enforce"); | |
| 57 | const jobEnv = Object.fromEntries(posts[1]!.body.spec.template.spec.containers[0].env.map((e: any) => [e.name, e.value])); | |
| 58 | expect(jobEnv.HTTPS_PROXY).toBe(`http://10.1.2.3:${PROXY_PORT}`); | |
| 59 | expect(jobEnv.http_proxy).toBe(`http://10.1.2.3:${PROXY_PORT}`); | |
| 60 | expect(posts[1]!.body.spec.template.metadata.labels["forge-check"]).toBe("true"); | |
| 61 | const deletes = calls.filter((c) => c.method === "DELETE").map((c) => c.path); | |
| 62 | expect(deletes).toContain("/api/v1/namespaces/forge/pods/check-r1-egress"); | |
| 63 | expect(deletes.some((p) => p.endsWith("/jobs/check-r1"))).toBe(true); | |
| 64 | }); | |
| 65 | ||
| 66 | test("a proxy that never comes up fails the run and leaves nothing behind", async () => { | |
| 67 | const { calls, opts } = cluster(); | |
| 68 | const stuck = async (url: string, init: RequestInit) => | |
| 69 | new URL(url).pathname.endsWith("-egress") && init.method === "GET" | |
| 70 | ? Response.json({ status: { phase: "Pending" } }) | |
| 71 | : (opts.fetch as (u: string, i: RequestInit) => Promise<Response>)(url, init); | |
| 72 | let t = 0; | |
| 73 | await expect(runJob(spec("enforce"), { ...opts, fetch: stuck as never, timeoutMs: 5, now: () => (t += 3) })).rejects.toThrow( | |
| 74 | "did not come up", | |
| 75 | ); | |
| 76 | expect(calls.some((c) => c.body?.kind === "Job")).toBe(false); | |
| 77 | expect(calls.some((c) => c.method === "DELETE" && c.path.endsWith("-egress"))).toBe(true); | |
| 78 | }); | |
| 79 | ||
| 80 | test("reported hosts come back from the proxy's log, and only in report mode", async () => { | |
| 81 | const log = 'egress proxy on :3128\nforge-reached {"host":"evil.test","port":443}\nforge-reached nonsense\n'; | |
| 82 | const reported = await runJob(spec("report"), cluster(log).opts); | |
| 83 | expect(reported.reached).toEqual([{ host: "evil.test", port: 443 }]); | |
| 84 | const enforced = await runJob(spec("enforce"), cluster(log).opts); | |
| 85 | expect(enforced.reached).toBeUndefined(); | |
| 86 | }); | |
| 87 | ||
| 88 | test("a spec without a proxy makes no pod", async () => { | |
| 89 | const { calls, opts } = cluster(); | |
| 90 | const plain = spec("enforce"); | |
| 91 | delete plain.proxy; | |
| 92 | await runJob(plain, opts); | |
| 93 | expect(calls.filter((c) => c.method === "POST").map((c) => c.body.kind)).toEqual(["Job"]); | |
| 94 | }); | |
| 95 | }); | |
| 96 | ||
| 97 | describe("the proxy's configuration", () => { | |
| 98 | test("is validated at the boundary", () => { | |
| 99 | expect(policyFromEnv({ FORGE_EGRESS_HOSTS: "nope" })).toContain("FORGE_EGRESS_HOSTS"); | |
| 100 | expect(policyFromEnv({ FORGE_EGRESS_HOSTS: '["a b"]' })).toContain("FORGE_EGRESS_HOSTS"); | |
| 101 | expect(policyFromEnv({ FORGE_EGRESS_HOSTS: "[]", FORGE_EGRESS_ORIGINS: '["forge"]' })).toContain("bad origin"); | |
| 102 | const p = policyFromEnv({ FORGE_EGRESS_HOSTS: '["x.test"]', FORGE_EGRESS_ORIGINS: '["forge.test:443"]' }); | |
| 103 | expect(p).toMatchObject({ hosts: ["x.test"], origins: [{ host: "forge.test", port: 443 }], report: undefined }); | |
| 104 | expect(reachedFromLog(['forge-reached {"host":"h","port":"x"}', "other"])).toEqual([]); | |
| 105 | }); | |
| 106 | ||
| 107 | test("the forge's origin is host:port; a bad URL is none", () => { | |
| 108 | expect(forgeOrigins("https://forge.test")).toEqual(["forge.test:443"]); | |
| 109 | expect(forgeOrigins("http://[::1]:8080")).toEqual(["::1:8080"]); | |
| 110 | expect(forgeOrigins("nope")).toEqual([]); | |
| 111 | }); | |
| 112 | ||
| 113 | test("a proxy image is optional and must not hold whitespace", () => { | |
| 114 | const env = { FORGE_CHECKS_PLACEMENT: "job", FORGE_CHECKS_IMAGE: "i", FORGE_CHECKS_CLAIM: "c" }; | |
| 115 | expect(placementFromEnv({ ...env, FORGE_CHECKS_PROXY_IMAGE: "forge:1" })).toMatchObject({ mode: "job", proxyImage: "forge:1" }); | |
| 116 | expect(placementFromEnv(env)).not.toHaveProperty("proxyImage"); | |
| 117 | expect(placementFromEnv({ ...env, FORGE_CHECKS_PROXY_IMAGE: "a b" })).toEqual({ mode: "process" }); | |
| 118 | }); | |
| 119 | }); | |
| 120 | ||
| 121 | describe("the proxy on a TCP port", () => { | |
| 122 | test("refuses an undeclared host with a 403 that names it", async () => { | |
| 123 | const probe = Bun.listen({ hostname: "127.0.0.1", port: 0, socket: { data() {} } }); | |
| 124 | const port = probe.port; | |
| 125 | probe.stop(true); | |
| 126 | const proxy = startEgress({ tcp: port }, { hosts: ["declared.test"], origins: [] }); | |
| 127 | try { | |
| 128 | const res = await fetch("http://undeclared.test/", { proxy: `http://127.0.0.1:${port}` }); | |
| 129 | expect(res.status).toBe(403); | |
| 130 | expect(await res.text()).toContain("undeclared.test:80"); | |
| 131 | } finally { | |
| 132 | proxy.close(); | |
| 133 | } | |
| 134 | }); | |
| 135 | }); |
new above
offline