Skip to content
Myr

env-set.test.ts

This file

Path

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

493 lines · 14.8 KiB · TypeScript

Last changed by

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

History of this file

Take it

1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { Client, Contracts } from "@repo/protocol/contracts";5import type { SetEnv } from "@repo/protocol/contracts";6import { Envelope } from "@repo/protocol/envelope";7import { EnvKey, Handle } from "@repo/protocol/ids";8import { NotSensitive, ValueTooShort } from "@repo/protocol/refusal";9import { explain } from "@repo/protocol/render";10import { asTester, unanswered } from "@repo/protocol/testing";11import {12  Cause,13  DateTime,14  Effect,15  Exit,16  Layer,17  Logger,18  Option,19  Queue,20  Redacted,21  Ref,22  References,23  Runtime,24  Schema,25  Stdio,26  Stream,27  Terminal,28} from "effect";29import { CliOutput } from "effect/cli";30import { RpcTest } from "effect/rpc";31import type { Rpc } from "effect/rpc";32import { TestConsole } from "effect/testing";3334import { refuseStrangeFlags } from "../../src/local/env-set.ts";35import { program } from "../../src/main.ts";36import { Output, OutputPlain } from "../../src/output.ts";37import type { Mode } from "../../src/output.ts";38import { SignedOut } from "../signed-out.ts";3940const secret = "sk_live_0123456789abcdef";4142const key = EnvKey.make("SENTRY_AUTH_TOKEN");4344const setAt = DateTime.makeUnsafe("2026-10-07T09:00:00Z");4546const piped = Stream.make(new TextEncoder().encode(`${secret}\n`));4748type Payload = Rpc.Payload<typeof SetEnv>;4950type Answer = Effect.Effect<51  Rpc.Success<typeof SetEnv>,52  NotSensitive | ValueTooShort53>;5455const stored: Answer = Effect.succeed({56  key,57  setAt,58  setBy: Handle.make("alice"),59});6061interface Printed {62  readonly method: "success" | "refused" | "plan" | "note";63  readonly input: object | string;64}6566interface Ran {67  readonly code: number;68  readonly out: string;69  readonly err: string;70  readonly logged: string;71  readonly calls: readonly Payload[];72  readonly printed: readonly Printed[];73  readonly shown: string;74}7576interface Setup {77  readonly mode?: Mode;78  readonly stdin?: Stream.Stream<Uint8Array>;79  readonly stdinIsTerminal?: boolean;80  readonly typed?: string;81  readonly answer?: Answer;82}8384const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>85  Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));8687const press = (name: string, input: Option.Option<string>) => ({88  input,89  key: { ctrl: false, meta: false, name, shift: false },90});9192const run = (args: readonly string[], setup: Setup = {}) =>93  Effect.gen(function* () {94    const calls = yield* Ref.make<readonly Payload[]>([]);95    const printed = yield* Ref.make<readonly Printed[]>([]);96    const shown = yield* Ref.make<readonly string[]>([]);97    const logged: string[] = [];9899    const record = (method: Printed["method"], input: Printed["input"]) =>100      Ref.update(printed, (all) => [...all, { input, method }]);101102    const output = Layer.effect(103      Output,104      Effect.gen(function* () {105        const plain = yield* Effect.service(Output);106107        return {108          mode: setup.mode ?? "human",109          note: (text) =>110            Effect.andThen(record("note", text), plain.note(text)),111          plan: (input) =>112            Effect.andThen(record("plan", input), plain.plan(input)),113          refused: (input) =>114            Effect.andThen(record("refused", input), plain.refused(input)),115          success: (input) =>116            Effect.andThen(record("success", input), plain.success(input)),117        } satisfies Output["Service"];118      })119    ).pipe(Layer.provide(OutputPlain));120121    const terminal = Layer.succeed(Terminal.Terminal)(122      Terminal.make({123        columns: Effect.succeed(80),124        display: (text) => Ref.update(shown, (all) => [...all, text]),125        readInput: Effect.gen(function* () {126          if (setup.typed === undefined) {127            return yield* Effect.die("prompted, where no prompt may run");128          }129130          const keys = yield* Queue.unbounded<Terminal.UserInput, Cause.Done>();131132          yield* Queue.offerAll(keys, [133            ...setup.typed134              .split("")135              .map((char) => press(char, Option.some(char))),136            press("enter", Option.none()),137          ]);138139          return keys;140        }),141        readLine: Effect.die("readLine is never used"),142        rows: Effect.succeed(24),143      })144    );145146    const platform = Layer.effect(Client)(RpcTest.makeClient(Contracts)).pipe(147      Layer.provide([148        Layer.mergeAll(149          unanswered,150          Contracts.toLayerHandler("setEnv", (payload) =>151            Ref.update(calls, (all) => [...all, payload]).pipe(152              Effect.andThen(setup.answer ?? stored)153            )154          )155        ),156        asTester,157      ])158    );159160    const exit = yield* Effect.exit(161      program(["env", "set", ...args]).pipe(162        Effect.provide(163          Layer.mergeAll(164            CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),165            platform,166            output,167            SignedOut,168            terminal,169            Logger.layer([170              Logger.make((options) => {171                logged.push(Logger.formatSimple.log(options));172              }),173            ]),174            Stdio.layerTest({175              stdin: setup.stdin ?? piped,176              stdinIsTerminal: Effect.succeed(setup.stdinIsTerminal ?? false),177            })178          )179        ),180        Effect.provideService(References.MinimumLogLevel, "All")181      )182    );183184    return {185      calls: yield* Ref.get(calls),186      code: exitCodeOf(exit),187      err: (yield* TestConsole.errorLines).map(String).join("\n"),188      logged: logged.join("\n"),189      out: (yield* TestConsole.logLines).map(String).join("\n"),190      printed: yield* Ref.get(printed),191      shown: (yield* Ref.get(shown)).join(""),192    } satisfies Ran;193  }).pipe(Effect.provide(TestConsole.layer));194195const neverShown = (ran: Ran) => {196  for (const seen of [197    ran.out,198    ran.err,199    ran.logged,200    ran.shown,201    JSON.stringify(ran.printed),202  ]) {203    expect(seen).not.toContain(secret);204    expect(seen).not.toContain("0123456789abcdef");205  }206};207208const decodeEnvelope = Schema.decodeEffect(209  Schema.fromJsonString(Envelope(Schema.Unknown))210);211212const onlyCall = (ran: Ran) => {213  expect(ran.calls).toHaveLength(1);214215  const [call] = ran.calls;216217  expect(call).toBeDefined();218  expect(Redacted.isRedacted(call?.value)).toBeTruthy();219220  return {221    ...call,222    value: call === undefined ? undefined : Redacted.value(call.value),223  };224};225226const always = ["--project", "oscabriel/datekit"];227228describe(`${Brand.cli} env set`, () => {229  it.live(230    "sends the piped value, less one newline, as a Redacted, and prints only who set which key and when",231    () =>232      Effect.gen(function* () {233        const ran = yield* run([key, ...always, "--yes", "--json"]);234235        expect(ran.code).toBe(0);236        expect(onlyCall(ran)).toStrictEqual({237          key: "SENTRY_AUTH_TOKEN",238          project: "oscabriel/datekit",239          value: secret,240        });241        expect(ran.err).toBe("");242        expect(yield* decodeEnvelope(ran.out)).toStrictEqual({243          command: "env set",244          data: {245            key: "SENTRY_AUTH_TOKEN",246            setAt: "2026-10-07T09:00:00.000Z",247            setBy: "alice",248          },249          ok: true,250          v: 1,251        });252        neverShown(ran);253      }).pipe(Effect.provide(NodeServices.layer))254  );255256  it.live(257    "refuses a value given as an argument, as a usage error that does not echo it",258    () =>259      Effect.gen(function* () {260        const ran = yield* run([key, secret, ...always, "--yes"]);261262        expect(ran.code).toBe(2);263        expect(ran.calls).toStrictEqual([]);264        expect(ran.err).toContain("stdin");265        neverShown(ran);266      }).pipe(Effect.provide(NodeServices.layer))267  );268269  it.live.each([270    {271      typed: `-${secret}`,272      why: "a value that starts with a dash, holding a v that would read as --version",273    },274    {275      typed: "-Zq8_w0rd5ecret",276      why: "a value effect/cli would read as short flags and print back letter by letter",277    },278    { typed: `--${secret}`, why: "a value that reads as a long flag" },279    { typed: `--token=${secret}`, why: "a value given to a flag it lacks" },280  ])(281    "refuses $why as a usage error, in one line that repeats none of it",282    ({ typed }) =>283      Effect.gen(function* () {284        const ran = yield* run([key, typed, ...always, "--yes"]);285286        expect(ran.code).toBe(2);287        expect(ran.calls).toStrictEqual([]);288        expect(ran.out).toBe("");289        expect(ran.err.split("\n")).toStrictEqual([290          expect.stringContaining("stdin"),291        ]);292        expect(ran.err).not.toContain(typed.slice(1, 4));293        neverShown(ran);294      }).pipe(Effect.provide(NodeServices.layer))295  );296297  it.live.each([298    { args: [key, "--project=datekit", "--yes"], shows: "set by alice" },299    {300      args: [key, ...always, "--yes", "--log-level", "debug"],301      shows: "set by alice",302    },303    { args: [key, "-h"], shows: "--acknowledge-short" },304    { args: [key, "--no-json", ...always, "--yes"], shows: "set by alice" },305  ])("still takes its own flags and effect/cli's: $args", ({ args, shows }) =>306    Effect.gen(function* () {307      const ran = yield* run(args);308309      expect(ran.code).toBe(0);310      expect(ran.out).toContain(shows);311    }).pipe(Effect.provide(NodeServices.layer))312  );313314  it.live("screens out no flag that `env set --help` names", () =>315    Effect.gen(function* () {316      const help = yield* run(["--help"]);317318      const named = help.out.split("\n").flatMap((line) => {319        const flags = /^\s+(?<flags>-[^\s,]+(?:, -[^\s,]+)*)/u.exec(line)320          ?.groups?.flags;321322        return flags === undefined ? [] : flags.split(", ");323      });324325      expect(named).toStrictEqual(326        expect.arrayContaining(["--yes", "--project", "--help", "-h"])327      );328329      const screened = yield* Effect.filter(named, (flag) =>330        Effect.map(331          Effect.exit(refuseStrangeFlags(["env", "set", key, flag])),332          Exit.isFailure333        )334      );335336      expect(screened).toStrictEqual([]);337    }).pipe(338      Effect.provide([NodeServices.layer, OutputPlain, TestConsole.layer])339    )340  );341342  it.live.each([343    { kept: `${secret}\n`, sent: `${secret}\n\n`, why: "only one newline" },344    { kept: secret, sent: `${secret}\r\n`, why: "a CRLF as one newline" },345    { kept: secret, sent: secret, why: "nothing from a value with no newline" },346  ])("strips $why from the piped value", ({ kept, sent }) =>347    Effect.gen(function* () {348      const ran = yield* run([key, ...always, "--yes"], {349        stdin: Stream.make(new TextEncoder().encode(sent)),350      });351352      expect(ran.code).toBe(0);353      expect(onlyCall(ran).value).toBe(kept);354    }).pipe(Effect.provide(NodeServices.layer))355  );356357  it.live.each([358    { sent: "", why: "nothing piped" },359    { sent: "\n", why: "an empty line piped" },360  ])(361    "with $why, exits 2 telling how to pipe the value, and calls nothing",362    ({ sent }) =>363      Effect.gen(function* () {364        const ran = yield* run([key, ...always, "--yes"], {365          stdin: Stream.make(new TextEncoder().encode(sent)),366        });367368        expect(ran.code).toBe(2);369        expect(ran.calls).toStrictEqual([]);370        expect(ran.err).toContain(`| ${Brand.cli} env set ${key}`);371      }).pipe(Effect.provide(NodeServices.layer))372  );373374  it.live("without --yes, exits 2 naming it and calls nothing", () =>375    Effect.gen(function* () {376      const ran = yield* run([key, ...always]);377378      expect(ran.code).toBe(2);379      expect(ran.calls).toStrictEqual([]);380      expect(ran.err).toContain("--yes");381      neverShown(ran);382    }).pipe(Effect.provide(NodeServices.layer))383  );384385  it.live(386    "with --dry-run, hands over the payload it would send with the value redacted, and calls nothing",387    () =>388      Effect.gen(function* () {389        const ran = yield* run([key, ...always, "--dry-run", "--json"]);390391        expect(ran.code).toBe(0);392        expect(ran.calls).toStrictEqual([]);393        expect(ran.printed).toStrictEqual([394          {395            input: {396              command: "env set",397              json: true,398              payload: {399                key: "SENTRY_AUTH_TOKEN",400                project: "oscabriel/datekit",401                value: "<redacted>",402              },403            },404            method: "plan",405          },406        ]);407        expect(yield* decodeEnvelope(ran.out)).toStrictEqual({408          command: "env set",409          data: {410            dryRun: true,411            payload: {412              key: "SENTRY_AUTH_TOKEN",413              project: "oscabriel/datekit",414              value: "<redacted>",415            },416          },417          ok: true,418          v: 1,419        });420        neverShown(ran);421      }).pipe(Effect.provide(NodeServices.layer))422  );423424  it.live.each([425    { refusal: new NotSensitive({ key }) },426    { refusal: ValueTooShort.of(key, 12) },427  ])(428    "prints $refusal._tag from the platform once, and exits 65",429    ({ refusal }: { readonly refusal: NotSensitive | ValueTooShort }) =>430      Effect.gen(function* () {431        const ran = yield* run([key, ...always, "--yes"], {432          answer: Effect.fail(refusal),433        });434435        expect(ran.code).toBe(65);436        expect(ran.out).toBe("");437        expect(ran.err).toBe(explain([refusal]).join("\n"));438        neverShown(ran);439      }).pipe(Effect.provide(NodeServices.layer))440  );441442  it.live("with --acknowledge-short, asks to store a short value anyway", () =>443    Effect.gen(function* () {444      const ran = yield* run([key, ...always, "--yes", "--acknowledge-short"]);445446      expect(ran.code).toBe(0);447      expect(onlyCall(ran)).toStrictEqual({448        acknowledgeShort: true,449        key: "SENTRY_AUTH_TOKEN",450        project: "oscabriel/datekit",451        value: secret,452      });453    }).pipe(Effect.provide(NodeServices.layer))454  );455456  it.live(457    "under an agent with a terminal on stdin, never prompts: it tells the person to pipe the value",458    () =>459      Effect.gen(function* () {460        const ran = yield* run([key, ...always, "--yes"], {461          mode: "agent",462          stdinIsTerminal: true,463        });464465        expect(ran.code).toBe(2);466        expect(ran.calls).toStrictEqual([]);467        expect(ran.err).toContain("pipe");468        expect(ran.shown).toBe("");469      }).pipe(Effect.provide(NodeServices.layer))470  );471472  it.live(473    "asks a person at a terminal with a prompt that shows nothing typed, not even its length",474    () =>475      Effect.gen(function* () {476        const ran = yield* run([key, ...always, "--yes"], {477          stdin: Stream.empty,478          stdinIsTerminal: true,479          typed: secret,480        });481482        expect(ran.code).toBe(0);483        expect(onlyCall(ran)).toStrictEqual({484          key: "SENTRY_AUTH_TOKEN",485          project: "oscabriel/datekit",486          value: secret,487        });488        expect(ran.shown).toContain(key);489        expect(ran.shown).not.toContain("*");490        neverShown(ran);491      }).pipe(Effect.provide(NodeServices.layer))492  );493});