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