held-back.test.ts
This file
Path
apps/sandbox/test/held-back.test.ts
690 lines · 20.0 KiB · TypeScript
Last changed by
Merge observability into mainoscabrielbefore adoption1985111
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1–36why, one step back1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { CheckAt } from "@repo/checks/check-runner";4import type { CheckRun, HeldBackPart } from "@repo/checks/check-runner";5import { CheckExit, CheckWire } from "@repo/checks/check-runner/wire";6import { phasePlan } from "@repo/checks/phases";7import type { HeldBackJob } from "@repo/project/visibility-port";8import { Command, Hostname } from "@repo/protocol/domain/common";9import { RunBlock } from "@repo/protocol/domain/run";10import {11 AreaName,12 CommitSha,13 LaneName,14 ProjectName,15 RepoName,16 RepoPath,17 SuiteRoot,18} from "@repo/protocol/ids";19import { VerifierBlocked } from "@repo/protocol/refusal";20import {21 Duration,22 Effect,23 Exit,24 Fiber,25 FileSystem,26 Latch,27 Layer,28 Match,29 Option,30 Redacted,31 Schema,32} from "effect";33import { TestClock } from "effect/testing";34import { expectTypeOf } from "vitest";3536import { Box, BoxFailed } from "../src/box.ts";Merge observability into mainoscabrielbefore adoption1985111
line 37why, one step back37import { checkJob } from "../src/checker.ts";Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 38–61why, one step back38import { REGISTRIES } from "../src/checker/network.ts";39import { check, REPO, roomFor } from "../src/checker/run.ts";40import { answerJob } from "../src/job.ts";41import { exited, fakeChecker } from "./fake-box.ts";42import type { Call, FakeOptions } from "./fake-box.ts";43import { LocalBox } from "./local-box.ts";4445const SETUP = "bun install --frozen-lockfile --ignore-scripts";4647const UNIT = "bun test --path-ignore-patterns='test/asks/**'";4849const run = RunBlock.make({50 checks: { [LaneName.make("unit")]: Command.make(UNIT) },51 setup: Command.make(SETUP),52 setupEgress: [Hostname.make("npm.pkg.github.com")],53 test: Command.make("bun test {path}"),54});5556const suite = SuiteRoot.make(`sha256:${"5e".repeat(32)}`);5758const exportArea = AreaName.make("export");5960const parser = AreaName.make("parser");61Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
line 62why, one step back62/** Each file carries a canary, so a leak is searchable. */Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 63–124why, one step back63const SEALED = [64 {65 area: exportArea,66 path: "checks/held-back/export/round-trip.test.ts",67 test: "formats 2026-W53 back to itself",68 },69 {70 area: exportArea,71 path: "checks/held-back/export/iso-weeks.test.ts",72 test: "keeps the ISO year at a year's edge",73 },74 {75 area: parser,76 path: "checks/held-back/parser/week-54.test.ts",77 test: "rejects week 54",78 },79].map(({ area, path, test }) => ({80 area,81 command: `bun test ${path}`,82 path,83 test,84 text: `// canary 7c1e2a90-sealed\ntest(${JSON.stringify(test)}, () => {});\n`,85}));8687const weekFile = SEALED.at(-1);8889const PARSER_STDOUT = `(fail) parser > ${weekFile?.test}\n`;9091const PARSER_STDERR =92 "AssertionError: expected Week(54) to be undefined at week-54.test.ts:3\n";9394const heldBack: HeldBackPart = {95 areas: [exportArea, parser],96 at: CommitSha.make("b".repeat(40)),97 files: SEALED.map(({ area, path, text }) => ({98 area,99 content: new TextEncoder().encode(text),100 path: RepoPath.make(path),101 })),102 runs: SEALED.map(({ area, command, path }) => ({103 area,104 command,105 path: RepoPath.make(path),106 })),107 suite,108};109110const wireFor = (111 sealed: Option.Option<HeldBackPart> = Option.some(heldBack)112): CheckWire => ({113 clone: {114 token: Redacted.make("art_v1_read-only"),115 url: "https://0123abcd.artifacts.cloudflare.net/git/public/datekit.git",116 },117 job: {118 at: CheckAt.cases.Commit.make({ commit: CommitSha.make("a".repeat(40)) }),119 ...Option.match(sealed, {120 onNone: () => ({}),121 onSome: (part) => ({ heldBack: part }),122 }),123 lanes: [{ command: UNIT, lane: LaneName.make("unit") }],124 placeholders: [],Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 125why, one step back125 project: ProjectName.make("oscabriel/datekit"),Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 126–672why, one step back126 proxies: [],127 repo: RepoName.make("datekit"),128 run,129 },130});131132const parserFails = (options: FakeOptions = {}) =>133 fakeChecker({134 commands: new Map([135 [136 weekFile?.command ?? "",137 exited(1, { stderr: PARSER_STDERR, stdout: PARSER_STDOUT }),138 ],139 ]),140 ...options,141 });142143const sealedCommands: ReadonlySet<string> = new Set(144 SEALED.map(({ command }) => command)145);146147const writesSealed = (call: Call) =>148 call.kind === "writeFile" ||149 (call.kind === "exec" && call.argv.some((arg) => arg.startsWith(`${REPO}/`)));150151const shellOf = (call: Call) =>152 call.kind === "exec" && call.argv[0] === "sh" && call.argv[1] === "-c"153 ? Option.fromUndefinedOr(call.argv[2])154 : Option.none();155156const phaseOf = Match.type<Call>().pipe(157 Match.discriminatorsExhaustive("kind")({158 allow: ({ hosts }): readonly string[] =>159 hosts.length === 0 ? ["egressOff"] : ["setup"],160 destroy: () => ["destroy"],161 exec: (call) => {162 if (call.argv[0] === "git") {163 return ["clone"];164 }165166 if (writesSealed(call)) {167 return ["writeHeldBack"];168 }169170 return Option.match(shellOf(call), {171 onNone: () => ["?"],172 onSome: (command) => {173 if (command === SETUP) {174 return ["setup"];175 }176177 return sealedCommands.has(command) ? ["runHeldBack"] : ["run"];178 },179 });180 },181 // The env gateway's routes open as egress goes off.182 intercept: () => ["egressOff"],183 log: () => [],184 report: () => ["report"],185 restore: () => ["setup"],186 route: () => ["clone"],187 save: () => ["snapshot"],188 writeFile: () => ["writeHeldBack"],189 })190);191192const phasesOf = (calls: readonly Call[]) =>193 calls194 .flatMap(phaseOf)195 .filter((phase, at, all) => at === 0 || all[at - 1] !== phase);196197const SECRETS = [198 ...SEALED.flatMap(({ path, test, text }) => [199 path,200 path.split("/").at(-1) ?? path,201 test,202 text,203 ]),204 "canary 7c1e2a90",205 PARSER_STDOUT.trim(),206 PARSER_STDERR.trim(),207 "Week(54)",208];209210const leakedIn = (text: string) =>211 SECRETS.filter((secret) => text.includes(secret));212213const leftBy = (calls: readonly Call[]) =>214 JSON.stringify(215 calls.filter((call) => call.kind === "report" || call.kind === "log")216 );217218const sealedJob = Effect.gen(function* () {219 const fake = parserFails();220221 const outcome = yield* Effect.exit(222 check(wireFor()).pipe(Effect.provide(fake.layer))223 );224225 return { calls: fake.calls, outcome };226});227228/** What a public lane prints when it finds the sealed files too (`bun test` with no path). */229const printedBeside = exited(1, {230 stdout: `(fail) export > ${SEALED[0]?.test}\nAssertionError: expected 53 to be 52\n`,231});232233const LINT_COUNT = "oxlint --format json";234235const printing = () =>236 fakeChecker({237 commands: new Map([238 [UNIT, printedBeside],239 [LINT_COUNT, printedBeside],240 ]),241 });242243const withCountLane = (sealed: Option.Option<HeldBackPart>): CheckWire => {244 const base = wireFor(sealed);245246 return {247 ...base,248 job: {249 ...base.job,250 lanes: [251 ...base.job.lanes,252 {253 command: LINT_COUNT,254 lane: LaneName.make("lint-count"),255 output: "stdout",256 },257 ],258 },259 };260};261262const serialized = (outcome: Exit.Exit<CheckRun, VerifierBlocked>) =>263 Schema.encodeEffect(CheckExit)(outcome).pipe(264 Effect.map((encoded) => JSON.stringify(encoded))265 );266267describe("the Checker's held-back phase", () => {268 it.effect(269 "writes the sealed files only after the snapshot and with egress off, runs the public lanes, then each sealed check, and destroys the container, in the plan's order",270 () =>271 Effect.gen(function* () {272 const { calls, outcome } = yield* sealedJob;273274 expect(Exit.isSuccess(outcome)).toBeTruthy();275 expect(phasesOf(calls)).toStrictEqual([276 "clone",277 "setup",278 "snapshot",279 "egressOff",280 "writeHeldBack",281 "run",282 "runHeldBack",283 "report",284 "destroy",285 ]);286287 expect(288 phasesOf(calls)289 .slice(1, -1)290 .filter((phase) => phase !== "runHeldBack")291 ).toStrictEqual(292 phasePlan({293 heldBack: Option.some({ areas: heldBack.areas }),294 lanes: [{ command: UNIT, lane: LaneName.make("unit") }],295 lockfileHash: "any",296 placeholders: [],297 run,298 }).map(299 ({ _tag }) => `${_tag.charAt(0).toLowerCase()}${_tag.slice(1)}`300 )301 );302303 expect(304 calls.find(305 (call) =>306 call.kind === "exec" && Option.contains(shellOf(call), SETUP)307 )308 ).toMatchObject({ network: [...REGISTRIES, "npm.pkg.github.com"] });309 expect(calls.at(-1)).toStrictEqual({ kind: "destroy" });310 })311 );312313 it.effect(314 "writes each sealed file's bytes at its path in the checked tree, and takes or restores no snapshot after the first",315 () =>316 Effect.gen(function* () {317 const { calls } = yield* sealedJob;318 const firstWrite = calls.findIndex((call) => call.kind === "writeFile");319320 expect(321 calls.flatMap((call) =>322 call.kind === "writeFile"323 ? [{ path: call.path, text: call.text }]324 : []325 )326 ).toStrictEqual(327 SEALED.map(({ path, text }) => ({ path: `${REPO}/${path}`, text }))328 );329 expect(firstWrite).toBeGreaterThan(-1);330 expect(331 calls332 .slice(firstWrite)333 .filter((call) => call.kind === "save" || call.kind === "restore")334 ).toStrictEqual([]);335 })336 );337338 it.effect(339 "runs each sealed check once, in the job's order, with the network off",340 () =>341 Effect.gen(function* () {342 const { calls } = yield* sealedJob;343344 expect(345 calls.flatMap((call) =>346 Option.match(shellOf(call), {347 onNone: () => [],348 onSome: (command) =>349 sealedCommands.has(command) && call.kind === "exec"350 ? [{ command, network: call.network }]351 : [],352 })353 )354 ).toStrictEqual(355 SEALED.map(({ command }) => ({ command, network: [] }))356 );357 })358 );359360 it.effect(361 "reports one result per area, passed of total under the suite root, with the parser's check failing",362 () =>363 Effect.gen(function* () {364 const fake = parserFails();365366 const ran = yield* check(wireFor()).pipe(Effect.provide(fake.layer));367368 expect(ran.heldBack).toStrictEqual([369 { area: "export", passed: 2, suite, total: 2 },370 { area: "parser", passed: 0, suite, total: 1 },371 ]);372 expect(373 ran.lanes.map(({ lane, result }) => ({ lane, result }))374 ).toStrictEqual([{ lane: "unit", result: "passed" }]);375 })376 );377378 it.effect(379 "lets no sealed path, file content, test name or sealed check's output into the result, the logs it hands over or its log lines",380 () =>381 Effect.gen(function* () {382 const fake = parserFails();383384 const outcome = yield* Effect.exit(385 check(wireFor()).pipe(Effect.provide(fake.layer))386 );387388 const result = yield* serialized(outcome);389390 expect(result).toContain(suite);391 expect(leakedIn(result)).toStrictEqual([]);392 expect(leakedIn(leftBy(fake.calls))).toStrictEqual([]);393 })394 );395396 it.effect(397 "without a sealed suite, keeps a failing public lane's log and signature, and a count lane's output",398 () =>399 Effect.gen(function* () {400 const fake = printing();401402 const ran = yield* check(withCountLane(Option.none())).pipe(403 Effect.provide(fake.layer)404 );405406 expect(ran.evidence[0]?.signature).toContain(SEALED[0]?.test);407 expect(ran.outputs).toHaveLength(1);408 expect(leakedIn(leftBy(fake.calls))).not.toStrictEqual([]);409 })410 );411412 it.effect(413 "keeps nothing a public lane printed once the sealed files sit in its tree: no log, no failure signature, no count output",414 () =>415 Effect.gen(function* () {416 const fake = printing();417418 const ran = yield* check(withCountLane(Option.some(heldBack))).pipe(419 Effect.provide(fake.layer)420 );421422 expect(423 ran.lanes.map(({ lane, result }) => ({ lane, result }))424 ).toStrictEqual([425 { lane: "unit", result: "failed" },426 { lane: "lint-count", result: "failed" },427 ]);428 expect(ran.evidence).toStrictEqual([429 { lane: "unit" },430 { lane: "lint-count" },431 ]);432 expect(ran).not.toHaveProperty("outputs");433 expect(leakedIn(JSON.stringify(ran))).toStrictEqual([]);434 expect(leakedIn(leftBy(fake.calls))).toStrictEqual([]);435 })436 );437438 it.effect(439 "makes no held-back write for a job without a sealed suite, and reports no areas",440 () =>441 Effect.gen(function* () {442 const fake = parserFails();443444 const ran = yield* check(wireFor(Option.none())).pipe(445 Effect.provide(fake.layer)446 );447448 expect(ran.heldBack).toStrictEqual([]);449 expect(fake.calls.filter(writesSealed)).toStrictEqual([]);450 expect(phasesOf(fake.calls)).toStrictEqual([451 "clone",452 "setup",453 "snapshot",454 "egressOff",455 "run",456 "report",457 "destroy",458 ]);459 })460 );461462 it.effect(463 "counts a sealed check that runs out of time, or whose container fails it, as not passed, and says no more",464 () =>465 Effect.gen(function* () {466 const started = yield* Latch.make();467 const [roundTrip] = SEALED;468469 const fake = fakeChecker({470 commands: new Map([471 // It says when it started, so the clock moves only once its472 // limit is running.473 [474 roundTrip?.command ?? "",475 started.open.pipe(Effect.andThen(Effect.never)),476 ],477 [478 weekFile?.command ?? "",479 Effect.fail(480 new BoxFailed({481 operation: "exec",482 reason: `process for ${weekFile?.command} died`,483 })484 ),485 ],486 ]),487 });488489 const fiber = yield* check(wireFor()).pipe(490 Effect.provide(fake.layer),491 Effect.forkChild492 );493494 yield* started.await;495 yield* TestClock.adjust(Duration.minutes(10));496497 const outcome = yield* Effect.exit(Fiber.join(fiber));498499 expect(Exit.map(outcome, ({ heldBack: areas }) => areas)).toStrictEqual(500 Exit.succeed([501 { area: "export", passed: 1, suite, total: 2 },502 { area: "parser", passed: 0, suite, total: 1 },503 ])504 );505 expect(leakedIn(leftBy(fake.calls))).toStrictEqual([]);506 })507 );508509 it.effect(510 "is VerifierBlocked, naming no path, when a sealed file cannot be written, and runs nothing after",511 () =>512 Effect.gen(function* () {513 const fake = parserFails({514 writeFile: (path) =>515 path.endsWith("iso-weeks.test.ts")516 ? Effect.fail(517 new BoxFailed({518 operation: "writeFile",519 reason: `ENOSPC writing ${path}`,520 })521 )522 : Effect.void,523 });524525 const outcome = yield* Effect.exit(526 check(wireFor()).pipe(Effect.provide(fake.layer))527 );528529 expect(Exit.findErrorOption(outcome)).toStrictEqual(530 Option.some(new VerifierBlocked({}))531 );532 expect(phasesOf(fake.calls)).toStrictEqual([533 "clone",534 "setup",535 "snapshot",536 "egressOff",537 "writeHeldBack",538 "report",539 "destroy",540 ]);541 expect(leakedIn(leftBy(fake.calls))).toStrictEqual([]);542 })543 );544545 it.effect(546 "is VerifierBlocked, writing nothing and naming no path, for a sealed file whose path leaves the checked tree",547 () =>548 Effect.gen(function* () {549 const outside = [550 "../escape.test.ts",551 "/etc/profile.d/escape.sh",552 "a/./b.ts",553 "a//b.ts",554 ];555556 const blocked = yield* Effect.forEach(outside, (path) =>557 Effect.gen(function* () {558 const fake = fakeChecker();559560 const wire = wireFor(561 Option.some({562 ...heldBack,563 files: [564 ...heldBack.files,565 {566 area: parser,567 content: new TextEncoder().encode("test('x', () => {});"),568 path: RepoPath.make(path),569 },570 ],571 })572 );573574 const outcome = yield* Effect.exit(575 check(wire).pipe(Effect.provide(fake.layer))576 );577578 return {579 error: Exit.findErrorOption(outcome),580 named: leftBy(fake.calls).includes(path),581 written: fake.calls.filter(writesSealed).length,582 };583 })584 );585586 expect(blocked).toStrictEqual(587 outside.map(() => ({588 error: Option.some(new VerifierBlocked({})),589 named: false,590 written: 0,591 }))592 );593 })594 );595596 it.live(597 "makes room for each sealed file whatever the answer's tree holds where it goes, and keeps the tree's other files",598 () =>599 Effect.gen(function* () {600 const fs = yield* FileSystem.FileSystem;601 const box = yield* Box;602 const tree = yield* fs.makeTempDirectoryScoped({ prefix: "tree-" });603604 const outside = yield* fs.makeTempDirectoryScoped({605 prefix: "outside-",606 });607608 const sealed = [609 "checks/held-back/export/round-trip.test.ts",610 "checks/held-back/parser/week-54.test.ts",611 "checks/held-back/tz/zone.test.ts",612 ];613614 // The answer's tree: a file where one sealed folder goes, a link to615 // a folder outside the tree where another goes, and a folder where616 // a sealed file goes, beside a file of its own. Left there, each617 // fails the write, and the refusal would tell the answer that a618 // sealed path is there without spending an attempt.619 yield* fs.makeDirectory(`${tree}/checks/held-back/tz/zone.test.ts`, {620 recursive: true,621 });622 yield* fs.writeFileString(`${tree}/checks/held-back/export`, "x\n");623 yield* fs.symlink(outside, `${tree}/checks/held-back/parser`);624 yield* fs.writeFileString(`${tree}/checks/own.test.ts`, "own\n");625626 const made = yield* box.exec(roomFor(tree, sealed), {627 cwd: tree,628 env: { PATH: "/usr/bin:/bin" },629 });630631 expect(made.exitCode).toBe(0);632633 yield* Effect.forEach(sealed, (path) =>634 box.writeFile(635 `${tree}/${path}`,636 new TextEncoder().encode(`sealed ${path}\n`)637 )638 );639640 expect(641 yield* Effect.forEach(sealed, (path) =>642 fs.readFileString(`${tree}/${path}`)643 )644 ).toStrictEqual(sealed.map((path) => `sealed ${path}\n`));645 expect(yield* fs.readFileString(`${tree}/checks/own.test.ts`)).toBe(646 "own\n"647 );648 expect(yield* fs.readDirectory(outside)).toStrictEqual([]);649 }).pipe(650 Effect.scoped,651 Effect.provide(Layer.merge(LocalBox, NodeServices.layer))652 )653 );654655 it("takes the held-back job the platform reads from the layer as it is", () => {656 expectTypeOf<HeldBackJob>().toEqualTypeOf<HeldBackPart>();657 });658659 it.effect(660 "takes the sealed files as base64 on the wire and writes the bytes they encode",661 () =>662 Effect.gen(function* () {663 const fake = parserFails();664 const encoded = yield* Schema.encodeEffect(CheckWire)(wireFor());665666 expect(encoded.job.heldBack?.files[0]).toStrictEqual({667 area: "export",668 contentBase64: btoa(SEALED[0]?.text ?? ""),669 path: SEALED[0]?.path,670 });671672 const outcome = yield* Effect.promise(() =>Merge observability into mainoscabrielbefore adoption1985111
line 673why, one step back673 answerJob(checkJob, (decoded) =>Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 674–690why, one step back674 check(decoded).pipe(Effect.provide(fake.layer))675 )(encoded)676 ).pipe(Effect.flatMap(Schema.decodeEffect(CheckExit)));677678 expect(679 Exit.map(outcome, ({ heldBack: areas }) =>680 areas.map(({ passed }) => passed)681 )682 ).toStrictEqual(Exit.succeed([2, 0]));683 expect(684 fake.calls.flatMap((call) =>685 call.kind === "writeFile" ? [call.text] : []686 )687 ).toStrictEqual(SEALED.map(({ text }) => text));688 })689 );690});