Reach the Checker and Lander through the sandbox binding with typed adapters that mint each job's only, short-lived tokens
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- apps/platform/src/adapters/sandbox-credentials.ts: withRemote(method, {repo, scope}, use) mints one token per repo with a 5-minute lifetime (jobTokenTtl), hands use the Remote, and revokes it in acquireUseRelease however the job ends; a revoke that fails is one warning line and never fails the job. sandboxJob encodes the wire with 301's schema, calls the binding, decodes the JSON Exit and settles it: success, a typed refusal as itself, and a rejected or throwing call, an undecodable or unencodable job or a far-side defect as VerifierBlocked with exactly one error line annotated with the method and failure, its detail scrubbed of every token the job carried and cut to 2,000 chars. - withRemote (one remote, nested) replaces the issue's withRemotes(needs, use(map)): a mint that fails after another revokes the first, and an adapter names each remote it holds with no missing-key branch. It takes the method so an unknown repo is VerifierBlocked, logged by method. - check-runner-sandbox.ts: SandboxBinding (property signatures, as lint requires; each method returns its Exit's encoded JSON) and CheckRunnerSandbox: one read token on the job's repo for the clone. - lander-sandbox.ts: merge reads canonical and the fork; land writes canonical and reads the fork only for a Merge rebuild; compose writes canonical (its compose ref lives there, per 301's ComposeWire); bundleRules reads canonical. Both layers capture RepoHost at build, so 317 provides it once. - Tests (apps/platform/test/sandbox-adapters.test.ts, 18): a fake SANDBOX that decodes each wire, runs W2's memory CheckRunner/Lander and encodes the Exit, over a recording memory RepoHost. The run and every Lander result come back; the exact mints per method and their 5-minute lifetimes; StaleBase and RepoBusy arrive typed; four breakages (rejects, throws, answers a non-Exit, dies) are VerifierBlocked with one error line by method; an unknown fork revokes canonical's token; every token is revoked, a failing revoke fails nothing; no token in any result, refusal or log line. A type test: Service<entrypoint shape> extends SandboxBinding. Red first by assertion; scrub, revoke and log level each checked by a mutation that the tests caught. - ASSUMPTION: a sandbox that echoes a token does so in plain text. - Open for 317 (env.SANDBOX is typed as a plain Fetcher), 304/306 (merge still pushes nothing), 399 (compose's canonical write token) and W6 (held-back needs a layer remote): in the issue's Comments.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+1106 added−0 removed
- tests:+722 added−0 removed
- other:+384 added−0 removed
Provenance
- Commit
b761e6d- Tree
4d8df94- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
e8acd94
4 files changed+1106 added−0 removed
added:apps/platform/src/adapters/check-runner-sandbox.ts+72 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172/** * `CheckRunner` over the sandbox Worker (spec §4.3): each run goes to the * Checker through the `SANDBOX` service binding, with one read token on the * repo it clones from and nothing else. The Checker's container never sees * the token (W3 315); its outcome comes back as the port's own `CheckRun` or * `VerifierBlocked`. */import { RepoHost } from "@repo/artifacts/repo-host";import { CheckRunner } from "@repo/checks/check-runner";import { CheckExit, CheckWire } from "@repo/checks/check-runner/wire";import type { BundleExit, BundleWire, ComposeExit, ComposeWire, LandExit, LandWire, MergeExit, MergeWire,} from "@repo/project/lander/wire";import { Effect, Layer } from "effect";
import { sandboxJob, withRemote } from "./sandbox-credentials.ts";
/** * The sandbox Worker's entrypoint, as the platform reaches it through the * `SANDBOX` service binding: each method takes a job's wire, encoded, and * answers with the job's `Exit` as JSON, which the adapters decode before * they trust any of it (principle 2). Structural, so 317 passes the binding * itself. */export interface SandboxBinding { readonly check: ( wire: typeof CheckWire.Encoded ) => Promise<typeof CheckExit.Encoded>; readonly merge: ( wire: typeof MergeWire.Encoded ) => Promise<typeof MergeExit.Encoded>; readonly land: ( wire: typeof LandWire.Encoded ) => Promise<typeof LandExit.Encoded>; readonly compose: ( wire: typeof ComposeWire.Encoded ) => Promise<typeof ComposeExit.Encoded>; readonly bundleRules: ( wire: typeof BundleWire.Encoded ) => Promise<typeof BundleExit.Encoded>;}
export const CheckRunnerSandbox = ( sandbox: SandboxBinding): Layer.Layer<CheckRunner, never, RepoHost> => Layer.effect( CheckRunner, Effect.gen(function* () { const host = yield* RepoHost;
return CheckRunner.of({ run: (job) => withRemote("check", { repo: job.repo, scope: "read" }, (clone) => sandboxJob({ exit: CheckExit, job: { clone, job }, method: "check", remotes: [clone], send: (wire) => sandbox.check(wire), wire: CheckWire, }) ).pipe(Effect.provideService(RepoHost, host)), }); }) );added:apps/platform/src/adapters/lander-sandbox.ts+104 added
1+/**2+ * `Lander` over the sandbox Worker (spec §4.3, D6): each job goes to the3+ * trusted Lander container through the `SANDBOX` service binding, with the4+ * fewest tokens it needs. Reads take read tokens: a merge on canonical and5+ * the fork, a bundle on canonical. A write token on canonical goes only to6+ * `land`, which moves `main` with a non-force compare-and-swap, and to7+ * `compose`, which pushes its compose ref alone; never to a Checker, never8+ * outside the platform's Workers (S1 change 2). The outcome comes back as9+ * the port's own types or its refusals: `StaleBase`, `RepoBusy`,10+ * `VerifierBlocked`.11+ */12+import { RepoHost } from "@repo/artifacts/repo-host";13+import type { RepoName } from "@repo/artifacts/repo-host";14+import { Lander, Rebuild } from "@repo/project/lander";15+import {16+ BundleExit,17+ BundleWire,18+ ComposeExit,19+ ComposeWire,20+ LandExit,21+ LandWire,22+ MergeExit,23+ MergeWire,24+} from "@repo/project/lander/wire";25+import { Effect, Layer } from "effect";26+27+import type { SandboxBinding } from "./check-runner-sandbox.ts";28+import { sandboxJob, withRemote } from "./sandbox-credentials.ts";29+import type { RemoteNeed } from "./sandbox-credentials.ts";30+31+const read = (repo: RepoName): RemoteNeed => ({ repo, scope: "read" });32+33+const write = (repo: RepoName): RemoteNeed => ({ repo, scope: "write" });34+35+/** One land, with every remote its wire carries. */36+const landing = (sandbox: SandboxBinding, wire: typeof LandWire.Type) =>37+ sandboxJob({38+ exit: LandExit,39+ job: wire,40+ method: "land",41+ remotes: wire.fork === undefined ? [wire.main] : [wire.main, wire.fork],42+ send: (encoded) => sandbox.land(encoded),43+ wire: LandWire,44+ });45+46+export const LanderSandbox = (47+ sandbox: SandboxBinding48+): Layer.Layer<Lander, never, RepoHost> =>49+ Layer.effect(50+ Lander,51+ Effect.gen(function* () {52+ const host = yield* RepoHost;53+54+ return Lander.of({55+ bundleRules: (job) =>56+ withRemote("bundleRules", read(job.repo), (main) =>57+ sandboxJob({58+ exit: BundleExit,59+ job: { job, main },60+ method: "bundleRules",61+ remotes: [main],62+ send: (wire) => sandbox.bundleRules(wire),63+ wire: BundleWire,64+ })65+ ).pipe(Effect.provideService(RepoHost, host)),66+ compose: (job) =>67+ withRemote("compose", write(job.repo), (main) =>68+ sandboxJob({69+ exit: ComposeExit,70+ job: { job, main },71+ method: "compose",72+ remotes: [main],73+ send: (wire) => sandbox.compose(wire),74+ wire: ComposeWire,75+ })76+ ).pipe(Effect.provideService(RepoHost, host)),77+ land: (job) =>78+ withRemote("land", write(job.repo), (main) =>79+ Rebuild.$match(job.rebuild, {80+ Compose: () => landing(sandbox, { job, main }),81+ Existing: () => landing(sandbox, { job, main }),82+ // Only a merge reads the answer's commits, from its fork.83+ Merge: ({ fork }) =>84+ withRemote("land", read(fork), (forkRemote) =>85+ landing(sandbox, { fork: forkRemote, job, main })86+ ),87+ })88+ ).pipe(Effect.provideService(RepoHost, host)),89+ merge: (job) =>90+ withRemote("merge", read(job.repo), (main) =>91+ withRemote("merge", read(job.fork), (fork) =>92+ sandboxJob({93+ exit: MergeExit,94+ job: { fork, job, main },95+ method: "merge",96+ remotes: [main, fork],97+ send: (wire) => sandbox.merge(wire),98+ wire: MergeWire,99+ })100+ )101+ ).pipe(Effect.provideService(RepoHost, host)),102+ });103+ })104+ );added:apps/platform/src/adapters/sandbox-credentials.ts+208 added
1+/**2+ * The only credentials a sandbox job carries, and the one way a job crosses3+ * the `SANDBOX` service binding (spec §4.3): the sandbox Worker has no4+ * Artifacts binding, so each job takes a token the platform minted for it5+ * alone, on one repo (tokens are per repo, S1 #10), with the narrowest scope6+ * the job needs and a lifetime of minutes, revoked as soon as the job ends7+ * (S1 change 2). A token never appears in a result, a refusal or a log: the8+ * wire redacts it, refusals carry no free text (principle 3), and what a9+ * failure log says is scrubbed of every token the job carried.10+ *11+ * A job is encoded with the wire schemas both sides share, and its outcome12+ * comes back as a JSON `Exit` decoded here (principle 2): a typed refusal13+ * stays typed; anything else (a rejected call, an outcome that won't decode,14+ * a defect on the far side) is `VerifierBlocked`, the gate's trouble and15+ * never the answer's, with one error-level log line naming the method.16+ */17+import { RepoHost } from "@repo/artifacts/repo-host";18+import type {19+ RepoName,20+ RepoNotFound,21+ TokenScope,22+} from "@repo/artifacts/repo-host";23+import type { Remote } from "@repo/checks/check-runner/wire";24+import { VerifierBlocked } from "@repo/protocol/refusal";25+import {26+ Cause,27+ Data,28+ Duration,29+ Effect,30+ Exit,31+ Option,32+ Redacted,33+ Schema,34+} from "effect";35+36+/**37+ * How long a job's token lives: enough for a cold container to start and38+ * fetch, short enough that a token outliving its job is dead within39+ * minutes (S1 #2: an expired token gets 403). Each is revoked when its job40+ * ends, so this bounds only a revoke that failed.41+ */42+export const jobTokenTtl = Duration.minutes(5);43+44+/** The sandbox entrypoint's methods: the one name every failure log carries. */45+export type SandboxMethod =46+ | "bundleRules"47+ | "check"48+ | "compose"49+ | "land"50+ | "merge";51+52+/** One repo a job reaches, and what it may do there. */53+export interface RemoteNeed {54+ readonly repo: RepoName;55+ readonly scope: TokenScope;56+}57+58+/** The longest failure detail a log line keeps. */59+const DETAIL_LIMIT = 2000;60+61+/**62+ * `text` without any token the job carried, cut to `DETAIL_LIMIT`: the far63+ * side holds the tokens and may echo one in an error.64+ */65+const scrub = (text: string, remotes: readonly Remote[]) => {66+ let scrubbed = text;67+68+ for (const { token } of remotes) {69+ const secret = Redacted.value(token);70+71+ if (secret.length > 0) {72+ scrubbed = scrubbed.replaceAll(secret, "<token>");73+ }74+ }75+76+ return scrubbed.slice(0, DETAIL_LIMIT);77+};78+79+/**80+ * The job could not run: one error-level log line, then `VerifierBlocked`,81+ * which carries no free text; what went wrong goes in the annotations.82+ */83+const blocked = (84+ method: SandboxMethod,85+ annotations: Readonly<Record<string, string>>86+) =>87+ Effect.logError("sandbox job blocked").pipe(88+ Effect.annotateLogs({ ...annotations, method }),89+ Effect.andThen(Effect.fail(new VerifierBlocked({})))90+ );91+92+/** A repo the store does not know: the job cannot run. */93+const unknownRepo =94+ (method: SandboxMethod) =>95+ ({ name }: RepoNotFound) =>96+ blocked(method, { failure: "repo not found", repo: name });97+98+/**99+ * Mints a `need.scope` token on `need.repo` for one job, hands `use` its100+ * remote, and revokes the token once `use` ends, however it ends. A revoke101+ * that fails is logged, never raised: the token dies with its lifetime. A102+ * repo the store does not know is `VerifierBlocked` for `method`.103+ */104+export const withRemote = <A, E, R>(105+ method: SandboxMethod,106+ need: RemoteNeed,107+ use: (remote: Remote) => Effect.Effect<A, E, R>108+): Effect.Effect<A, E | VerifierBlocked, R | RepoHost> =>109+ Effect.gen(function* () {110+ const host = yield* RepoHost;111+112+ const url = yield* host113+ .remote(need.repo)114+ .pipe(Effect.catchTag("RepoNotFound", unknownRepo(method)));115+116+ return yield* Effect.acquireUseRelease(117+ host118+ .mintToken(need.repo, need.scope, jobTokenTtl)119+ .pipe(Effect.catchTag("RepoNotFound", unknownRepo(method))),120+ ({ secret }) => use({ token: secret, url }),121+ ({ id }) =>122+ host.revokeToken(need.repo, id).pipe(123+ Effect.catchCause((cause) =>124+ Effect.logWarning("sandbox job token not revoked").pipe(125+ Effect.annotateLogs({126+ cause: Cause.pretty(cause),127+ method,128+ repo: need.repo,129+ tokenId: id,130+ })131+ )132+ )133+ )134+ );135+ });136+137+/** Why a job's outcome never arrived as a typed `Exit`. */138+class Unreached extends Data.TaggedError("Unreached")<{139+ readonly failure: "rejected" | "undecodable" | "unencodable";140+ readonly detail: string;141+}> {}142+143+/** One job for the sandbox: what to send, and how its wire and outcome are coded. */144+export interface SandboxJob<W, WI, A, E, X> {145+ readonly method: SandboxMethod;146+ readonly wire: Schema.Codec<W, WI>;147+ readonly exit: Schema.Codec<Exit.Exit<A, E>, X>;148+ readonly job: W;149+ /** Every remote `job` carries: their tokens are scrubbed from failure logs. */150+ readonly remotes: readonly Remote[];151+ /** The binding's method, called with the encoded job. */152+ readonly send: (encoded: WI) => Promise<X>;153+}154+155+/**156+ * An outcome as the port gives it: the success, a typed refusal as itself,157+ * and a defect or an interruption on the far side as `VerifierBlocked`.158+ */159+const settle = <A, E>(160+ method: SandboxMethod,161+ remotes: readonly Remote[],162+ exit: Exit.Exit<A, E>163+): Effect.Effect<A, E | VerifierBlocked> =>164+ Exit.isSuccess(exit)165+ ? Effect.succeed(exit.value)166+ : Option.match(Cause.findErrorOption(exit.cause), {167+ onNone: () =>168+ blocked(method, {169+ detail: scrub(Cause.pretty(exit.cause), remotes),170+ failure: "defect",171+ }),172+ onSome: (refusal): Effect.Effect<never, E> => Effect.fail(refusal),173+ });174+175+/**176+ * Sends one job and settles its outcome into the Effect's channels; a job177+ * whose outcome never arrived as an `Exit` is `VerifierBlocked`. Each178+ * failure is logged once, at error level.179+ */180+export const sandboxJob = <W, WI, A, E, X>(181+ call: SandboxJob<W, WI, A, E, X>182+): Effect.Effect<A, E | VerifierBlocked> =>183+ Schema.encodeEffect(call.wire)(call.job).pipe(184+ Effect.mapError(185+ ({ message }) =>186+ new Unreached({ detail: message, failure: "unencodable" })187+ ),188+ Effect.flatMap((encoded) =>189+ Effect.tryPromise({190+ catch: (cause) =>191+ new Unreached({ detail: String(cause), failure: "rejected" }),192+ try: () => call.send(encoded),193+ })194+ ),195+ Effect.flatMap((outcome) =>196+ Schema.decodeEffect(call.exit)(outcome).pipe(197+ Effect.mapError(198+ ({ message }) =>199+ new Unreached({ detail: message, failure: "undecodable" })200+ )201+ )202+ ),203+ Effect.matchEffect({204+ onFailure: ({ detail, failure }) =>205+ blocked(call.method, { detail: scrub(detail, call.remotes), failure }),206+ onSuccess: (exit) => settle(call.method, call.remotes, exit),207+ })208+ );added:apps/platform/test/sandbox-adapters.test.ts+722 added
1+import { describe, expect, expectTypeOf, it } from "@effect/vitest";2+import { RepoHost, RepoNotFound } from "@repo/artifacts/repo-host";3+import type { TokenScope } from "@repo/artifacts/repo-host";4+import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";5+import { Brand } from "@repo/brand";6+import { CheckAt, CheckRunner } from "@repo/checks/check-runner";7+import type { CheckJob } from "@repo/checks/check-runner";8+import { CheckRunnerMemory, scriptKey } from "@repo/checks/check-runner/memory";9+import { CheckExit, CheckWire } from "@repo/checks/check-runner/wire";10+import { Lander, Rebuild } from "@repo/project/lander";11+import type { LandJob } from "@repo/project/lander";12+import { LanderMemory } from "@repo/project/lander/memory";13+import type { LanderScript } from "@repo/project/lander/memory";14+import {15+ BundleExit,16+ BundleWire,17+ ComposeExit,18+ ComposeWire,19+ LandExit,20+ LandWire,21+ MergeExit,22+ MergeWire,23+} from "@repo/project/lander/wire";24+import type { LaneResult } from "@repo/protocol/domain/answer";25+import {26+ CommitSha,27+ Handle,28+ LandedSha,29+ LaneName,30+ ProjectName,31+ RepoName,32+ RepoPath,33+ RequestId,34+ TreeSha,35+} from "@repo/protocol/ids";36+import { RepoBusy, StaleBase, VerifierBlocked } from "@repo/protocol/refusal";37+import type { WorkerEntrypoint } from "cloudflare:workers";38+import {39+ Duration,40+ Effect,41+ Exit,42+ FiberSet,43+ Layer,44+ Logger,45+ Option,46+ Redacted,47+ Result,48+ Schema,49+} from "effect";50+51+import { CheckRunnerSandbox } from "../src/adapters/check-runner-sandbox.ts";52+import type { SandboxBinding } from "../src/adapters/check-runner-sandbox.ts";53+import { LanderSandbox } from "../src/adapters/lander-sandbox.ts";54+55+const project = ProjectName.make("datekit");56+57+const canonical = RepoName.make("datekit");58+59+const fork = RepoName.make("datekit--fix-parse--alice");60+61+const base = CommitSha.make("2".repeat(40));62+63+const head = CommitSha.make("3".repeat(40));64+65+const main = LandedSha.make("4".repeat(40));66+67+const tree = TreeSha.make("5".repeat(40));68+69+const composed = CommitSha.make("6".repeat(40));70+71+const landed = LandedSha.make("7".repeat(40));72+73+const path = RepoPath.make("src/parse.ts");74+75+const lane = LaneName.make("test");76+77+const failed: LaneResult = {78+ command: "bun test",79+ durationMs: 1200,80+ lane,81+ result: "failed",82+};83+84+/** One lane on an answer's merged tree, cloned from the claim's fork. */85+const checkJob: CheckJob = {86+ at: CheckAt.cases.Tree.make({ tree }),87+ lanes: [{ command: "bun test", lane }],88+ placeholders: [],89+ project,90+ proxies: [],91+ repo: fork,92+};93+94+const mergeJob = { base, fork, head, main, repo: canonical };95+96+const landJob = (rebuild: Rebuild): LandJob => ({97+ author: Handle.make("alice"),98+ main,99+ message: "Fix the parser\n\nRequest-Id: request-0001\n",100+ rebuild,101+ repo: canonical,102+ requestId: RequestId.make("request-0001"),103+ tree,104+ verdict: Option.none(),105+});106+107+const landMerge = landJob(Rebuild.Merge({ base, fork, head }));108+109+const composeJob = {110+ files: [{ content: "export {};\n", path }] as const,111+ main,112+ repo: canonical,113+};114+115+const bundleJob = { at: main, repo: canonical };116+117+const bundle = {118+ entry: `${Brand.configDir}/project.ts`,119+ modules: {},120+ sdkVersion: "1.0.0",121+};122+123+const merged = { changes: [{ path, status: "modified" as const }], tree };124+125+const stale = new StaleBase({ base, conflicts: [path], main });126+127+/** What the memory Lander inside the fake sandbox answers, unless a test says otherwise. */128+const landerScript: LanderScript = {129+ bundle: [Result.succeed(bundle)],130+ compose: [Result.succeed({ commit: composed, tree })],131+ land: [Result.succeed({ pending: [], sha: landed })],132+ merge: [Result.succeed(merged)],133+};134+135+/** One token a job minted, as the store gave it out. */136+interface Minted {137+ readonly repo: RepoName;138+ readonly scope: TokenScope;139+ readonly ttlMs: number;140+ readonly id: string;141+ readonly secret: string;142+}143+144+/**145+ * The memory store with the canonical repo and a claim's fork, recording146+ * every token it mints and every revoke it is asked for; with `failRevoke`,147+ * every revoke fails after it is recorded.148+ */149+const recordingRepoHost = (failRevoke: boolean) =>150+ Effect.gen(function* () {151+ const store = yield* RepoHost;152+ const minted: Minted[] = [];153+ const revoked: { readonly repo: RepoName; readonly id: string }[] = [];154+155+ yield* store.create(canonical);156+ yield* store.create(fork);157+158+ const host = RepoHost.of({159+ ...store,160+ mintToken: (repo, scope, ttl) =>161+ store.mintToken(repo, scope, ttl).pipe(162+ Effect.tap(({ id, secret }) =>163+ Effect.sync(() =>164+ minted.push({165+ id,166+ repo,167+ scope,168+ secret: Redacted.value(secret),169+ ttlMs: Duration.toMillis(ttl),170+ })171+ )172+ )173+ ),174+ revokeToken: (repo, id) =>175+ Effect.sync(() => revoked.push({ id, repo })).pipe(176+ Effect.andThen(177+ failRevoke178+ ? Effect.fail(new RepoNotFound({ name: repo }))179+ : store.revokeToken(repo, id)180+ )181+ ),182+ });183+184+ return { host, minted, revoked };185+ }).pipe(Effect.provide(RepoHostMemory));186+187+/** Every wire the fake sandbox decoded, by method. */188+interface Seen {189+ readonly bundleRules: (typeof BundleWire.Type)[];190+ readonly check: (typeof CheckWire.Type)[];191+ readonly compose: (typeof ComposeWire.Type)[];192+ readonly land: (typeof LandWire.Type)[];193+ readonly merge: (typeof MergeWire.Type)[];194+}195+196+/**197+ * The sandbox Worker's entrypoint as the service binding reaches it, in198+ * memory: each method decodes its wire with 301's schema, runs the memory199+ * `CheckRunner` or `Lander` it was built over, and encodes the `Exit`. It200+ * keeps every wire it decoded, by method.201+ */202+const fakeSandbox = Effect.gen(function* () {203+ const run = yield* FiberSet.makeRuntimePromise<CheckRunner | Lander>();204+205+ const seen: Seen = {206+ bundleRules: [],207+ check: [],208+ compose: [],209+ land: [],210+ merge: [],211+ };212+213+ /** Decodes a wire into `into`, runs its job, and encodes the outcome. */214+ const answer =215+ <W, WI, A, E, X>(216+ wire: Schema.Codec<W, WI>,217+ exit: Schema.Codec<Exit.Exit<A, E>, X>,218+ into: W[],219+ job: (decoded: W) => Effect.Effect<A, E, CheckRunner | Lander>220+ ) =>221+ (encoded: WI): Promise<X> =>222+ run(223+ Schema.decodeEffect(wire)(encoded).pipe(224+ Effect.orDie,225+ Effect.tap((decoded) => Effect.sync(() => into.push(decoded))),226+ Effect.flatMap(job),227+ Effect.exit,228+ Effect.flatMap((outcome) =>229+ Effect.orDie(Schema.encodeEffect(exit)(outcome))230+ )231+ )232+ );233+234+ const sandbox: SandboxBinding = {235+ bundleRules: answer(BundleWire, BundleExit, seen.bundleRules, ({ job }) =>236+ Lander.use((lander) => lander.bundleRules(job))237+ ),238+ check: answer(CheckWire, CheckExit, seen.check, ({ job }) =>239+ CheckRunner.use((runner) => runner.run(job))240+ ),241+ compose: answer(ComposeWire, ComposeExit, seen.compose, ({ job }) =>242+ Lander.use((lander) => lander.compose(job))243+ ),244+ land: answer(LandWire, LandExit, seen.land, ({ job }) =>245+ Lander.use((lander) => lander.land(job))246+ ),247+ merge: answer(MergeWire, MergeExit, seen.merge, ({ job }) =>248+ Lander.use((lander) => lander.merge(job))249+ ),250+ };251+252+ return { sandbox, seen };253+});254+255+interface WorldOptions {256+ readonly script?: LanderScript;257+ /** The binding the adapters get, made from the fake's. */258+ readonly binding?: (sandbox: SandboxBinding) => SandboxBinding;259+ readonly failRevoke?: boolean;260+}261+262+/**263+ * Both adapters over a fake sandbox and a recording store, and what the264+ * fake and the store saw.265+ */266+const world = (options: WorldOptions = {}) =>267+ Effect.gen(function* () {268+ const { host, minted, revoked } = yield* recordingRepoHost(269+ options.failRevoke ?? false270+ );271+272+ const fake = yield* fakeSandbox.pipe(273+ Effect.provide(274+ Layer.mergeAll(275+ CheckRunnerMemory.layer(276+ new Map([[scriptKey(checkJob.at, lane), [failed]]])277+ ),278+ LanderMemory.layer(options.script ?? landerScript)279+ )280+ )281+ );282+283+ const binding = options.binding?.(fake.sandbox) ?? fake.sandbox;284+285+ const { lander, runner } = yield* Effect.gen(function* () {286+ return { lander: yield* Lander, runner: yield* CheckRunner };287+ }).pipe(288+ Effect.provide(289+ Layer.mergeAll(290+ CheckRunnerSandbox(binding),291+ LanderSandbox(binding)292+ ).pipe(Layer.provide(Layer.succeed(RepoHost, host)))293+ )294+ );295+296+ return { host, lander, minted, revoked, runner, seen: fake.seen };297+ });298+299+/** One log line, as the structured logger renders it. */300+type Line = ReturnType<typeof Logger.formatStructured.log>;301+302+/** Runs `body` with every log line it writes kept: its exit, and the lines. */303+const withLogs = <A, E>(body: Effect.Effect<A, E>) =>304+ Effect.gen(function* () {305+ const lines: Line[] = [];306+307+ const exit = yield* Effect.exit(body).pipe(308+ Effect.provide(309+ Logger.layer([310+ Logger.make((options) => {311+ lines.push(Logger.formatStructured.log(options));312+ }),313+ ])314+ )315+ );316+317+ return { exit, lines };318+ });319+320+/** Which repo each token was minted on, with which scope. */321+const mintsOf = (minted: readonly Minted[]) =>322+ minted.map(({ repo, scope }) => ({ repo, scope }));323+324+/** A wire remote, with its token in the clear for comparing. */325+const opened = (remote: {326+ readonly token: Redacted.Redacted;327+ readonly url: string;328+}) => ({329+ token: Redacted.value(remote.token),330+ url: remote.url,331+});332+333+type World = Effect.Success<ReturnType<typeof world>>;334+335+/** Every operation of both adapters once, a land for each rebuild that reads a fork or not. */336+const everyJob = ({337+ lander,338+ runner,339+}: World): readonly Effect.Effect<340+ object,341+ RepoBusy | StaleBase | VerifierBlocked342+>[] => [343+ runner.run(checkJob),344+ lander.merge(mergeJob),345+ lander.land(landMerge),346+ lander.land(landJob(Rebuild.Existing({ commit: composed }))),347+ lander.compose(composeJob),348+ lander.bundleRules(bundleJob),349+];350+351+/** By token id, so revokes in any order compare. */352+const byId = <T extends { readonly id: string }>(tokens: readonly T[]) =>353+ tokens.toSorted((a, b) => a.id.localeCompare(b.id));354+355+/**356+ * The sandbox Worker's default entrypoint, by its shape in357+ * `apps/sandbox/src/worker.ts` (an app may not import another app).358+ */359+interface SandboxEntrypoint extends WorkerEntrypoint<Env> {360+ readonly check: (361+ wire: typeof CheckWire.Encoded362+ ) => Promise<typeof CheckExit.Encoded>;363+ readonly merge: (364+ wire: typeof MergeWire.Encoded365+ ) => Promise<typeof MergeExit.Encoded>;366+ readonly land: (367+ wire: typeof LandWire.Encoded368+ ) => Promise<typeof LandExit.Encoded>;369+ readonly compose: (370+ wire: typeof ComposeWire.Encoded371+ ) => Promise<typeof ComposeExit.Encoded>;372+ readonly bundleRules: (373+ wire: typeof BundleWire.Encoded374+ ) => Promise<typeof BundleExit.Encoded>;375+}376+377+describe("the sandbox binding", () => {378+ it("is the service binding's RPC stub as the runtime types it", () => {379+ expectTypeOf<Service<SandboxEntrypoint>>().toExtend<SandboxBinding>();380+ });381+});382+383+describe("the sandbox CheckRunner", () => {384+ it.effect(385+ "returns the Checker's run, cloned with a read token on the answer's repo",386+ () =>387+ Effect.gen(function* () {388+ const { host, minted, runner, seen } = yield* world();389+390+ expect(yield* Effect.exit(runner.run(checkJob))).toStrictEqual(391+ Exit.succeed({392+ durationMs: 1200,393+ evidence: [{ lane, signature: "test: scripted failure" }],394+ heldBack: [],395+ lanes: [failed],396+ })397+ );398+ expect(mintsOf(minted)).toStrictEqual([{ repo: fork, scope: "read" }]);399+ expect(seen.check.map(({ clone }) => opened(clone))).toStrictEqual([400+ { token: minted[0]?.secret, url: yield* host.remote(fork) },401+ ]);402+ })403+ );404+});405+406+describe("the sandbox Lander", () => {407+ it.effect(408+ "merges with read tokens on canonical and the fork, and nothing more",409+ () =>410+ Effect.gen(function* () {411+ const { host, lander, minted, seen } = yield* world();412+413+ expect(yield* Effect.exit(lander.merge(mergeJob))).toStrictEqual(414+ Exit.succeed(merged)415+ );416+ expect(mintsOf(minted)).toStrictEqual([417+ { repo: canonical, scope: "read" },418+ { repo: fork, scope: "read" },419+ ]);420+ expect(421+ seen.merge.map((wire) => ({422+ fork: opened(wire.fork),423+ main: opened(wire.main),424+ }))425+ ).toStrictEqual([426+ {427+ fork: { token: minted[1]?.secret, url: yield* host.remote(fork) },428+ main: {429+ token: minted[0]?.secret,430+ url: yield* host.remote(canonical),431+ },432+ },433+ ]);434+ })435+ );436+437+ it.effect(438+ "lands a merge with one write token on canonical and a read token on the fork",439+ () =>440+ Effect.gen(function* () {441+ const { host, lander, minted, seen } = yield* world();442+443+ expect(yield* Effect.exit(lander.land(landMerge))).toStrictEqual(444+ Exit.succeed({ pending: [], sha: landed })445+ );446+ expect(mintsOf(minted)).toStrictEqual([447+ { repo: canonical, scope: "write" },448+ { repo: fork, scope: "read" },449+ ]);450+ expect(451+ seen.land.map((wire) => ({452+ fork: Option.map(Option.fromUndefinedOr(wire.fork), opened),453+ main: Redacted.value(wire.main.token),454+ }))455+ ).toStrictEqual([456+ {457+ fork: Option.some({458+ token: minted[1]?.secret,459+ url: yield* host.remote(fork),460+ }),461+ main: minted[0]?.secret,462+ },463+ ]);464+ })465+ );466+467+ it.effect.each([468+ Rebuild.Compose({ files: composeJob.files }),469+ Rebuild.Existing({ commit: composed }),470+ ])(471+ "lands a $_tag rebuild with the write token on canonical alone",472+ (rebuild) =>473+ Effect.gen(function* () {474+ const { lander, minted, seen } = yield* world();475+476+ expect(yield* Effect.exit(lander.land(landJob(rebuild)))).toStrictEqual(477+ Exit.succeed({ pending: [], sha: landed })478+ );479+ expect(mintsOf(minted)).toStrictEqual([480+ { repo: canonical, scope: "write" },481+ ]);482+ expect(seen.land.map((wire) => wire.fork)).toStrictEqual([undefined]);483+ })484+ );485+486+ it.effect(487+ "composes with one write token on canonical, for its compose ref",488+ () =>489+ Effect.gen(function* () {490+ const { lander, minted, seen } = yield* world();491+492+ expect(yield* Effect.exit(lander.compose(composeJob))).toStrictEqual(493+ Exit.succeed({ commit: composed, tree })494+ );495+ expect(mintsOf(minted)).toStrictEqual([496+ { repo: canonical, scope: "write" },497+ ]);498+ expect(499+ seen.compose.map((wire) => Redacted.value(wire.main.token))500+ ).toStrictEqual([minted[0]?.secret]);501+ })502+ );503+504+ it.effect("bundles the config folder with one read token on canonical", () =>505+ Effect.gen(function* () {506+ const { lander, minted, seen } = yield* world();507+508+ expect(yield* Effect.exit(lander.bundleRules(bundleJob))).toStrictEqual(509+ Exit.succeed(bundle)510+ );511+ expect(mintsOf(minted)).toStrictEqual([512+ { repo: canonical, scope: "read" },513+ ]);514+ expect(515+ seen.bundleRules.map((wire) => Redacted.value(wire.main.token))516+ ).toStrictEqual([minted[0]?.secret]);517+ })518+ );519+520+ it.effect("gives every token a lifetime of five minutes", () =>521+ Effect.gen(function* () {522+ const ok = yield* world();523+524+ yield* Effect.forEach(everyJob(ok), (job) => Effect.exit(job));525+526+ expect(ok.minted.map(({ ttlMs }) => ttlMs)).toStrictEqual(527+ Array.from({ length: 8 }, () => 300_000)528+ );529+ })530+ );531+});532+533+/** A way the sandbox's `merge` can fail to answer with an `Exit`, each echoing a token it was sent. */534+interface Breakage {535+ readonly name: string;536+ readonly failure: string;537+ readonly merge: SandboxBinding["merge"];538+}539+540+const breakages: readonly Breakage[] = [541+ {542+ failure: "rejected",543+ merge: (wire) =>544+ Promise.reject(545+ new Error(`no fetch from ${wire.main.url}: ${wire.main.token}`)546+ ),547+ name: "rejects",548+ },549+ {550+ failure: "rejected",551+ merge: (wire) => {552+ throw new Error(`no fork at ${wire.fork.token}`);553+ },554+ name: "throws",555+ },556+ {557+ failure: "undecodable",558+ merge: (wire) => Promise.resolve({ sha: wire.main.token }),559+ name: "answers with something that is not an Exit",560+ },561+ {562+ failure: "defect",563+ merge: (wire) =>564+ Promise.resolve(565+ Schema.encodeSync(MergeExit)(566+ Exit.die(new Error(`git said ${wire.main.token}`))567+ )568+ ),569+ name: "dies on the far side",570+ },571+];572+573+/** Every secret in `minted` that `text` contains. */574+const leaked = (text: string, minted: readonly Minted[]) =>575+ minted.flatMap(({ secret }) => (text.includes(secret) ? [secret] : []));576+577+describe("a sandbox job that fails", () => {578+ it.effect(579+ "arrives as the typed StaleBase or RepoBusy the Lander refused with",580+ () =>581+ Effect.gen(function* () {582+ const busy = new RepoBusy({});583+584+ const { lander } = yield* world({585+ script: { land: [Result.fail(busy)], merge: [Result.fail(stale)] },586+ });587+588+ expect(yield* Effect.exit(lander.merge(mergeJob))).toStrictEqual(589+ Exit.fail(stale)590+ );591+ expect(yield* Effect.exit(lander.land(landMerge))).toStrictEqual(592+ Exit.fail(busy)593+ );594+ })595+ );596+597+ it.effect.each(breakages)(598+ "is VerifierBlocked, logged once by its method and with no token, when the sandbox $name",599+ ({ failure, merge }) =>600+ Effect.gen(function* () {601+ const { lander, minted, revoked } = yield* world({602+ binding: (sandbox) => ({ ...sandbox, merge }),603+ });604+605+ const { exit, lines } = yield* withLogs(lander.merge(mergeJob));606+607+ expect(exit).toStrictEqual(Exit.fail(new VerifierBlocked({})));608+ expect(609+ lines610+ .filter(({ level }) => level === "ERROR")611+ .map(({ annotations }) => ({612+ failure: annotations.failure,613+ method: annotations.method,614+ }))615+ ).toStrictEqual([{ failure, method: "merge" }]);616+ expect(leaked(JSON.stringify(lines), minted)).toStrictEqual([]);617+ expect(revoked.map(({ id }) => id)).toStrictEqual(618+ minted.map(({ id }) => id).toReversed()619+ );620+ })621+ );622+623+ it.effect(624+ "is VerifierBlocked on a repo the store does not know, and revokes what it minted first",625+ () =>626+ Effect.gen(function* () {627+ const { lander, minted, revoked } = yield* world();628+ const gone = RepoName.make("datekit--gone--bob");629+630+ const { exit, lines } = yield* withLogs(631+ lander.merge({ ...mergeJob, fork: gone })632+ );633+634+ expect(exit).toStrictEqual(Exit.fail(new VerifierBlocked({})));635+ expect(mintsOf(minted)).toStrictEqual([636+ { repo: canonical, scope: "read" },637+ ]);638+ expect(revoked.map(({ id }) => id)).toStrictEqual(639+ minted.map(({ id }) => id)640+ );641+ expect(642+ lines.map(({ annotations, level }) => ({643+ failure: annotations.failure,644+ level,645+ method: annotations.method,646+ repo: annotations.repo,647+ }))648+ ).toStrictEqual([649+ {650+ failure: "repo not found",651+ level: "ERROR",652+ method: "merge",653+ repo: gone,654+ },655+ ]);656+ })657+ );658+});659+660+describe("a sandbox job's tokens", () => {661+ it.effect("are each revoked once their job has ended", () =>662+ Effect.gen(function* () {663+ const ok = yield* world();664+665+ yield* Effect.forEach(everyJob(ok), (job) => Effect.exit(job));666+667+ expect(ok.minted).toHaveLength(8);668+ expect(byId(ok.revoked)).toStrictEqual(669+ byId(ok.minted.map(({ id, repo }) => ({ id, repo })))670+ );671+ })672+ );673+674+ it.effect("fail no job when they cannot be revoked", () =>675+ Effect.gen(function* () {676+ const { lander, minted, revoked } = yield* world({ failRevoke: true });677+678+ const { exit, lines } = yield* withLogs(lander.land(landMerge));679+680+ expect(exit).toStrictEqual(Exit.succeed({ pending: [], sha: landed }));681+ expect(revoked.map(({ id }) => id)).toStrictEqual(682+ minted.map(({ id }) => id).toReversed()683+ );684+ expect(lines.map(({ level }) => level)).toStrictEqual(["WARN", "WARN"]);685+ })686+ );687+688+ it.effect("appear in no result, refusal or log line", () =>689+ Effect.gen(function* () {690+ const ok = yield* world();691+692+ const refusing = yield* world({693+ script: {694+ ...landerScript,695+ land: [Result.fail(new RepoBusy({}))],696+ merge: [Result.fail(stale)],697+ },698+ });699+700+ const broken = yield* Effect.forEach(breakages, ({ merge }) =>701+ world({ binding: (sandbox) => ({ ...sandbox, merge }) })702+ );703+704+ const { exit, lines } = yield* withLogs(705+ Effect.forEach(706+ [707+ ...everyJob(ok),708+ ...everyJob(refusing),709+ ...broken.map(({ lander }) => lander.merge(mergeJob)),710+ ],711+ (job) => Effect.exit(job)712+ )713+ );714+715+ const minted = [ok, refusing, ...broken].flatMap((each) => each.minted);716+717+ expect(minted).toHaveLength(24);718+ expect(leaked(JSON.stringify(exit), minted)).toStrictEqual([]);719+ expect(leaked(JSON.stringify(lines), minted)).toStrictEqual([]);720+ })721+ );722+});