Skip to content
Myr

layer-gateway.test.ts

This file

Path

apps/platform/test/visibility/layer-gateway.test.ts

603 lines · 16.7 KiB · TypeScript

Last changed by

Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8

History of this file

Take it

1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { RefName, RepoName } from "@repo/artifacts/repo-host";4import type { RepoHost } from "@repo/artifacts/repo-host";5import { Brand } from "@repo/brand";6import { CheckAt } from "@repo/checks/check-runner";7import { Exchange } from "@repo/git/upstream";8import {9  noPlan,10  noVisibility,11  ProjectVisibility,12} from "@repo/project/visibility-port";13import type { VisibilityPort } from "@repo/project/visibility-port";14import {15  keyOf,16  AskId,17  Handle,18  LaneName,19  LayerName,20  ProjectName,21  RepoPath,22} from "@repo/protocol/ids";23import type { CommitSha } from "@repo/protocol/ids";24import { Principal } from "@repo/protocol/principal";25import { PrivatePathInPublicTree } from "@repo/protocol/refusal";26import { explain } from "@repo/protocol/render";27import { git } from "@repo/testkit/git";28import type { Ran } from "@repo/testkit/git";29import { LayerRepos } from "@repo/visibility/layer-repos";30import {31  Array,32  Cause,33  Effect,34  Exit,35  FileSystem,36  Layer,37  Option,38  Redacted,39} from "effect";4041import { LayerGate, noLayers } from "../../src/layer-gate.ts";42import { decodeEnv } from "../../src/platform.ts";43import { workerPorts } from "../../src/ports.ts";44import { LayerGateLive } from "../../src/visibility/layers.ts";45import { fakeEnv } from "../fake-env.ts";46import { coreLoopWorld } from "../world.ts";4748const project = ProjectName.make("ines-v/datekit");4950const maintainers = LayerName.make("maintainers");5152const layerRepo = RepoName.make(`${keyOf(project)}--${maintainers}`);5354const sealed = "checks/held-back/export/escape.test.ts";5556const mainRef = "refs/heads/main";5758const tokens = {59  bram: "bram-layer-gateway-token-0123456789abcdef",60  "ines-v": "ines-v-layer-gateway-token-0123456789abcdef",61  okonkwo: "okonkwo-layer-gateway-token-0123456789abcdef",62} as const;6364const keepers: ReadonlySet<string> = new Set(["ines-v", "okonkwo"]);6566const keeps = (who: Principal) =>67  Principal.guards.Person(who) && keepers.has(who.handle);6869interface Heard {70  readonly asks: LayerName[];71  readonly reads: {72    readonly handle: Handle;73    readonly layer: LayerName;74    readonly sha: Option.Option<CommitSha>;75  }[];76  readonly pushes: {77    readonly head: CommitSha;78    readonly layer: LayerName;79    readonly pusher: Handle;80  }[];81}8283const visibilityHeard = (heard: Heard): VisibilityPort => ({84  ...noVisibility,85  access: (who, layer) => {86    heard.asks.push(layer);8788    return layer === maintainers89      ? Option.some(keeps(who) ? "write" : "none")90      : Option.none();91  },92  layerPaths: () => Effect.succeed(new Set([RepoPath.make(sealed)])),93  onLayerPush: ({ head, layer, pusher }) =>94    Effect.sync(() => {95      heard.pushes.push({ head, layer, pusher });9697      return noPlan;98    }),99  onPolicy: () =>100    Effect.succeed({101      effects: [],102      writes: { layers: [{ name: maintainers, repo: layerRepo }] },103    }),104  readableLayers: (who) => new Set(keeps(who) ? [maintainers] : []),105  recordRead: ({ handle, layer, sha }) => {106    heard.reads.push({ handle, layer, sha });107108    return {};109  },110});111112const minting = (113  host: RepoHost["Service"],114  minted: string[]115): RepoHost["Service"] => ({116  ...host,117  mintToken: (name, scope, ttl) =>118    Effect.tap(host.mintToken(name, scope, ttl), (token) =>119      Effect.sync(() => {120        minted.push(Redacted.value(token.secret));121      })122    ),123});124125const sdk = `${Brand.cliPackage}/rules`;126127const start = {128  [`${Brand.configDir}/project.ts`]: [129    `import { kinds, project } from "${sdk}";`,130    ``,131    `export default project({`,132    `  kinds: [kinds.fix],`,133    `  run: { checks: {}, test: "bun test {path}" },`,134    `});`,135    ``,136  ].join("\n"),137  [`${Brand.configDir}/vouched.td`]: "bram\nines-v\n",138  "README.md": "datekit: dates, exported\n",139  "package.json": '{ "name": "ines-v/datekit", "private": true }\n',140  "src/export.ts": "export const toIso = (date: Date) => date.toISOString();\n",141};142143const askFiles = (ask: AskId) =>144  Array.make(145    {146      content: [147        `import { kinds, territory } from "${sdk}";`,148        ``,149        `export default kinds.fix.ask({`,150        `  path: "test/${ask}.test.ts",`,151        `  territory: territory.paths("src/**", "checks/**"),`,152        `  want: "toIso keeps the offset it was given",`,153        `});`,154        ``,155      ].join("\n"),156      path: RepoPath.make(`${Brand.configDir}/asks/${ask}.ask.ts`),157    },158    {159      content: [160        `import { expect, it } from "bun:test";`,161        `import { toIso } from "../src/export.ts";`,162        ``,163        `it("keeps the offset", () => {`,164        `  expect(toIso(new Date(0))).toContain("+00:00");`,165        `});`,166        ``,167      ].join("\n"),168      path: RepoPath.make(`test/${ask}.test.ts`),169    }170  );171172const remoteLines = (stderr: string) =>173  stderr174    .split("\n")175    .filter((line) => line.startsWith("remote: "))176    .map((line) => line.trimEnd());177178const rendered = (refusals: Parameters<typeof explain>[0]) =>179  explain(refusals).map((line) => `remote: ${line}`);180181const escaping = {182  [sealed]: "it('escapes', () => {});\n",183  "src/fix.ts": "export const fix = true;\n",184};185186const layerWorld = Effect.gen(function* () {187  const fs = yield* FileSystem.FileSystem;188  const heard: Heard = { asks: [], pushes: [], reads: [] };189  const minted: string[] = [];190  const outputs: Ran[] = [];191  const stores: RepoHost["Service"][] = [];192193  const world = yield* coreLoopWorld({194    plugIn: (store) => {195      stores.push(store);196197      return {198        project: Layer.succeed(ProjectVisibility, visibilityHeard(heard)),199        worker: LayerGateLive.pipe(200          Layer.provide(201            Layer.succeed(LayerRepos, LayerRepos.of(minting(store, minted)))202          )203        ),204      };205    },206    sessions: Object.fromEntries(207      Object.entries(tokens).map(([handle, token]) => [token, handle])208    ),209  });210211  const layers = yield* Effect.fromNullishOr(stores[0]);212  const ines = yield* world.person("ines-v");213  const bram = yield* world.person("bram");214215  const kept = <R>(ran: Effect.Effect<Ran, never, R>) =>216    Effect.tap(ran, (output) =>217      Effect.sync(() => {218        outputs.push(output);219      })220    );221222  const made = yield* ines.rpc.initProject({ project });223  const home = yield* ines.git.clone(made.remote);224225  yield* ines.git.commit(home, "Start datekit", start);226  yield* kept(ines.git.push(home));227228  yield* layers.create(layerRepo);229230  const seed = yield* fs.makeTempDirectoryScoped();231232  yield* ines.git.ok(seed, "init", "--quiet", "--initial-branch=main");233234  const layered = yield* ines.git.commit(seed, "Seal the export check", {235    [sealed]: "it('keeps the offset', () => {});\n",236  });237238  const remote = yield* layers.remote(layerRepo);239240  yield* ines.git.ok(seed, "push", "--quiet", remote, "HEAD:main");241242  return {243    bram,244    heard,245    ines,246    kept,247    layered,248    layers,249    minted,250    outputs,251    remote,252    seed,253    world,254  };255});256257describe("a project's layer repos, through the gateway", () => {258  it.live(259    "its keepers clone and push to it, anyone else is turned away, each read is logged, and a fork push cannot carry its paths",260    () =>261      Effect.gen(function* () {262        const fs = yield* FileSystem.FileSystem;263264        const {265          bram,266          heard,267          ines,268          kept,269          layered,270          layers,271          minted,272          outputs,273          world,274        } = yield* layerWorld;275276        const layerUrl = `${world.origin}/${project}--maintainers.git`;277278        const ask = (repo: string, token?: string) =>279          world.fetch(280            new Request(281              `${world.origin}/${repo}.git/info/refs?service=git-upload-pack`,282              token === undefined283                ? {}284                : {285                    headers: {286                      authorization: `Basic ${btoa(`x:${token}`)}`,287                    },288                  }289            )290          );291292        const anonymous = yield* ask(`${project}--maintainers`);293        const undeclared = yield* ask(`${project}--secrets`);294295        const undeclaredSignedIn = yield* ask(296          `${project}--secrets`,297          tokens.bram298        );299300        const asksBefore = heard.asks.length;301        const keeper = yield* ask(`${project}--maintainers`, tokens["ines-v"]);302303        expect({304          anonymous: {305            challenge: anonymous.headers.get("www-authenticate"),306            status: anonymous.status,307          },308          keeper: {309            asks: heard.asks.length - asksBefore,310            status: keeper.status,311          },312          undeclared: undeclared.status,313          undeclaredSignedIn: undeclaredSignedIn.status,314        }).toStrictEqual({315          anonymous: { challenge: `Basic realm="${Brand.name}"`, status: 401 },316          keeper: { asks: 1, status: 200 },317          undeclared: 404,318          undeclaredSignedIn: 404,319        });320321        const outside = yield* fs.makeTempDirectoryScoped();322        const clone = `${outside}/ines-v`;323324        const inesClone = yield* kept(325          ines.git.run(outside, "clone", "--quiet", layerUrl, "ines-v")326        );327328        const cloned = yield* ines.git.ok(clone, "rev-parse", "HEAD");329        const file = yield* fs.readFileString(`${clone}/${sealed}`);330        const readsAfterClone = [...heard.reads];331332        const bramClone = yield* kept(333          bram.git.run(outside, "clone", "--quiet", layerUrl, "layer")334        );335336        const nobody = yield* kept(337          git(outside, "clone", "--quiet", layerUrl, "nobody")338        );339340        expect({341          bram: {342            exitCode: bramClone.exitCode,343            remote: remoteLines(bramClone.stderr),344          },345          cloned,346          file,347          ines: inesClone.exitCode,348          nobody: nobody.exitCode,349          reads: readsAfterClone,350          readsAfterRefusals: heard.reads,351        }).toStrictEqual({352          bram: {353            exitCode: 128,354            remote: [`remote: bram may not read ${project}--maintainers`],355          },356          cloned: layered,357          file: "it('keeps the offset', () => {});\n",358          ines: 0,359          nobody: 128,360          reads: [361            {362              handle: Handle.make("ines-v"),363              layer: maintainers,364              sha: Option.some(layered),365            },366          ],367          readsAfterRefusals: readsAfterClone,368        });369370        const next = yield* ines.git.commit(clone, "Seal a second check", {371          "checks/held-back/export/offset.test.ts":372            "it('offsets', () => {});\n",373        });374375        const pushed = yield* kept(ines.git.push(clone));376377        const own = `${outside}/own`;378379        yield* bram.git.ok(380          outside,381          "init",382          "--quiet",383          "--initial-branch=main",384          own385        );386        yield* bram.git.commit(own, "Try the layer", { [sealed]: "it();\n" });387388        const bramPush = yield* kept(389          bram.git.run(own, "push", layerUrl, "HEAD:main")390        );391392        const tips = yield* layers.refs(layerRepo);393394        expect({395          bram: {396            exitCode: bramPush.exitCode,397            remote: remoteLines(bramPush.stderr),398          },399          main: tips.get(RefName.make(mainRef)),400          pushed: pushed.exitCode,401          pushes: heard.pushes,402        }).toStrictEqual({403          bram: {404            exitCode: 128,405            remote: [`remote: bram may not push to ${project}--maintainers`],406          },407          main: next,408          pushed: 0,409          pushes: [410            { head: next, layer: maintainers, pusher: Handle.make("ines-v") },411          ],412        });413414        const asks = [415          AskId.make("keep-offset"),416          AskId.make("keep-zone"),417        ] as const;418419        for (const id of asks) {420          const files = askFiles(id);421422          yield* world.script(423            CheckAt.cases.Commit.make({424              commit: yield* world.composed(project, files),425            }),426            LaneName.make("redThenGreen"),427            ["failed", "failed"]428          );429430          yield* ines.rpc.openAsk({ ask: id, files, project });431        }432433        const [first, second] = asks;434435        const { claim: bramsClaim } = yield* bram.rpc.claim({436          ask: first,437          project,438        });439440        const { claim: inesClaim } = yield* ines.rpc.claim({441          ask: second,442          project,443        });444445        const bramsWork = yield* bram.git.clone(bramsClaim.remote);446447        const bramsHead = yield* bram.git.commit(448          bramsWork,449          "Fix, and copy",450          escaping451        );452453        const bramsAnswer = yield* kept(bram.git.push(bramsWork));454455        const inesWork = yield* ines.git.clone(inesClaim.remote);456457        yield* ines.git.commit(inesWork, "Fix, and copy", escaping);458459        const inesAnswer = yield* kept(ines.git.push(inesWork));460461        expect({462          bram: {463            exitCode: bramsAnswer.exitCode,464            fork: yield* bram.git.ok(bramsWork, "ls-remote", "origin", mainRef),465            remote: remoteLines(bramsAnswer.stderr),466          },467          ines: {468            exitCode: inesAnswer.exitCode,469            remote: remoteLines(inesAnswer.stderr),470          },471        }).toStrictEqual({472          bram: {473            exitCode: 1,474            fork: `${bramsHead}\t${mainRef}`,475            remote: rendered([476              new PrivatePathInPublicTree({477                paths: [RepoPath.make(sealed), RepoPath.make("src/fix.ts")],478              }),479            ]),480          },481          ines: {482            exitCode: 1,483            remote: rendered([484              new PrivatePathInPublicTree({ paths: [RepoPath.make(sealed)] }),485            ]),486          },487        });488489        const logged = yield* world.logged;490491        const said = [492          ...outputs.flatMap(({ stderr, stdout }) => [stderr, stdout]),493          ...logged.flatMap(({ annotations, message }) => [494            message,495            ...annotations.values(),496          ]),497        ].join("\n");498499        expect({500          leaked: minted.filter((secret) => said.includes(secret)),501          minted: minted.length > 0,502        }).toStrictEqual({ leaked: [], minted: true });503      }).pipe(Effect.provide(NodeServices.layer)),504    60_000505  );506  it.live(507    "a clone over protocol v0, and one whose request git compresses, each log one read naming a commit it wanted",508    () =>509      Effect.gen(function* () {510        const { heard, ines, layered, remote, seed, world } = yield* layerWorld;511        const layerUrl = `${world.origin}/${project}--maintainers.git`;512513        // Forty more branches: a clone that wants them all sends git's514        const branches = Array.makeBy(40, (n) => `refs/heads/area-${n}`);515516        yield* ines.git.ok(517          seed,518          "push",519          "--quiet",520          remote,521          ...branches.map((ref) => `HEAD:${ref}`)522        );523524        const v0 = yield* ines.git.ok(525          seed,526          "-c",527          "protocol.version=0",528          "clone",529          "--quiet",530          layerUrl,531          "v0"532        );533534        const afterV0 = [...heard.reads];535536        yield* ines.git.ok(537          seed,538          "clone",539          "--quiet",540          "--no-single-branch",541          layerUrl,542          "every-branch"543        );544545        expect({546          afterV0,547          v0,548          wide: heard.reads.slice(afterV0.length),549        }).toStrictEqual({550          afterV0: [551            {552              handle: Handle.make("ines-v"),553              layer: maintainers,554              sha: Option.some(layered),555            },556          ],557          v0: "",558          wide: [559            {560              handle: Handle.make("ines-v"),561              layer: maintainers,562              sha: Option.some(layered),563            },564          ],565        });566      }).pipe(Effect.provide(NodeServices.layer)),567    60_000568  );569570  it.effect("the stage's ports carry the live gate, not the default", () =>571    Effect.gen(function* () {572      const config = yield* decodeEnv(fakeEnv()).pipe(Effect.orDie);573574      const gate = yield* LayerGate.use(Effect.succeed).pipe(575        Effect.provide(workerPorts(config))576      );577578      expect(gate === noLayers).toBeFalsy();579    })580  );581582  it.effect(583    "the stage's layer gate asks the private namespace for a layer repo, never the public one",584    () =>585      Effect.gen(function* () {586        const config = yield* decodeEnv(fakeEnv()).pipe(Effect.orDie);587588        const exit = yield* LayerGate.use((gate) =>589          gate.upstream.exchange(590            layerRepo,591            Exchange.Advertise({592              headers: new Headers(),593              service: "git-upload-pack",594            })595          )596        ).pipe(Effect.provide(workerPorts(config)), Effect.exit);597598        expect(Exit.isFailure(exit) ? Cause.pretty(exit.cause) : "").toContain(599          "a test touched ARTIFACTS_PRIVATE."600        );601      })602  );603});