env-injection.test.ts
This file
Path
apps/sandbox/test/env-injection.test.ts
670 lines · 20.0 KiB · TypeScript
Last changed by
Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
History of this fileTake it
1import { describe, expect, it } from "@effect/vitest";2import { CheckAt } from "@repo/checks/check-runner";3import type { CheckJob } from "@repo/checks/check-runner";4import { CheckExit, CheckWire } from "@repo/checks/check-runner/wire";5import { Command } from "@repo/protocol/domain/common";6import { RunBlock } from "@repo/protocol/domain/run";7import {8 AreaName,9 CommitSha,10 EnvKey,11 LaneName,12 ProjectName,13 RepoName,14 RepoPath,15 SuiteRoot,16} from "@repo/protocol/ids";17import { untouchable } from "@repo/testkit/untouchable";18import { Effect, Exit, Option, Redacted, Schema } from "effect";19import { vi } from "vitest";2021import { Checker } from "../src/checker.ts";22import { envPlanOf } from "../src/checker/env.ts";23import { CLONE_HOST, REGISTRIES } from "../src/checker/network.ts";24import { check } from "../src/checker/run.ts";25import { EnvGateway } from "../src/env-gateway.ts";26import type { EnvGatewayProps } from "../src/env-gateway.ts";27import { fakeChecker, fakeContainer } from "./fake-box.ts";28import type { Call } from "./fake-box.ts";29import { fakeEnv } from "./fake-env.ts";3031const SETUP = "bun install --frozen-lockfile";3233const UNIT = "bun test";3435const run = RunBlock.make({36 checks: { [LaneName.make("unit")]: Command.make(UNIT) },37 setup: Command.make(SETUP),38 test: Command.make("bun test {path}"),39});4041const SENTRY = EnvKey.make("SENTRY_AUTH_TOKEN");4243const PLACEHOLDER = "__SENTRY_AUTH_TOKEN_PLACEHOLDER__";4445const VALUE = "sntrys_5f0c1d2e3b4a69788796a5b4c3d2e1f0";4647const sentryRule = {48 block: false,49 host: "sentry.io",50 key: SENTRY,51 path: "/api/**",52 placeholder: PLACEHOLDER,53};5455const jobWith = (env: Partial<CheckJob> = {}): CheckWire => ({56 clone: {57 token: Redacted.make("art_v1_read-only"),58 url: "https://0123abcd.artifacts.cloudflare.net/git/public/datekit.git",59 },60 job: {61 at: CheckAt.cases.Commit.make({ commit: CommitSha.make("a".repeat(40)) }),62 lanes: [{ command: UNIT, lane: LaneName.make("unit") }],63 placeholders: [{ key: SENTRY, placeholder: PLACEHOLDER }],64 project: ProjectName.make("oscabriel/datekit"),65 proxies: [sentryRule],66 repo: RepoName.make("datekit"),67 run,68 ...env,69 },70});7172const envsOf = (calls: readonly Call[], command: string) =>73 calls.flatMap((call) =>74 call.kind === "exec" && call.argv[0] === "sh" && call.argv[2] === command75 ? [call.options.env ?? {}]76 : []77 );7879const checked = (wire: CheckWire) =>80 Effect.gen(function* () {81 const fake = fakeChecker();8283 const outcome = yield* Effect.exit(84 check(wire).pipe(Effect.provide(fake.layer))85 );8687 return { calls: fake.calls, outcome };88 });8990const landedJob = () =>91 jobWith({92 landed: true,93 values: [{ key: SENTRY, value: Redacted.make(VALUE) }],94 });9596describe("the Checker's env", () => {97 it.effect(98 "sets each placeholder in the env of setup and of every lane, and no value, even in a landed job",99 () =>100 Effect.gen(function* () {101 for (const wire of [jobWith(), landedJob()]) {102 const { calls } = yield* checked(wire);103104 const envs = [...envsOf(calls, SETUP), ...envsOf(calls, UNIT)];105106 expect(envs).toHaveLength(2);107108 for (const env of envs) {109 expect(env[SENTRY]).toBe(PLACEHOLDER);110 expect(Object.values(env)).not.toContain(VALUE);111 }112 }113 })114 );115116 it.effect(117 "registers one intercept per proxied host, once egress is off and before any lane runs",118 () =>119 Effect.gen(function* () {120 const { calls } = yield* checked(jobWith());121122 const egressOff = calls.findIndex(123 (call) => call.kind === "allow" && call.hosts.length === 0124 );125126 const firstLane = calls.findIndex(127 (call) =>128 call.kind === "exec" &&129 call.argv[0] === "sh" &&130 call.argv[2] === UNIT131 );132133 const intercepts = calls.flatMap((call, at) =>134 call.kind === "intercept" ? [{ at, host: call.host }] : []135 );136137 expect(intercepts.map(({ host }) => host)).toStrictEqual(["sentry.io"]);138 expect(egressOff).toBeGreaterThan(-1);139 expect(intercepts[0]?.at).toBeGreaterThan(egressOff);140 expect(intercepts[0]?.at).toBeLessThan(firstLane);141 })142 );143144 it.effect(145 "intercepts HTTPS hosts only: an http:// host is left out, with the reason logged",146 () =>147 Effect.gen(function* () {148 const { calls } = yield* checked(149 jobWith({150 proxies: [151 sentryRule,152 { ...sentryRule, host: "http://plain.example.com" },153 { ...sentryRule, host: "https://api.example.com" },154 ],155 })156 );157158 expect(159 calls.flatMap((call) =>160 call.kind === "intercept" ? [call.host] : []161 )162 ).toStrictEqual(["sentry.io", "api.example.com"]);163164 const reasons = calls.flatMap((call) =>165 call.kind === "log" &&166 call.annotations.host === "http://plain.example.com"167 ? [call.annotations.reason ?? ""]168 : []169 );170171 expect(reasons).toHaveLength(1);172 expect(reasons[0]).toContain("HTTPS only");173 })174 );175176 it.effect(177 "opens no env route beside a sealed suite: its checks run with the network off, seeing the placeholders",178 () =>179 Effect.gen(function* () {180 const sealedCheck = "bun test checks/held-back/parser/week-54.test.ts";181182 const { calls } = yield* checked(183 jobWith({184 heldBack: {185 areas: [AreaName.make("parser")],186 at: CommitSha.make("b".repeat(40)),187 files: [188 {189 area: AreaName.make("parser"),190 content: new TextEncoder().encode("test('x', () => {});\n"),191 path: RepoPath.make(192 "checks/held-back/parser/week-54.test.ts"193 ),194 },195 ],196 runs: [197 {198 area: AreaName.make("parser"),199 command: sealedCheck,200 path: RepoPath.make(201 "checks/held-back/parser/week-54.test.ts"202 ),203 },204 ],205 suite: SuiteRoot.make(`sha256:${"5e".repeat(32)}`),206 },207 lanes: [],208 })209 );210211 expect(calls.filter((call) => call.kind === "intercept")).toStrictEqual(212 []213 );214 expect(215 calls.flatMap((call) =>216 call.kind === "exec" && call.argv[2] === sealedCheck217 ? [{ network: call.network, token: call.options.env?.[SENTRY] }]218 : []219 )220 ).toStrictEqual([{ network: [], token: PLACEHOLDER }]);221 expect(222 calls.flatMap((call) =>223 call.kind === "log" && call.annotations.host === "sentry.io"224 ? [call.annotations.reason]225 : []226 )227 ).toStrictEqual(["a sealed suite runs with the network off"]);228 })229 );230});231232const upstream = (answer: (request: Request) => Response) =>233 Effect.acquireRelease(234 Effect.sync(() => {235 const sent: Request[] = [];236237 vi.stubGlobal("fetch", (request: Request) => {238 sent.push(request);239240 return Promise.resolve(answer(request));241 });242243 return sent;244 }),245 () => Effect.sync(() => vi.unstubAllGlobals())246 );247248const gatewayFor = (props: Partial<EnvGatewayProps> = {}) =>249 new EnvGateway(250 untouchable<ExecutionContext<EnvGatewayProps>>("ctx", {251 props: { rules: [sentryRule], values: [], ...props },252 }),253 fakeEnv()254 );255256const landedValues = [{ key: SENTRY, placeholder: PLACEHOLDER, value: VALUE }];257258const releaseRequest = () =>259 new Request("https://sentry.io/api/0/releases/", {260 body: JSON.stringify({ version: "1.4.0" }),261 headers: {262 authorization: `Bearer ${PLACEHOLDER}`,263 "content-type": "application/json",264 },265 method: "POST",266 });267268const readSent = (request: Request) =>269 Effect.promise(() => request.text()).pipe(270 Effect.map((body) => ({271 body,272 headers: Object.fromEntries(request.headers),273 method: request.method,274 url: request.url,275 }))276 );277278const fetched = (gateway: EnvGateway, request: Request) =>279 Effect.promise(() => gateway.fetch(request)).pipe(280 Effect.flatMap((response) =>281 Effect.map(282 Effect.promise(() => response.text()),283 (text) => ({284 status: response.status,285 text,286 })287 )288 )289 );290291describe("the env gateway", () => {292 it.effect(293 "for an unlanded job, sends a request its rules allow on with the placeholder unchanged, adding no header",294 () =>295 Effect.gen(function* () {296 const sent = yield* upstream(() => new Response("{}"));297298 const answered = yield* fetched(gatewayFor(), releaseRequest());299300 expect(answered.status).toBe(200);301 expect(yield* Effect.forEach(sent, readSent)).toStrictEqual([302 {303 body: '{"version":"1.4.0"}',304 headers: {305 authorization: `Bearer ${PLACEHOLDER}`,306 "content-type": "application/json",307 },308 method: "POST",309 url: "https://sentry.io/api/0/releases/",310 },311 ]);312 })313 );314315 it.effect(316 "answers 403 outside the rules' path or method, to a block rule, and to plain HTTP, sending nothing on",317 () =>318 Effect.gen(function* () {319 const sent = yield* upstream(() => new Response("{}"));320321 const statuses = yield* Effect.forEach(322 [323 [gatewayFor(), new Request("https://sentry.io/other")],324 [325 gatewayFor({ rules: [{ ...sentryRule, method: "GET" }] }),326 releaseRequest(),327 ],328 [329 gatewayFor({ rules: [{ ...sentryRule, block: true }] }),330 releaseRequest(),331 ],332 [333 gatewayFor({334 rules: [sentryRule, { ...sentryRule, block: true }],335 values: landedValues,336 }),337 releaseRequest(),338 ],339 [gatewayFor(), new Request("http://sentry.io/api/0/releases/")],340 [gatewayFor(), new Request("https://other.example.com/api/x")],341 ] as const,342 ([gateway, request]) =>343 Effect.map(fetched(gateway, request), ({ status }) => status)344 );345346 expect(statuses).toStrictEqual([403, 403, 403, 403, 403, 403]);347 expect(sent).toStrictEqual([]);348 })349 );350351 it.effect(352 "for a landed job, swaps the placeholder in the headers for the value, and scrubs the value from a small JSON answer",353 () =>354 Effect.gen(function* () {355 const sent = yield* upstream((request) =>356 Response.json({ echoed: request.headers.get("authorization") })357 );358359 const answered = yield* fetched(360 gatewayFor({ values: landedValues }),361 releaseRequest()362 );363364 expect(365 (yield* Effect.forEach(sent, readSent)).map(({ headers }) => headers)366 ).toStrictEqual([367 {368 authorization: `Bearer ${VALUE}`,369 "content-type": "application/json",370 },371 ]);372 expect(answered).toStrictEqual({373 status: 200,374 text: JSON.stringify({ echoed: `Bearer ${PLACEHOLDER}` }),375 });376 })377 );378379 it.effect(380 "scrubs a value that a streamed text answer splits across chunks, and leaves a binary answer as it is",381 () =>382 Effect.gen(function* () {383 const cut = 12;384 const bytes = new Uint8Array([0, 1, 2, 255]);385386 yield* upstream((request) =>387 request.method === "GET"388 ? new Response(bytes, {389 headers: { "content-type": "application/octet-stream" },390 })391 : new Response(392 new ReadableStream({393 start: (controller) => {394 const encoder = new TextEncoder();395396 controller.enqueue(397 encoder.encode(`{"token":"${VALUE.slice(0, cut)}`)398 );399 controller.enqueue(400 encoder.encode(`${VALUE.slice(cut)}","ok":true}`)401 );402 controller.close();403 },404 }),405 { headers: { "content-type": "application/json" } }406 )407 );408409 const gateway = gatewayFor({410 rules: [{ ...sentryRule, method: "GET, POST" }],411 values: landedValues,412 });413414 const streamed = yield* fetched(gateway, releaseRequest());415416 const binary = yield* Effect.flatMap(417 Effect.promise(() =>418 gateway.fetch(new Request("https://sentry.io/api/0/blob"))419 ),420 (response) => Effect.promise(() => response.arrayBuffer())421 );422423 expect(streamed).toStrictEqual({424 status: 200,425 text: `{"token":"${PLACEHOLDER}","ok":true}`,426 });427 expect(new Uint8Array(binary)).toStrictEqual(bytes);428 })429 );430431 it.effect(432 "refuses a request two rules match with one placeholder for two keys",433 () =>434 Effect.gen(function* () {435 const sent = yield* upstream(() => new Response("{}"));436437 const answered = yield* fetched(438 gatewayFor({439 rules: [440 sentryRule,441 { ...sentryRule, key: EnvKey.make("SENTRY_ORG_TOKEN") },442 ],443 values: landedValues,444 }),445 releaseRequest()446 );447448 expect(answered.status).toBe(403);449 expect(sent).toStrictEqual([]);450 })451 );452453 it.effect(454 "scrubs a value that holds another whole, leaving no part of it in the response",455 () =>456 Effect.gen(function* () {457 const password = "hunter2-0123456789abcdef";458 const url = `postgres://ci:${password}@db.example.com/app`;459460 yield* upstream(() => Response.json({ connected: url }));461462 const answered = yield* fetched(463 gatewayFor({464 values: [465 {466 key: EnvKey.make("DB_PASSWORD"),467 placeholder: "__DB_PASSWORD_PLACEHOLDER__",468 value: password,469 },470 {471 key: EnvKey.make("DATABASE_URL"),472 placeholder: "__DATABASE_URL_PLACEHOLDER__",473 value: url,474 },475 ],476 }),477 releaseRequest()478 );479480 expect(answered).toStrictEqual({481 status: 200,482 text: JSON.stringify({ connected: "__DATABASE_URL_PLACEHOLDER__" }),483 });484 })485 );486});487488const inContainer = (wire: CheckWire) =>489 Effect.gen(function* () {490 const box = fakeContainer();491492 const index = untouchable<DurableObjectStub<Checker>>("index", {493 forgetSnapshot: () => Promise.resolve(),494 keepSnapshot: () => Promise.resolve(),495 snapshotOf: () => Promise.resolve(null),496 });497498 const checker = new Checker(499 untouchable<DurableObjectState>("ctx", {500 container: box.container,501 exports: {502 ...untouchable<Cloudflare.Exports>("exports"),503 ...box.exports,504 },505 }),506 {507 CHECKER: untouchable<Env["CHECKER"]>("CHECKER", {508 getByName: () => index,509 }),510 LANDER: untouchable("LANDER"),511 }512 );513514 const encoded = yield* Schema.encodeEffect(CheckWire)(wire).pipe(515 Effect.orDie516 );517518 const outcome = yield* Effect.flatMap(519 Effect.promise(() => checker.check(encoded)),520 Schema.decodeEffect(CheckExit)521 );522523 return { calls: box.calls, outcome };524 });525526describe("the Checker's container", () => {527 it.effect(528 "intercepts each proxied host ahead of the catch-all, with the egress gateway until egress is off and the env gateway after",529 () =>530 Effect.gen(function* () {531 const { calls, outcome } = yield* inContainer(landedJob());532 const registries = `egress [${REGISTRIES.join(" ")}]`;533534 expect(Exit.isSuccess(outcome)).toBeTruthy();535 expect(536 calls.flatMap((call) =>537 call.kind === "intercept" && call.target !== CLONE_HOST538 ? [`${call.target} → ${call.to}`]539 : []540 )541 ).toStrictEqual([542 "sentry.io → egress []",543 "* → egress []",544 "http:* → egress []",545 `sentry.io → ${registries}`,546 `* → ${registries}`,547 `http:* → ${registries}`,548 "sentry.io → egress []",549 "* → egress []",550 "http:* → egress []",551 "sentry.io → env [sentry.io] 1 values",552 "* → egress []",553 "http:* → egress []",554 ]);555 })556 );557558 it.effect(559 "for a landed job, puts no value in the container: not in a command, its env, or a gateway's description of its props",560 () =>561 Effect.gen(function* () {562 const { calls } = yield* inContainer(landedJob());563564 const lanes = calls.flatMap((call) =>565 call.kind === "exec" && call.argv[2] === UNIT ? [call.env] : []566 );567568 expect(lanes.map((env) => env[SENTRY])).toStrictEqual([PLACEHOLDER]);569 expect(JSON.stringify(calls)).not.toContain(VALUE);570 })571 );572});573574describe("a check job's env part", () => {575 it("intercepts at most 60 proxy hosts, under the container's 64 intercept targets, and logs the rest", () => {576 const hosts = Array.from({ length: 61 }, (_, n) => `api${n}.example.com`);577578 const plan = envPlanOf(579 jobWith({580 proxies: hosts.map((host) => ({ ...sentryRule, host })),581 }).job582 );583584 expect({585 intercepted: Option.map(plan.route, (route) => route.hosts.length),586 skipped: plan.skipped,587 }).toStrictEqual({588 intercepted: Option.some(60),589 skipped: [590 {591 host: "api60.example.com",592 reason:593 "the container intercepts at most 60 proxy hosts beside the clone route and the catch-all",594 },595 ],596 });597 });598599 it.effect(600 "carries values only for landed code: an unlanded job with one neither encodes nor decodes, and the error holds no value",601 () =>602 Effect.gen(function* () {603 const unlanded = jobWith({604 values: [{ key: SENTRY, value: Redacted.make(VALUE) }],605 });606607 const encoded = yield* Schema.encodeEffect(CheckWire)(landedJob()).pipe(608 Effect.orDie609 );610611 const encoding = yield* Effect.flip(612 Schema.encodeEffect(CheckWire)(unlanded)613 );614615 const decoding = yield* Effect.flip(616 Schema.decodeEffect(CheckWire)({617 ...encoded,618 job: { ...encoded.job, landed: false },619 })620 );621622 for (const failure of [encoding, decoding]) {623 expect(failure.message).toContain(624 "only a job of landed code carries values"625 );626 expect(failure.message).not.toContain(VALUE);627 }628 })629 );630631 it.effect(632 "hands the env gateway a landed job's values for its proxied keys alone",633 () =>634 Effect.gen(function* () {635 const { calls } = yield* checked(636 jobWith({637 landed: true,638 values: [639 { key: SENTRY, value: Redacted.make(VALUE) },640 {641 key: EnvKey.make("DATEKIT_SIGNING_KEY"),642 value: Redacted.make("unproxied-signing-key-0123456789"),643 },644 ],645 })646 );647648 expect(calls.filter((call) => call.kind === "intercept")).toStrictEqual(649 [{ host: "sentry.io", kind: "intercept", values: 1 }]650 );651 expect(JSON.stringify(calls)).not.toContain(VALUE);652 })653 );654655 it.effect(656 "hands the env gateway no value for a job that is not landed, even one that reached the Checker carrying values",657 () =>658 Effect.gen(function* () {659 // Past the codec, which refuses such a job: the Checker's own660 // filter still keeps the value from the gateway.661 const { calls } = yield* checked(662 jobWith({ values: [{ key: SENTRY, value: Redacted.make(VALUE) }] })663 );664665 expect(calls.filter((call) => call.kind === "intercept")).toStrictEqual(666 [{ host: "sentry.io", kind: "intercept", values: 0 }]667 );668 })669 );670});