Skip to content
Myr

env.test.ts

This file

Path

packages/project/test/visibility/env.test.ts

841 lines · 23.8 KiB · TypeScript

Last changed by

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

History of this file

Take it

1import { describe, expect, it } from "@effect/vitest";2import { RefName, RepoHost } from "@repo/artifacts/repo-host";3import { Brand } from "@repo/brand";4import { Hostname } from "@repo/protocol/domain/common";5import { DecisionSubject } from "@repo/protocol/domain/decision";6import { EnvItem } from "@repo/protocol/domain/env";7import { ProjectEvent } from "@repo/protocol/domain/event";8import { Territory } from "@repo/protocol/domain/territory";9import { LedgerEntry } from "@repo/protocol/domain/visibility";10import {11  EnvKey,12  Handle,13  LandedSha,14  LaneName,15  RepoName,16  RepoPath,17  keyOf,18  RequestId,19} from "@repo/protocol/ids";20import { Anonymous, Person } from "@repo/protocol/principal";21import {22  NotDecider,23  NotSensitive,24  UnknownEnvItem,25  ValueTooShort,26} from "@repo/protocol/refusal";27import { advanceTo, at } from "@repo/testkit/clock";28import type { Files } from "@repo/testkit/git-client";29import { aProject, withAsk } from "@repo/testkit/scenarios";30import type { Scenario } from "@repo/testkit/scenarios";31import { EnvSchemaParser } from "@repo/visibility/env-schema";32import type { ParsedEnvSchema } from "@repo/visibility/env-schema";33import { EnvSchemaParserEnvSpec } from "@repo/visibility/env-schema/env-spec";34import { EnvSchemaParserMemory } from "@repo/visibility/env-schema/memory";35import { SealedValue } from "@repo/visibility/vault";36import { WriteOnlyValuesWebCrypto } from "@repo/visibility/vault/webcrypto";37import { Context, Effect, Layer, Option, Redacted, Ref, Schema } from "effect";3839import datekitText from "../../../../examples/datekit/.env.schema?raw";40import { noRunEnv, ProjectEnv } from "../../src/env-port.ts";41import { ProjectStore } from "../../src/project-store.ts";42import { projectService } from "../../src/project.ts";43import type { ProjectApi } from "../../src/project.ts";44import {45  ProjectEnvLive,46  schemaFilesAt,47  widenedProxies,48} from "../../src/visibility/env.ts";49import { CheckScript, mergedAt, Pusher, worldOf } from "../world.ts";5051const scenario = aProject({ deciders: ["ines-v"], people: ["bram"] });5253const { project } = scenario;5455const repo = RepoName.make(keyOf(project));5657const mainRef = RefName.make("refs/heads/main");5859const ines = Person.make({ handle: Handle.make("ines-v") });6061const bram = Person.make({ handle: Handle.make("bram") });6263const anyone = Anonymous.make({});6465const noon = at("2026-10-07T12:00:00Z");6667const token = EnvKey.make("SENTRY_AUTH_TOKEN");6869const value = "sntrys_eyJpYXQiOjE3M";7071const envFile = RepoPath.make(".env.schema");7273const datekitParsed: ParsedEnvSchema = {74  header: [75    {76      name: "currentEnv",77      value: {78        fn: "ref",79        named: [],80        positional: ["APP_ENV"],81        text: "ref(APP_ENV)",82      },83    },84    { name: "defaultRequired", value: "infer" },85    { name: "defaultSensitive", value: false },86  ],87  imports: [],88  items: [89    {90      decorators: [91        {92          name: "type",93          value: {94            fn: "enum",95            named: [],96            positional: ["development", "test", "production"],97            text: "enum(development, test, production)",98          },99        },100      ],101      key: "APP_ENV",102      value: "development",103    },104    {105      decorators: [{ name: "type", value: "url" }],106      description: "Error reporting DSN. Public: it ships in builds.",107      key: "SENTRY_DSN",108      value: "https://public@o0.ingest.example.invalid/1",109    },110    {111      decorators: [112        { name: "sensitive", value: true },113        {114          name: "required",115          value: {116            fn: "forEnv",117            named: [],118            positional: ["production"],119            text: "forEnv(production)",120          },121        },122        { name: "tag", value: { named: [], positional: ["release"] } },123        {124          name: "proxy",125          value: {126            named: [127              { key: "domain", value: "sentry.io" },128              { key: "path", value: "/api/**" },129            ],130            positional: [],131          },132        },133      ],134      description:135        "Source-map upload token. Release step only; never enters a check.",136      key: "SENTRY_AUTH_TOKEN",137    },138    {139      decorators: [],140      description: "Where locale data lives.",141      key: "DATEKIT_LOCALE_DIR",142      value: "./locales",143    },144  ],145};146147const item = Schema.decodeUnknownSync(EnvItem);148149const weekParsed: ParsedEnvSchema = {150  header: [],151  imports: [],152  items: [153    { decorators: [], key: "APP_ENV", value: "test" },154    { decorators: [], key: "WEEK_API_KEY" },155  ],156};157158class Parses extends Context.Service<159  Parses,160  { readonly count: Effect.Effect<number> }161>()("test/Parses") {}162163const counting = (inner: Layer.Layer<EnvSchemaParser>) =>164  Layer.effectContext(165    Effect.gen(function* () {166      const parser = yield* EnvSchemaParser;167      const count = yield* Ref.make(0);168169      return Context.make(170        EnvSchemaParser,171        EnvSchemaParser.of({172          parse: (file, text) =>173            Effect.andThen(174              Ref.update(count, (n) => n + 1),175              parser.parse(file, text)176            ),177        })178      ).pipe(Context.add(Parses, { count: Ref.get(count) }));179    })180  ).pipe(Layer.provide(inner));181182const sentryAuthToken = item({183  description:184    "Source-map upload token. Release step only; never enters a check.",185  key: "SENTRY_AUTH_TOKEN",186  proxy: { domains: ["sentry.io"], path: "/api/**" },187  required: "depends",188  sensitive: true,189  tags: ["release"],190});191192const tokenPlaceholder = "__SENTRY_AUTH_TOKEN_PLACEHOLDER__";193194const tokenRunEnv = {195  placeholders: [{ key: token, placeholder: tokenPlaceholder }],196  proxies: [197    {198      block: false,199      host: "sentry.io",200      key: token,201      path: "/api/**",202      placeholder: tokenPlaceholder,203    },204  ],205};206207const start = (schema: string): Files => [208  ["package.json", '{ "name": "alice/datekit" }\n'],209  ["src/index.ts", "export const now = () => 0;\n"],210  [".env.schema", schema],211];212213const vault = WriteOnlyValuesWebCrypto(214  Redacted.make("0123456789abcdef".repeat(4))215);216217const worldWith = <More = never>(218  parser: Layer.Layer<EnvSchemaParser | More>,219  on: Scenario = scenario220) =>221  ProjectEnvLive.pipe(222    Layer.provide(vault),223    Layer.provideMerge(parser),224    Layer.provideMerge(worldOf(on, "memory"))225  );226227const world = worldWith(228  EnvSchemaParserMemory(new Map([[envFile, datekitParsed]]))229);230231const begun = (schema: string = datekitText, more: Files = []) =>232  Effect.gen(function* () {233    yield* advanceTo("2026-10-07T12:00:00Z");234235    const api = yield* projectService(project);236237    yield* api.initProject(ines, {});238239    const first = yield* Pusher.use((pusher) =>240      pusher.push(repo, Option.none(), [...start(schema), ...more], "Start")241    );242243    yield* api.recordFirstPush(ines, first);244245    return api;246  });247248const tokenItem = (api: ProjectApi) =>249  Effect.map(api.envShape(anyone), ({ items }) =>250    items.find(({ key }) => key === token)251  );252253const stored = ProjectStore.use((store) => store.load());254255describe("the env shape at the landed SHA", () => {256  // Holds the hand-written fake to the real parser's reading, so a drift in either shows here.257  it.effect(258    "is read from datekit's committed .env.schema as the fake holds it",259    () =>260      Effect.gen(function* () {261        const parser = yield* EnvSchemaParser;262263        expect(yield* parser.parse(envFile, datekitText)).toStrictEqual(264          datekitParsed265        );266      }).pipe(Effect.provide(EnvSchemaParserEnvSpec))267  );268269  it.effect(270    "is empty where no schema can be read, so a maintainer's value is for an unknown item",271    () =>272      Effect.gen(function* () {273        const api = yield* begun();274        const shown = yield* api.envShape(anyone);275276        const refused = yield* Effect.flip(277          api.setEnv(ines, { key: token, value: Redacted.make(value) })278        );279280        const env = yield* ProjectEnv;281282        expect({283          file: shown.file,284          items: shown.items,285          refused,286          run: yield* env.runEnv({ landed: false }, yield* stored),287          stored: (yield* stored).envValues,288        }).toStrictEqual({289          file: envFile,290          items: [],291          refused: new UnknownEnvItem({ key: token }),292          run: noRunEnv,293          stored: [],294        });295      }).pipe(Effect.provide(worldWith(EnvSchemaParserMemory(new Map()))))296  );297298  it.effect(299    "lists datekit's four items, the token sensitive behind sentry.io and with no value",300    () =>301      Effect.gen(function* () {302        const api = yield* begun();303        const shown = yield* api.envShape(anyone);304305        expect({306          currentEnvKey: shown.currentEnvKey,307          file: shown.file,308          keys: shown.items.map(({ key }) => key),309          token: shown.items.find(({ key }) => key === token),310        }).toStrictEqual({311          currentEnvKey: "APP_ENV",312          file: envFile,313          keys: [314            "APP_ENV",315            "SENTRY_DSN",316            "SENTRY_AUTH_TOKEN",317            "DATEKIT_LOCALE_DIR",318          ],319          token: sentryAuthToken,320        });321      }).pipe(Effect.provide(world))322  );323324  it.effect(325    "reads the root's schema first, then each workspace package's, a key declared twice once",326    () =>327      Effect.gen(function* () {328        const api = yield* begun(datekitText, [329          ["packages/week/.env.schema", "APP_ENV=test\nWEEK_API_KEY=\n"],330          ["packages/week/src/week.ts", "export const week = () => 1;\n"],331        ]);332333        const shown = yield* api.envShape(anyone);334335        expect({336          currentEnvKey: shown.currentEnvKey,337          file: shown.file,338          keys: shown.items.map(({ key }) => key),339          week: shown.items.find(({ key }) => key === "WEEK_API_KEY"),340        }).toStrictEqual({341          currentEnvKey: "APP_ENV",342          file: envFile,343          keys: [344            "APP_ENV",345            "SENTRY_DSN",346            "SENTRY_AUTH_TOKEN",347            "DATEKIT_LOCALE_DIR",348            "WEEK_API_KEY",349          ],350          week: item({351            key: "WEEK_API_KEY",352            required: true,353            sensitive: true,354            tags: [],355          }),356        });357      }).pipe(358        Effect.provide(359          worldWith(360            EnvSchemaParserMemory(361              new Map([362                [envFile, datekitParsed],363                [RepoPath.make("packages/week/.env.schema"), weekParsed],364              ])365            ),366            scenario.pipe(367              withAsk({ id: "week-start", territory: "packages/week" })368            )369          )370        )371      )372  );373374  it.effect("parses a commit's schemas once, however often it is read", () =>375    Effect.gen(function* () {376      const api = yield* begun();377378      yield* api.envShape(anyone);379      yield* api.setEnv(ines, { key: token, value: Redacted.make(value) });380      yield* api.envShape(anyone);381      yield* api.scanForValues({ text: value });382383      expect(yield* Parses.use(({ count }) => count)).toBe(1);384    }).pipe(385      Effect.provide(386        worldWith(387          counting(EnvSchemaParserMemory(new Map([[envFile, datekitParsed]])))388        )389      )390    )391  );392});393394describe("a write-only value", () => {395  it.effect(396    "is set by a maintainer, shown as who and when, stored sealed, and recorded in the ledger",397    () =>398      Effect.gen(function* () {399        const api = yield* begun();400401        const set = yield* api.setEnv(ines, {402          key: token,403          value: Redacted.make(value),404        });405406        const shown = yield* tokenItem(api);407        const rows = yield* stored;408        const row = rows.envValues.find(({ key }) => key === token);409410        const sealed = yield* Schema.decodeUnknownEffect(SealedValue)(411          row?.sealed412        );413414        expect({415          ledger: rows.ledger,416          row: { setAt: row?.setAt, setBy: row?.setBy },417          set,418        }).toStrictEqual({419          ledger: [420            LedgerEntry.cases.ValueSet.make({421              at: noon,422              by: Handle.make("ines-v"),423              key: token,424              seq: 1,425            }),426          ],427          row: { setAt: noon, setBy: "ines-v" },428          set: { key: token, setAt: noon, setBy: "ines-v" },429        });430        expect(shown).toStrictEqual({431          ...sentryAuthToken,432          value: { setAt: noon, setBy: "ines-v" },433        });434        expect(435          `${Object.values(sealed).join(" ")} ${JSON.stringify(rows.envValues)}`436        ).not.toContain(value);437      }).pipe(Effect.provide(world))438  );439440  it.effect(441    "appends the ledger entry as an event, and no event holds the value",442    () =>443      Effect.gen(function* () {444        const api = yield* begun();445446        yield* api.setEnv(ines, { key: token, value: Redacted.make(value) });447448        const events = yield* ProjectStore.use((store) =>449          store.eventsSince(0, 100)450        );451452        const appended = events.flatMap(({ event }) =>453          ProjectEvent.guards.LedgerAppended(event) ? [event.entry] : []454        );455456        expect(appended).toStrictEqual([457          LedgerEntry.cases.ValueSet.make({458            at: noon,459            by: Handle.make("ines-v"),460            key: token,461            seq: 1,462          }),463        ]);464        expect(JSON.stringify(events)).not.toContain(value);465      }).pipe(Effect.provide(world))466  );467468  it.effect(469    "is refused to a non-maintainer, for an item not sensitive or unknown, and when too short",470    () =>471      Effect.gen(function* () {472        const api = yield* begun();473474        const refused = (475          who: Person,476          key: string,477          text: string,478          acknowledgeShort = false479        ) =>480          Effect.flip(481            api.setEnv(who, {482              acknowledgeShort,483              key: EnvKey.make(key),484              value: Redacted.make(text),485            })486          );487488        const got = {489          byBram: yield* refused(bram, "SENTRY_AUTH_TOKEN", value),490          notSensitive: yield* refused(ines, "APP_ENV", value),491          shortAcknowledged: yield* refused(492            ines,493            "SENTRY_AUTH_TOKEN",494            "ab",495            true496          ),497          tooShort: yield* refused(ines, "SENTRY_AUTH_TOKEN", "abcdefgh"),498          unknown: yield* refused(ines, "NOPE", value),499        };500501        expect(got).toStrictEqual({502          byBram: new NotDecider({}),503          notSensitive: new NotSensitive({ key: EnvKey.make("APP_ENV") }),504          shortAcknowledged: new ValueTooShort({505            key: token,506            minimum: 3,507            next: `${Brand.cli} env set SENTRY_AUTH_TOKEN`,508          }),509          tooShort: ValueTooShort.of(token, 12),510          unknown: new UnknownEnvItem({ key: EnvKey.make("NOPE") }),511        });512513        const acknowledged = yield* api.setEnv(ines, {514          acknowledgeShort: true,515          key: token,516          value: Redacted.make("abcdefgh"),517        });518519        expect(acknowledged.setBy).toBe("ines-v");520        expect((yield* stored).envValues.map(({ key }) => key)).toStrictEqual([521          token,522        ]);523      }).pipe(Effect.provide(world))524  );525});526527const proxied = (proxy: string) =>528  [529    "# @defaultSensitive=false",530    "# ---",531    "# @type=enum(development, test, production)",532    "APP_ENV=development",533    "",534    "# @sensitive",535    `# @proxy(${proxy})`,536    "SENTRY_AUTH_TOKEN=",537    "",538  ].join("\n");539540describe("the env a check of unlanded code runs with", () => {541  it.effect(542    "names a placeholder for every sensitive item and the @proxy items, and holds no value",543    () =>544      Effect.gen(function* () {545        const api = yield* begun();546547        yield* api.setEnv(ines, { key: token, value: Redacted.make(value) });548549        const env = yield* ProjectEnv;550        const run = yield* env.runEnv({ landed: false }, yield* stored);551552        expect(run).toStrictEqual(tokenRunEnv);553        expect(JSON.stringify(run)).not.toContain(value);554      }).pipe(Effect.provide(world))555  );556557  it.effect(558    "leaves an empty @proxy path or method off the rule, as the check job's wire takes none",559    () =>560      Effect.gen(function* () {561        yield* begun(proxied('domain="sentry.io", path="", method="POST"'));562563        const env = yield* ProjectEnv;564565        expect(566          (yield* env.runEnv({ landed: false }, yield* stored)).proxies567        ).toStrictEqual([568          {569            block: false,570            host: "sentry.io",571            key: token,572            method: "POST",573            placeholder: tokenPlaceholder,574          },575        ]);576      }).pipe(Effect.provide(worldWith(EnvSchemaParserEnvSpec)))577  );578});579580describe("the env a check of landed code runs with", () => {581  it.effect(582    "carries the stored value, opened, beside the same placeholders and proxies",583    () =>584      Effect.gen(function* () {585        const api = yield* begun();586587        yield* api.setEnv(ines, { key: token, value: Redacted.make(value) });588589        const env = yield* ProjectEnv;590591        const { values, ...run } = yield* env.runEnv(592          { landed: true },593          yield* stored594        );595596        expect({597          run,598          values: values?.map((each) => ({599            key: each.key,600            value: Redacted.value(each.value),601          })),602        }).toStrictEqual({603          run: { ...tokenRunEnv, landed: true },604          values: [{ key: token, value }],605        });606      }).pipe(Effect.provide(world))607  );608609  it.effect("carries no value for an item whose value nobody set", () =>610    Effect.gen(function* () {611      yield* begun();612613      const env = yield* ProjectEnv;614615      expect(yield* env.runEnv({ landed: true }, yield* stored)).toStrictEqual({616        ...tokenRunEnv,617        landed: true,618        values: [],619      });620    }).pipe(Effect.provide(world))621  );622});623624describe("the scan for stored values", () => {625  it.effect(626    "finds a stored value in a text or a blob by its item, and never the placeholder",627    () =>628      Effect.gen(function* () {629        const api = yield* begun();630631        yield* api.setEnv(ines, { key: token, value: Redacted.make(value) });632633        expect({634          blob: yield* api.scanForValues({635            blob: new TextEncoder().encode(`SENTRY_AUTH_TOKEN=${value}\n`),636          }),637          placeholder: yield* api.scanForValues({638            text: "Authorization: Bearer __SENTRY_AUTH_TOKEN_PLACEHOLDER__",639          }),640          text: yield* api.scanForValues({641            text: `uploading with ${value} to sentry.io`,642          }),643        }).toStrictEqual({644          blob: Option.some(token),645          placeholder: Option.none(),646          text: Option.some(token),647        });648      }).pipe(Effect.provide(world))649  );650});651652const narrow = proxied('domain="sentry.io"');653654const wide = proxied('domain=["sentry.io", "upload.example.invalid"]');655656const tipOf = (name: RepoName) =>657  Effect.gen(function* () {658    const refs = yield* (yield* RepoHost).refs(name).pipe(Effect.orDie);659660    return LandedSha.make(661      Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))662    );663  });664665const landSchema = (api: ProjectApi, schema: string, requestId: string) =>666  Effect.gen(function* () {667    const { fork } = yield* api.fork(ines);668    const base = yield* tipOf(fork);669    const main = yield* tipOf(repo);670671    const head = yield* Pusher.use((pusher) =>672      pusher.push(fork, Option.some(base), start(schema), "Change the env")673    );674675    const merged = yield* mergedAt({ base, fork, head, main, repo });676677    yield* CheckScript.use((checker) =>678      Effect.forEach(679        [LaneName.make("lint"), LaneName.make("types")],680        (lane) => checker.script(merged, lane, ["passed"]),681        { discard: true }682      )683    );684685    yield* api.land(ines, {686      base,687      head,688      message: "Change the env",689      requestId: RequestId.make(requestId),690    });691692    return yield* tipOf(repo);693  });694695const widenings = (api: ProjectApi) =>696  Effect.map(api.today(ines), ({ decisions }) =>697    decisions.flatMap(({ evidence, subject }) =>698      DecisionSubject.guards.ProxyWidened(subject)699        ? [{ evidence, subject }]700        : []701    )702  );703704describe("a landing that widens a @proxy", () => {705  const read = worldWith(EnvSchemaParserEnvSpec);706707  it.effect(708    "opens a ProxyWidened decision on Today with the hosts before and after; narrowing opens none",709    () =>710      Effect.gen(function* () {711        const api = yield* begun(narrow);712        const before = yield* tipOf(repo);713        const widened = yield* landSchema(api, wide, "land-wide");714        const afterWidening = yield* widenings(api);715716        yield* landSchema(api, narrow, "land-narrow");717718        expect(widened).not.toBe(before);719        expect(afterWidening).toStrictEqual([720          {721            evidence: [722              { label: "before", value: "sentry.io" },723              { label: "after", value: "sentry.io, upload.example.invalid" },724            ],725            subject: DecisionSubject.cases.ProxyWidened.make({726              hosts: [727                Hostname.make("sentry.io"),728                Hostname.make("upload.example.invalid"),729              ],730              item: token,731            }),732          },733        ]);734        expect(yield* widenings(api)).toStrictEqual(afterWidening);735      }).pipe(Effect.provide(read))736  );737});738739const territory = Schema.decodeUnknownSync(Territory);740741describe("where the env schemas live", () => {742  it("is the repo's root, then each workspace package's folder, once each", () => {743    expect(744      schemaFilesAt([745        territory({ module: "week", paths: ["packages/week/**"] }),746        territory({747          module: "format",748          paths: ["packages/format/**", "packages/format/README.md"],749        }),750        territory({ module: "again", paths: ["packages/week/src/**"] }),751      ])752    ).toStrictEqual([753      ".env.schema",754      "packages/week/.env.schema",755      "packages/format/.env.schema",756      "packages/week/src/.env.schema",757    ]);758  });759760  it("is the root alone for a single-package repo", () => {761    expect(762      schemaFilesAt([territory({ module: ".", paths: ["**"] })])763    ).toStrictEqual([".env.schema"]);764    expect(schemaFilesAt([])).toStrictEqual([".env.schema"]);765  });766});767768const behind = (769  key: string,770  domains: readonly [string, ...string[]],771  block?: boolean772) =>773  item({774    key,775    proxy: block === undefined ? { domains } : { block, domains },776    required: true,777    sensitive: true,778    tags: [],779  });780781describe("a widened proxy", () => {782  it("is an item whose value may reach a host it could not before, with every host it may reach", () => {783    expect(784      widenedProxies(785        { items: [behind("SENTRY_AUTH_TOKEN", ["sentry.io"])] },786        {787          items: [788            behind("SENTRY_AUTH_TOKEN", [789              "sentry.io",790              "upload.example.invalid",791            ]),792            behind("NPM_TOKEN", ["registry.npmjs.org"]),793          ],794        }795      )796    ).toStrictEqual([797      {798        hosts: ["sentry.io", "upload.example.invalid"],799        item: "SENTRY_AUTH_TOKEN",800      },801      { hosts: ["registry.npmjs.org"], item: "NPM_TOKEN" },802    ]);803  });804805  it("is an unblocked rule that was blocked", () => {806    expect(807      widenedProxies(808        { items: [behind("SENTRY_AUTH_TOKEN", ["sentry.io"], true)] },809        { items: [behind("SENTRY_AUTH_TOKEN", ["sentry.io"])] }810      )811    ).toStrictEqual([{ hosts: ["sentry.io"], item: "SENTRY_AUTH_TOKEN" }]);812  });813814  it("is never a narrowing, an unchanged rule, a newly blocked one, or a dropped item", () => {815    const both = behind("SENTRY_AUTH_TOKEN", [816      "sentry.io",817      "upload.example.invalid",818    ]);819820    expect([821      widenedProxies(822        { items: [both] },823        { items: [behind("SENTRY_AUTH_TOKEN", ["sentry.io"])] }824      ),825      widenedProxies({ items: [both] }, { items: [both] }),826      widenedProxies(827        { items: [both] },828        {829          items: [830            behind(831              "SENTRY_AUTH_TOKEN",832              ["sentry.io", "upload.example.invalid", "evil.example"],833              true834            ),835          ],836        }837      ),838      widenedProxies({ items: [both] }, { items: [] }),839    ]).toStrictEqual([[], [], [], []]);840  });841});