Skip to content
Myr

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

4 files+1135 added−0 removed

added:apps/platform/src/adapters/check-runner-sandbox.ts+72 added
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 */12import { RepoHost } from "@repo/artifacts/repo-host";13import type { RepoName } from "@repo/artifacts/repo-host";14import { Lander, Rebuild } from "@repo/project/lander";15import {16 BundleExit,17 BundleWire,18 ComposeExit,19 ComposeWire,20 LandExit,21 LandWire,22 MergeExit,23 MergeWire,24} from "@repo/project/lander/wire";25import { Effect, Layer } from "effect";2627import type { SandboxBinding } from "./check-runner-sandbox.ts";28import { sandboxJob, withRemote } from "./sandbox-credentials.ts";29import type { RemoteNeed } from "./sandbox-credentials.ts";3031const read = (repo: RepoName): RemoteNeed => ({ repo, scope: "read" });3233const write = (repo: RepoName): RemoteNeed => ({ repo, scope: "write" });3435/** One land, with every remote its wire carries. */36const 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 });4546export const LanderSandbox = (47 sandbox: SandboxBinding48): Layer.Layer<Lander, never, RepoHost> =>49 Layer.effect(50 Lander,51 Effect.gen(function* () {52 const host = yield* RepoHost;5354 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 */19import { RepoHost } from "@repo/artifacts/repo-host";20import type {21 RepoName,22 RepoNotFound,23 TokenScope,24} from "@repo/artifacts/repo-host";25import type { Remote } from "@repo/checks/check-runner/wire";26import { VerifierBlocked } from "@repo/protocol/refusal";27import {28 Cause,29 Data,30 Duration,31 Effect,32 Exit,33 Option,34 Redacted,35 Schema,36} from "effect";3738/**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 */44export const jobTokenTtl = Duration.minutes(5);4546/** The sandbox entrypoint's methods: the one name every failure log carries. */47export type SandboxMethod =48 | "bundleRules"49 | "check"50 | "compose"51 | "land"52 | "merge";5354/** One repo a job reaches, and what it may do there. */55export interface RemoteNeed {56 readonly repo: RepoName;57 readonly scope: TokenScope;58}5960/** The longest failure detail a log line keeps. */61const DETAIL_LIMIT = 2000;6263/**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 */67const scrub = (text: string, remotes: readonly Remote[]) => {68 let scrubbed = text;6970 for (const { token } of remotes) {71 const secret = Redacted.value(token);7273 if (secret.length > 0) {74 scrubbed = scrubbed.replaceAll(secret, "<token>");75 }76 }7778 return scrubbed.slice(0, DETAIL_LIMIT);79};8081/**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 */85const 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 );9394/** A repo the store does not know: the job cannot run. */95const unknownRepo =96 (method: SandboxMethod) =>97 ({ name }: RepoNotFound) =>98 blocked(method, { failure: "repo not found", repo: name });99100/**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 */107export 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;114115 const url = yield* host116 .remote(need.repo)117 .pipe(Effect.catchTag("RepoNotFound", unknownRepo(method)));118119 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 });143144/** Why a job's outcome never arrived as a typed `Exit`. */145class Unreached extends Data.TaggedError("Unreached")<{146 readonly failure: "rejected" | "undecodable" | "unencodable";147 readonly detail: string;148}> {}149150/** One job for the sandbox: what to send, and how its wire and outcome are coded. */151export 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}161162/**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 */166const 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 });181182/**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 */187export 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
1import { describe, expect, expectTypeOf, it } from "@effect/vitest";2import { RepoHost } from "@repo/artifacts/repo-host";3import type { TokenScope } from "@repo/artifacts/repo-host";4import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";5import { Brand } from "@repo/brand";6import { CheckAt, CheckRunner } from "@repo/checks/check-runner";7import type { CheckJob } from "@repo/checks/check-runner";8import { CheckRunnerMemory, scriptKey } from "@repo/checks/check-runner/memory";9import { CheckExit, CheckWire } from "@repo/checks/check-runner/wire";10import { Lander, Rebuild } from "@repo/project/lander";11import type { LandJob } from "@repo/project/lander";12import { LanderMemory } from "@repo/project/lander/memory";13import type { LanderScript } from "@repo/project/lander/memory";14import {15 BundleExit,16 BundleWire,17 ComposeExit,18 ComposeWire,19 LandExit,20 LandWire,21 MergeExit,22 MergeWire,23} from "@repo/project/lander/wire";24import type { LaneResult } from "@repo/protocol/domain/answer";25import {26 CommitSha,27 Handle,28 LandedSha,29 LaneName,30 ProjectName,31 RepoName,32 RepoPath,33 RequestId,34 TreeSha,35} from "@repo/protocol/ids";36import { RepoBusy, StaleBase, VerifierBlocked } from "@repo/protocol/refusal";37import type { WorkerEntrypoint } from "cloudflare:workers";38import {39 Duration,40 Effect,41 Exit,42 FiberSet,43 Layer,44 Logger,45 Option,46 Redacted,47 Result,48 Schema,49} from "effect";5051import { CheckRunnerSandbox } from "../src/adapters/check-runner-sandbox.ts";52import type { SandboxBinding } from "../src/adapters/check-runner-sandbox.ts";53import { LanderSandbox } from "../src/adapters/lander-sandbox.ts";5455const project = ProjectName.make("datekit");5657const canonical = RepoName.make("datekit");5859const fork = RepoName.make("datekit--fix-parse--alice");6061const base = CommitSha.make("2".repeat(40));6263const head = CommitSha.make("3".repeat(40));6465const main = LandedSha.make("4".repeat(40));6667const tree = TreeSha.make("5".repeat(40));6869const composed = CommitSha.make("6".repeat(40));7071const landed = LandedSha.make("7".repeat(40));7273const path = RepoPath.make("src/parse.ts");7475const lane = LaneName.make("test");7677const failed: LaneResult = {78 command: "bun test",79 durationMs: 1200,80 lane,81 result: "failed",82};8384/** One lane on an answer's merged tree, cloned from the claim's fork. */85const 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};9394const mergeJob = { base, fork, head, main, repo: canonical };9596const 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});106107const landMerge = landJob(Rebuild.Merge({ base, fork, head }));108109const composeJob = {110 files: [{ content: "export {};\n", path }] as const,111 main,112 repo: canonical,113};114115const bundleJob = { at: main, repo: canonical };116117const bundle = {118 entry: `${Brand.configDir}/project.ts`,119 modules: {},120 sdkVersion: "1.0.0",121};122123const merged = { changes: [{ path, status: "modified" as const }], tree };124125const stale = new StaleBase({ base, conflicts: [path], main });126127/** What the memory Lander inside the fake sandbox answers, unless a test says otherwise. */128const 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};134135/** One token a job minted, as the store gave it out. */136interface Minted {137 readonly repo: RepoName;138 readonly scope: TokenScope;139 readonly ttlMs: number;140 readonly id: string;141 readonly secret: string;142}143144/**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 */150const 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 }[] = [];155156 yield* store.create(canonical);157 yield* store.create(fork);158159 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 });188189 return { host, minted, revoked };190 }).pipe(Effect.provide(RepoHostMemory));191192/** Every wire the fake sandbox decoded, by method. */193interface 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}200201/**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 */207const fakeSandbox = Effect.gen(function* () {208 const run = yield* FiberSet.makeRuntimePromise<CheckRunner | Lander>();209210 const seen: Seen = {211 bundleRules: [],212 check: [],213 compose: [],214 land: [],215 merge: [],216 };217218 /** 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 );238239 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 };256257 return { sandbox, seen };258});259260interface 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}266267/**268 * Both adapters over a fake sandbox and a recording store, and what the269 * fake and the store saw.270 */271const world = (options: WorldOptions = {}) =>272 Effect.gen(function* () {273 const { host, minted, revoked } = yield* recordingRepoHost(274 options.failRevoke ?? false275 );276277 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 );287288 const binding = options.binding?.(fake.sandbox) ?? fake.sandbox;289290 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 );300301 return { host, lander, minted, revoked, runner, seen: fake.seen };302 });303304/** One log line, as the structured logger renders it. */305type Line = ReturnType<typeof Logger.formatStructured.log>;306307/** Runs `body` with every log line it writes kept: its exit, and the lines. */308const withLogs = <A, E>(body: Effect.Effect<A, E>) =>309 Effect.gen(function* () {310 const lines: Line[] = [];311312 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 );321322 return { exit, lines };323 });324325/** Which repo each token was minted on, with which scope. */326const mintsOf = (minted: readonly Minted[]) =>327 minted.map(({ repo, scope }) => ({ repo, scope }));328329/** A wire remote, with its token in the clear for comparing. */330const opened = (remote: {331 readonly token: Redacted.Redacted;332 readonly url: string;333}) => ({334 token: Redacted.value(remote.token),335 url: remote.url,336});337338type World = Effect.Success<ReturnType<typeof world>>;339340/** Every operation of both adapters once, a land for each rebuild that reads a fork or not. */341const 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];355356/** By token id, so revokes in any order compare. */357const byId = <T extends { readonly id: string }>(tokens: readonly T[]) =>358 tokens.toSorted((a, b) => a.id.localeCompare(b.id));359360/**361 * The sandbox Worker's default entrypoint, by its shape in362 * `apps/sandbox/src/worker.ts` (an app may not import another app).363 */364interface 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}381382describe("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});387388describe("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();394395 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});410411describe("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();417418 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 );441442 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();447448 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 );471472 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();480481 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 );490491 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();496497 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 );508509 it.effect("bundles the config folder with one read token on canonical", () =>510 Effect.gen(function* () {511 const { lander, minted, seen } = yield* world();512513 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 );524525 it.effect("gives every token a lifetime of five minutes", () =>526 Effect.gen(function* () {527 const ok = yield* world();528529 yield* Effect.forEach(everyJob(ok), (job) => Effect.exit(job));530531 expect(ok.minted.map(({ ttlMs }) => ttlMs)).toStrictEqual(532 Array.from({ length: 8 }, () => 300_000)533 );534 })535 );536});537538/** A way the sandbox's `merge` can fail to answer with an `Exit`, each echoing a token it was sent. */539interface Breakage {540 readonly name: string;541 readonly failure: string;542 readonly merge: SandboxBinding["merge"];543}544545const 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];577578/** Every secret in `minted` that `text` contains. */579const leaked = (text: string, minted: readonly Minted[]) =>580 minted.flatMap(({ secret }) => (text.includes(secret) ? [secret] : []));581582describe("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({});588589 const { lander } = yield* world({590 script: { land: [Result.fail(busy)], merge: [Result.fail(stale)] },591 });592593 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 );601602 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 });609610 const { exit, lines } = yield* withLogs(lander.merge(mergeJob));611612 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 );627628 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");634635 const { exit, lines } = yield* withLogs(636 lander.merge({ ...mergeJob, fork: gone })637 );638639 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});664665describe("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();669670 yield* Effect.forEach(everyJob(ok), (job) => Effect.exit(job));671672 expect(ok.minted).toHaveLength(8);673 expect(byId(ok.revoked)).toStrictEqual(674 byId(ok.minted.map(({ id, repo }) => ({ id, repo })))675 );676 })677 );678679 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 });684685 const { exit, lines } = yield* withLogs(lander.land(landMerge));686687 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 );709710 it.effect("appear in no result, refusal or log line", () =>711 Effect.gen(function* () {712 const ok = yield* world();713714 const refusing = yield* world({715 script: {716 ...landerScript,717 land: [Result.fail(new RepoBusy({}))],718 merge: [Result.fail(stale)],719 },720 });721722 const broken = yield* Effect.forEach(breakages, ({ merge }) =>723 world({ binding: (sandbox) => ({ ...sandbox, merge }) })724 );725726 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 );736737 const minted = [ok, refusing, ...broken].flatMap((each) => each.minted);738739 expect(minted).toHaveLength(24);740 expect(leaked(JSON.stringify(exit), minted)).toStrictEqual([]);741 expect(leaked(JSON.stringify(lines), minted)).toStrictEqual([]);742 })743 );744});