Skip to content
Myr

env-set-live.test.ts

This file

Path

apps/cli/test/local/env-set-live.test.ts

837 lines · 23.7 KiB · TypeScript

Last changed by

Merge observability into mainoscabrielbefore adoption1985111

History of this file

Take it

1import { NodeServices } from "@effect/platform-node";2import { expect, layer } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { CheckJob } from "@repo/checks/check-runner";5import { Client } from "@repo/protocol/contracts";6import { EnvSchemaView } from "@repo/protocol/domain/env";7import { Ledger, LedgerEntry } from "@repo/protocol/domain/visibility";8import { Envelope } from "@repo/protocol/envelope";9import {10  AskId,11  EnvKey,12  Handle,13  ProjectName,14  keyOf,15  RepoPath,16} from "@repo/protocol/ids";17import {18  NotDecider,19  NotSensitive,20  ValueTooShort,21} from "@repo/protocol/refusal";22import { explain } from "@repo/protocol/render";23import { git, gitOk, spawn } from "@repo/testkit/git";24import {25  Array,26  Cause,27  Context,28  DateTime,29  Deferred,30  Effect,31  Exit,32  FileSystem,33  Layer,34  Logger,35  Option,36  Path,37  Redacted,38  Ref,39  References,40  Runtime,41  Schema,42  Stdio,43  Stream,44  Terminal,45} from "effect";46import { CliOutput } from "effect/cli";47import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";48import { TestConsole } from "effect/testing";4950import { Credentials } from "../../src/credentials.ts";51import { program } from "../../src/main.ts";52import { OutputLive } from "../../src/output.ts";53import { policyFor } from "../../src/policy.ts";54import { RemoteClient } from "../../src/remote.ts";5556const WORLD = "apps/platform/test/visibility/serve-cartridge-world.ts";5758const project = ProjectName.make("ines-v/datekit");5960const token = EnvKey.make("SENTRY_AUTH_TOKEN");6162const value = "sk_test_0123456789abcdef";6364// Under the 12 characters a value needs.65const short = "tooshort";6667const ask = AskId.make("parse-iso-week");6869interface Person {70  readonly handle: Handle;71  readonly token: string;72}7374const ines: Person = {75  handle: Handle.make("ines-v"),76  token: "ines-v-env-set-live-token-0123456789abcdef",77};7879const bram: Person = {80  handle: Handle.make("bram"),81  token: "bram-env-set-live-token-0123456789abcdefgh",82};8384const seeded = (file: string) =>85  [86    ".env.schema",87    `${Brand.configDir}/project.ts`,88    `${Brand.configDir}/vouched.td`,89    "package.json",90    "tsconfig.json",91  ].includes(file) ||92  /^src\/[^/]+\.ts$/u.test(file) ||93  /^test\/[^/]+\.test\.ts$/u.test(file);9495const askFiles = [96  `${Brand.configDir}/asks/${ask}.ask.ts`,97  `test/asks/${ask}.test.ts`,98] as const;99100const Serving = Schema.fromJsonString(101  Schema.Struct({ kept: Schema.String, origin: Schema.String })102);103104const decodeServing = Schema.decodeUnknownOption(Serving);105106interface Served {107  readonly origin: string;108  readonly kept: string;109  readonly printed: Effect.Effect<string>;110}111112// Both streams are drained, so the process never blocks on a full pipe.113const servedWorld = (root: string) =>114  Effect.gen(function* () {115    const child = yield* spawn("bun", [WORLD], {116      cwd: root,117      env: {118        WORLD_SESSIONS: JSON.stringify({119          [ines.token]: ines.handle,120          [bram.token]: bram.handle,121        }),122      },123    });124125    const printed = yield* Ref.make("");126    const serving = yield* Deferred.make<typeof Serving.Type>();127128    const keep = (text: string) => Ref.update(printed, (all) => all + text);129130    yield* Stream.decodeText(child.stderr).pipe(131      Stream.runForEach(keep),132      Effect.ignore,133      Effect.forkScoped134    );135136    yield* Stream.splitLines(Stream.decodeText(child.stdout)).pipe(137      Stream.runForEach((line) =>138        Effect.andThen(139          keep(`${line}\n`),140          Option.match(decodeServing(line), {141            onNone: () => Effect.void,142            onSome: (where) => Deferred.succeed(serving, where),143          })144        )145      ),146      Effect.ignore,147      Effect.forkScoped148    );149150    const ended = child.exitCode.pipe(151      Effect.ignore,152      Effect.andThen(Ref.get(printed)),153      Effect.flatMap((said) =>154        Effect.die(`the world ended before it served: ${said}`)155      )156    );157158    const where = yield* Effect.raceFirst(Deferred.await(serving), ended).pipe(159      Effect.timeout("60 seconds"),160      Effect.orDie161    );162163    return { ...where, printed: Ref.get(printed) } satisfies Served;164  });165166const Kept = Schema.fromJsonString(167  Schema.Struct({168    bodies: Schema.Array(Schema.String),169    jobs: Schema.Array(Schema.Unknown),170    logged: Schema.Array(Schema.String),171    store: Schema.NullOr(172      Schema.Struct({173        envValues: Schema.Array(174          Schema.Struct({175            key: Schema.String,176            sealed: Schema.Record(Schema.String, Schema.Unknown),177            setAt: Schema.String,178            setBy: Schema.String,179          })180        ),181        events: Schema.Array(Schema.Unknown),182        ledger: Schema.Array(Schema.Unknown),183      })184    ),185  })186);187188const keptBy = (world: Served) =>189  Effect.gen(function* () {190    const http = yield* HttpClient.HttpClient;191    const response = yield* http.get(`${world.kept}/kept?project=${project}`);192193    return yield* Schema.decodeEffect(Kept)(yield* response.text);194  }).pipe(Effect.orDie);195196const settle = (world: Served) =>197  Effect.gen(function* () {198    const http = yield* HttpClient.HttpClient;199    const response = yield* http.post(`${world.kept}/settle`);200201    return response.status === 204202      ? yield* Effect.void203      : yield* Effect.die(`the world did not settle: ${response.status}`);204  }).pipe(Effect.orDie);205206// MCP's 2026-07-28 protocol is stateless: each request names its version207// and client in `_meta` and repeats its method in a header.208const mcpVersion = "2026-07-28";209210const Listed = Schema.fromJsonString(211  Schema.Struct({212    result: Schema.Struct({213      tools: Schema.Array(Schema.Struct({ name: Schema.String })),214    }),215  })216);217218const toolsListed = (world: Served, as: Person) =>219  Effect.gen(function* () {220    const http = yield* HttpClient.HttpClient;221222    const request = HttpClientRequest.post(`${world.origin}/mcp`).pipe(223      HttpClientRequest.setHeaders({224        accept: "application/json, text/event-stream",225        "mcp-method": "tools/list",226        "mcp-protocol-version": mcpVersion,227      }),228      HttpClientRequest.bearerToken(as.token),229      HttpClientRequest.bodyText(230        JSON.stringify({231          id: 1,232          jsonrpc: "2.0",233          method: "tools/list",234          params: {235            _meta: {236              "io.modelcontextprotocol/clientCapabilities": {},237              "io.modelcontextprotocol/clientInfo": {238                name: "test",239                version: "0.0.0",240              },241              "io.modelcontextprotocol/protocolVersion": mcpVersion,242            },243          },244        }),245        "application/json"246      )247    );248249    const response = yield* http.execute(request);250    const text = yield* response.text;251252    // The reply is plain JSON or an event stream; its last message answers.253    const last =254      response.headers["content-type"]?.includes("text/event-stream") === true255        ? (text256            .split("\n")257            .findLast((line) => line.startsWith("data: "))258            ?.slice("data: ".length) ?? "")259        : text;260261    const { result } = yield* Schema.decodeEffect(Listed)(last);262263    return result.tools.map(({ name }) => name);264  }).pipe(Effect.orDie);265266const signedIn = (world: Served, as: Person) =>267  Layer.succeed(Credentials)({268    current: Effect.succeedSome({269      handle: as.handle,270      token: Redacted.make(as.token),271      url: world.origin,272    }),273    forHost: () => Effect.succeedNone,274    put: () => Effect.die("the test stores no profile"),275    remove: () => Effect.die("the test removes no profile"),276  });277278const clientOf = (world: Served, as: Person) =>279  Effect.map(280    Layer.build(RemoteClient.pipe(Layer.provide(signedIn(world, as)))),281    (built) => Context.get(built, Client)282  );283284const gitOf = (helpers: string, as: Person) =>285  Effect.gen(function* () {286    const fs = yield* FileSystem.FileSystem;287    const helper = `${helpers}/${as.handle}`;288289    yield* fs.writeFileString(290      helper,291      [292        "#!/bin/sh",293        'test "$1" = get || exit 0',294        `echo username=${as.handle}`,295        `echo password=${as.token}`,296        "",297      ].join("\n")298    );299300    yield* fs.chmod(helper, 0o700);301302    const helped = ["-c", `credential.helper=${helper}`];303304    return {305      ok: (cwd: string, ...args: string[]) => gitOk(cwd, ...helped, ...args),306      run: (cwd: string, ...args: string[]) => git(cwd, ...helped, ...args),307    };308  });309310interface Ran {311  readonly code: number;312  readonly out: readonly string[];313  readonly err: readonly string[];314  readonly logged: readonly string[];315}316317const noPrompts = Layer.succeed(Terminal.Terminal)(318  Terminal.make({319    columns: Effect.succeed(80),320    display: () => Effect.die("the CLI prompted"),321    readInput: Effect.die("the CLI prompted"),322    readLine: Effect.die("the CLI prompted"),323    rows: Effect.succeed(24),324  })325);326327const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>328  Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));329330const linesOf = (chunks: readonly unknown[]) =>331  chunks.flatMap((chunk) => String(chunk).split("\n"));332333const cli = (334  world: Served,335  as: Person,336  args: readonly string[],337  stdin = ""338): Effect.Effect<Ran> =>339  Effect.suspend(() => {340    const logged: string[] = [];341    const policy = policyFor({ env: {}, isTTY: true });342    const credentials = signedIn(world, as);343344    return Effect.gen(function* () {345      const exit = yield* Effect.exit(program(args));346347      return {348        code: exitCodeOf(exit),349        err: linesOf(yield* TestConsole.errorLines),350        logged,351        out: linesOf(yield* TestConsole.logLines),352      };353    }).pipe(354      Effect.provideService(References.MinimumLogLevel, "All"),355      Effect.provide(356        Layer.mergeAll(357          NodeServices.layer,358          TestConsole.layer,359          CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),360          RemoteClient.pipe(Layer.provide(credentials)),361          credentials,362          policy,363          OutputLive.pipe(Layer.provide(policy)),364          noPrompts,365          Logger.layer([366            Logger.make((options) => {367              logged.push(Logger.formatSimple.log(options));368            }),369          ]),370          // Last, so it stands in for the host's stdio.371          Stdio.layerTest({372            stdin: Stream.make(new TextEncoder().encode(stdin)),373            stdinIsTerminal: Effect.succeed(false),374          })375        )376      )377    );378  });379380class Scenario extends Context.Service<381  Scenario,382  {383    readonly set: Ran;384    readonly byBram: Ran;385    readonly publicItem: Ran;386    readonly tooShort: Ran;387    readonly envView: Ran;388    readonly ledger: Ran;389    readonly answered: { readonly exitCode: number; readonly stderr: string };390    readonly answerJobs: readonly CheckJob[];391    readonly tools: readonly string[];392    readonly kept: typeof Kept.Type;393    readonly printed: string;394  }395>()("test/EnvSetLiveScenario") {}396397// By `CheckJob`'s fields alone, so a job carrying values still decodes and a test refuses it.398const decodeJobs = Schema.decodeUnknownEffect(399  Schema.Array(Schema.Struct(CheckJob.fields))400);401402const ScenarioOnce = Layer.effect(403  Scenario,404  Effect.gen(function* () {405    const fs = yield* FileSystem.FileSystem;406    const path = yield* Path.Path;407408    const root = yield* path.fromFileUrl(409      new URL("../../../../", import.meta.url)410    );411412    const example = path.join(root, "examples", "datekit");413    const home = yield* fs.makeTempDirectoryScoped({ prefix: "env-set-live-" });414    const world = yield* servedWorld(root);415    const helpers = path.join(home, "helpers");416417    yield* fs.makeDirectory(helpers);418419    const inesGit = yield* gitOf(helpers, ines);420    const bramGit = yield* gitOf(helpers, bram);421    const asInes = yield* clientOf(world, ines);422    const asBram = yield* clientOf(world, bram);423424    const made = yield* asInes.initProject({ project });425    const start = path.join(home, "start");426427    const tracked = yield* gitOk(example, "ls-files", "--full-name", ".");428    const prefix = "examples/datekit/";429430    yield* fs.makeDirectory(start);431432    for (const file of tracked433      .split("\n")434      .map((line) => line.slice(prefix.length))) {435      if (seeded(file)) {436        yield* fs.makeDirectory(path.dirname(path.join(start, file)), {437          recursive: true,438        });439        yield* fs.copyFile(path.join(example, file), path.join(start, file));440      }441    }442443    yield* gitOk(start, "init", "--quiet", "--initial-branch=main");444    yield* gitOk(start, "add", "--all");445    yield* gitOk(start, "commit", "--quiet", "--message", "Start datekit");446    yield* inesGit.ok(start, "push", "--quiet", made.remote, "HEAD:main");447448    const setting = (key: string) => [449      "env",450      "set",451      key,452      "--project",453      project,454      "--yes",455    ];456457    const set = yield* cli(world, ines, setting(token), `${value}\n`);458    const byBram = yield* cli(world, bram, setting(token), `${value}\n`);459460    const publicItem = yield* cli(461      world,462      ines,463      setting("APP_ENV"),464      `${value}\n`465    );466467    const tooShort = yield* cli(world, ines, setting(token), `${short}\n`);468469    const envView = yield* cli(world, ines, [470      "env",471      "shape",472      "--project",473      project,474      "--json",475    ]);476477    const ledger = yield* cli(world, ines, [478      "ledger",479      "--project",480      project,481      "--json",482    ]);483484    const files = yield* Effect.forEach(askFiles, (file) =>485      Effect.map(fs.readFileString(path.join(example, file)), (content) => ({486        content,487        path: RepoPath.make(file),488      }))489    );490491    yield* asInes.openAsk({492      ask,493      files: Array.isReadonlyArrayNonEmpty(files)494        ? files495        : yield* Effect.die("the ask has no files"),496      project,497    });498499    const { claim } = yield* asBram.claim({ ask, project });500    const work = path.join(home, "work");501502    yield* bramGit.ok(home, "clone", "--quiet", claim.remote, work);503504    const parse = path.join(work, "src", "parse.ts");505506    yield* fs.writeFileString(507      parse,508      `${yield* fs.readFileString(parse)}// Week dates next.\n`509    );510511    yield* gitOk(512      work,513      "commit",514      "--quiet",515      "--all",516      "--message",517      "Read week dates"518    );519520    const answered = yield* bramGit.run(work, "push", "origin", "HEAD:main");521    const before = (yield* keptBy(world)).jobs.length;522523    yield* settle(world);524525    const tools = yield* toolsListed(world, ines);526    const kept = yield* keptBy(world);527528    return {529      answerJobs: yield* decodeJobs(kept.jobs.slice(before)),530      answered,531      byBram,532      envView,533      kept,534      ledger,535      printed: yield* world.printed,536      publicItem,537      set,538      tooShort,539      tools,540    };541  }).pipe(Effect.orDie)542).pipe(Layer.provide([NodeServices.layer, FetchHttpClient.layer]));543544const decodeEnvelope = <A extends Schema.Top>(data: A) =>545  Schema.decodeUnknownEffect(Schema.fromJsonString(Envelope(data)));546547const dataOf = (ran: Ran) =>548  Effect.map(549    decodeEnvelope(Schema.Unknown)(ran.out.join("\n")).pipe(Effect.orDie),550    (printed) => (printed.ok ? printed.data : undefined)551  );552553const filled = (lines: readonly string[]) =>554  lines.filter((line) => line.length > 0);555556const allOf = (ran: Ran) => [...ran.out, ...ran.err, ...ran.logged].join("\n");557558// What any base64 text holding the value at this byte alignment must contain.559const base64At = (shift: number) => {560  const encoded = btoa(`${"\0".repeat(shift)}${value}`);561562  return encoded.slice(563    shift === 0 ? 0 : 4,564    (shift + value.length) % 3 === 0 ? encoded.length : encoded.length - 4565  );566};567568const forms = [569  value,570  ...[0, 1, 2]571    .map(base64At)572    .flatMap((form) => [form, form.replaceAll("+", "-").replaceAll("/", "_")]),573];574575const holds = (text: string) => forms.some((form) => text.includes(form));576577const setAtOf = (set: Ran) =>578  / at (?<at>\S+Z)\. /u.exec(filled(set.out)[0] ?? "")?.groups?.at;579580const Entries = Schema.Struct({581  entries: Schema.Array(Schema.Record(Schema.String, Schema.Unknown)),582});583584const tokenItem = (envView: Ran) =>585  Effect.map(586    decodeEnvelope(EnvSchemaView)(envView.out.join("\n")).pipe(Effect.orDie),587    (printed) =>588      printed.ok589        ? printed.data.items.find(({ key }) => key === token)590        : undefined591  );592593const placeholder = `__${token}_PLACEHOLDER__`;594595layer(ScenarioOnce, { excludeTestServices: true, timeout: "240 seconds" })(596  `${Brand.cli} env set against the platform's Node world, the visibility cartridge composed`,597  (it) => {598    it.effect(599      "stores ines-v's piped token and prints one line naming the key, ines-v and a time",600      () =>601        Effect.gen(function* () {602          const { set } = yield* Scenario;603604          expect({605            code: set.code,606            err: filled(set.err),607            out: filled(set.out),608          }).toStrictEqual({609            code: 0,610            err: [],611            out: [612              expect.stringMatching(613                /^SENTRY_AUTH_TOKEN on ines-v\/datekit was set by ines-v at \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\. Nobody can read it back\.$/u614              ),615            ],616          });617        })618    );619620    it.effect(621      "shows who set the token and when in env shape and in the ledger, and nothing more of it",622      () =>623        Effect.gen(function* () {624          const { envView, ledger, set } = yield* Scenario;625          const item = yield* tokenItem(envView);626          const at = setAtOf(set) ?? "never";627628          const data = yield* dataOf(ledger);629          const { entries } = yield* Schema.decodeUnknownEffect(Ledger)(data);630          const encoded = yield* Schema.decodeUnknownEffect(Entries)(data);631632          expect({633            code: envView.code,634            sensitive: item?.sensitive,635            setAt: item?.value && DateTime.formatIso(item.value.setAt),636            setBy: item?.value?.setBy,637          }).toStrictEqual({638            code: 0,639            sensitive: true,640            setAt: at,641            setBy: "ines-v",642          });643          expect(entries).toStrictEqual([644            LedgerEntry.cases.ValueSet.make({645              at: DateTime.makeUnsafe(at),646              by: ines.handle,647              key: token,648              seq: 1,649            }),650          ]);651          // The entry is who, which key and when, numbered: no field holds more.652          expect(653            encoded.entries.map((entry) => Object.keys(entry).toSorted())654          ).toStrictEqual([["_tag", "at", "by", "key", "seq"]]);655        })656    );657658    it.effect(659      "leaves the value in no output, response body, log line, event, ledger entry or job, and the DO's row holds it sealed",660      () =>661        Effect.gen(function* () {662          const scenario = yield* Scenario;663          const { kept, printed, set } = scenario;664665          const runs = [666            scenario.set,667            scenario.byBram,668            scenario.publicItem,669            scenario.tooShort,670            scenario.envView,671            scenario.ledger,672          ];673674          // Counts, so a failure never prints what it found.675          expect({676            bodies: kept.bodies.filter(holds).length,677            cli: runs.filter((ran) => holds(allOf(ran))).length,678            envValues: holds(JSON.stringify(kept.store?.envValues ?? null)),679            events: holds(JSON.stringify(kept.store?.events ?? null)),680            jobs: holds(JSON.stringify(kept.jobs)),681            ledger: holds(JSON.stringify(kept.store?.ledger ?? null)),682            logged: kept.logged.filter(holds).length,683            printed: holds(printed),684          }).toStrictEqual({685            bodies: 0,686            cli: 0,687            envValues: false,688            events: false,689            jobs: false,690            ledger: false,691            logged: 0,692            printed: false,693          });694695          const reply = JSON.stringify({696            key: token,697            setAt: setAtOf(set),698            setBy: "ines-v",699          });700701          expect({702            event: JSON.stringify(kept.store?.events ?? null).includes(703              '"entry":{"_tag":"ValueSet"'704            ),705            logged: kept.logged.filter((line) =>706              line.includes('"a write-only value was set"')707            ),708            printed: printed.includes("a write-only value was set"),709            replies: kept.bodies.filter((body) => body.includes(reply)).length,710            rows: kept.store?.envValues.map(711              ({ key, sealed, setAt, setBy }) => ({712                key,713                sealed: Object.keys(sealed).length > 0,714                setAt,715                setBy,716              })717            ),718          }).toStrictEqual({719            event: true,720            logged: [721              `["a write-only value was set"] {"project":"${project}","by":"ines-v","key":"${token}"}`,722            ],723            printed: true,724            replies: 1,725            rows: [726              {727                key: token,728                sealed: true,729                setAt: setAtOf(set),730                setBy: "ines-v",731              },732            ],733          });734        })735    );736737    it.effect(738      "refuses bram, no maintainer, with NotDecider printed once and exit 77",739      () =>740        Effect.gen(function* () {741          const { byBram } = yield* Scenario;742743          expect({744            code: byBram.code,745            err: filled(byBram.err),746            out: filled(byBram.out),747          }).toStrictEqual({748            code: 77,749            err: explain([new NotDecider({})]),750            out: [],751          });752        })753    );754755    it.effect(756      "refuses a public item NotSensitive, and a short value ValueTooShort that tells neither the value nor its length",757      () =>758        Effect.gen(function* () {759          const { publicItem, tooShort } = yield* Scenario;760761          expect({762            publicItem: {763              code: publicItem.code,764              err: filled(publicItem.err),765              out: filled(publicItem.out),766            },767            tooShort: {768              code: tooShort.code,769              err: filled(tooShort.err),770              out: filled(tooShort.out),771            },772          }).toStrictEqual({773            publicItem: {774              code: 65,775              err: explain([new NotSensitive({ key: EnvKey.make("APP_ENV") })]),776              out: [],777            },778            tooShort: {779              code: 65,780              err: explain([ValueTooShort.of(token, 12)]),781              out: [],782            },783          });784          expect(allOf(tooShort)).not.toContain(short);785          expect(allOf(tooShort)).not.toContain(String(short.length));786        })787    );788789    it.effect(790      "gives the answer's checks the token's placeholder, and no value",791      () =>792        Effect.gen(function* () {793          const { answerJobs, answered } = yield* Scenario;794795          expect(answered.exitCode).toBe(0);796          expect(answered.stderr).toContain(`remote: checking ${ask} at `);797          expect(answerJobs.map(({ repo }) => repo)).toContain(798            `${keyOf(project)}--${ask}--${bram.handle}`799          );800          expect(801            answerJobs.map((job) => ({802              landed: job.landed ?? false,803              placeholders: job.placeholders,804              proxies: job.proxies,805              values: job.values?.length ?? 0,806            }))807          ).toStrictEqual(808            answerJobs.map(() => ({809              landed: false,810              placeholders: [{ key: token, placeholder }],811              proxies: [812                {813                  block: false,814                  host: "sentry.io",815                  key: token,816                  path: "/api/**",817                  placeholder,818                },819              ],820              values: 0,821            }))822          );823        })824    );825826    it.effect(827      "serves no setEnv tool over /mcp, where it serves the env shape's",828      () =>829        Effect.gen(function* () {830          const { tools } = yield* Scenario;831832          expect(tools).toContain("envShape");833          expect(tools).not.toContain("setEnv");834        })835    );836  }837);