Skip to content
Myr

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholders

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents c3d7b1b, e3bbb78 · Browse files · 5 files+1804 added−18 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+1804 added−18 removed

  • tests:+1248 added−0 removed
  • other:+556 added−18 removed

5 files+1804 added−18 removed

modified:apps/platform/src/visibility/env.ts+51 added-7 removed
added:apps/platform/test/visibility/env-values.test.ts+408 added
1/**2 * Write-only values over the platform's surfaces (W6 614): the handler the3 * Worker serves, its Project DOs in process on SQLite, the platform's ports4 * in memory, and the visibility cartridge's env composed over them with5 * 603's real parser and 610's WebCrypto vault under the fake env's test6 * `MASTER_KEY`. A decider sets datekit's token over `/rpc` with their7 * token; anyone reads the env shape over `/rpc` and sees who set it and8 * when. The value is in no response body, no log line and no event, and9 * the row the DO keeps is sealed. These tests live in the cartridge and go10 * with it.11 */12import { SqliteClient } from "@effect/sql-sqlite-node";13import { describe, expect, it } from "@effect/vitest";14import { Fetch } from "@repo/artifacts/fetch";15import { RefName, RepoHost } from "@repo/artifacts/repo-host";16import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";17import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";18import { CheckRunnerMemory } from "@repo/checks/check-runner/memory";19import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";20import { Upstream } from "@repo/git/upstream";21import { AlarmsMemory } from "@repo/project/alarms/memory";22import { AnswerRuns } from "@repo/project/answer-runs";23import { FrontPageMemory } from "@repo/project/front-page/memory";24import { LanderIsogit } from "@repo/project/lander/isogit";25import { FinishersFromChecks } from "@repo/project/project";26import { ProjectStore } from "@repo/project/project-store";27import { ProjectStoreSqlite } from "@repo/project/project-store/sqlite";28import { ProjectionMemory } from "@repo/project/projection/memory";29import { Projects } from "@repo/project/projects";30import { Contracts } from "@repo/protocol/contracts";31import { ProjectEvent } from "@repo/protocol/domain/event";32import type { Policy } from "@repo/protocol/domain/policy";33import { LedgerEntry } from "@repo/protocol/domain/visibility";34import { EnvKey, Handle, RepoName } from "@repo/protocol/ids";35import { Person } from "@repo/protocol/principal";36import { NotDecider } from "@repo/protocol/refusal";37import { Finishers } from "@repo/rules/finish";38import { RulesEvaluator } from "@repo/rules/rules-evaluator";39import { gitClient } from "@repo/testkit/git-client";40import { aProject } from "@repo/testkit/scenarios";41import { untouchable } from "@repo/testkit/untouchable";42import { EnvSchemaParserEnvSpec } from "@repo/visibility/env-schema/env-spec";43import { SealedValue } from "@repo/visibility/vault";44import {45 Cause,46 Context,47 Effect,48 Layer,49 Logger,50 Option,51 Redacted,52 References,53 Schema,54} from "effect";55import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";56import { RpcClient, RpcSerialization } from "effect/rpc";57import type { SqlClient } from "effect/sql/SqlClient";5859import { DoProjects } from "../../src/adapters/do-projects.ts";60import {61 MemoryRateLimits,62 WorkerCaps,63} from "../../src/adapters/rate-limits.ts";64import { decodeEnv, platformOn } from "../../src/platform.ts";65import { projectShell } from "../../src/project-shell.ts";66import { serve } from "../../src/surfaces.ts";67import { envOn } from "../../src/visibility/env.ts";68import { fakeEnv } from "../fake-env.ts";69import { origin } from "../harness.ts";70import { inProcessNamespace } from "../project-namespace.ts";7172const scenario = aProject({ deciders: ["ines-v"], people: ["bram"] });7374const { project } = scenario;7576const repo = RepoName.make(project);7778const token = EnvKey.make("SENTRY_AUTH_TOKEN");7980/** What ines-v sets: a token-shaped value of 24 characters. */81const value = "sntrys_eyJpYXQiOjE3MjA5X";8283/** Each person's platform token, as `SESSION_TOKENS` lists them. */84const tokens = {85 bram: "bram-env-values-token-0123456789abcdef",86 "ines-v": "ines-env-values-token-0123456789abcdef",87} as const;8889/** datekit's `.env.schema` (507) cut to its header, one public item and its one sensitive item. */90const datekitSchema = [91 "# @currentEnv=$APP_ENV",92 "# @defaultRequired=infer @defaultSensitive=false",93 "# ---",94 "",95 "# @type=enum(development, test, production)",96 "APP_ENV=development",97 "",98 "# Source-map upload token. Release step only; never enters a check.",99 "# @sensitive @required=forEnv(production) @tag(release)",100 '# @proxy(domain="sentry.io", path="/api/**")',101 "SENTRY_AUTH_TOKEN=",102 "",103].join("\n");104105/** A `RulesEvaluator` that evaluates nothing: at any commit, the scenario's policy. */106const rules = Layer.effect(107 RulesEvaluator,108 Effect.gen(function* () {109 const finishers = yield* Finishers;110111 return RulesEvaluator.of({112 call: () => Effect.succeed(false),113 evaluate: ({ at, facts }) =>114 Effect.succeed({115 ...scenario.policy,116 asks: [],117 at,118 judge: finishers.judgeClosure(scenario.policy.run, facts.ci),119 } satisfies Policy),120 });121 })122).pipe(Layer.provide(FinishersFromChecks));123124/** Every line logged, with its annotations and cause, as text. */125const keeper = (logged: string[]) =>126 Logger.make(({ cause, fiber, message }) => {127 logged.push(128 [129 JSON.stringify(message),130 JSON.stringify(fiber.getRef(References.CurrentLogAnnotations)),131 Cause.pretty(cause),132 ].join(" ")133 );134 });135136/** What the world kept: every response body and log line, and each DO's SQLite. */137interface Kept {138 readonly bodies: string[];139 readonly logged: string[];140 readonly databases: Map<string, Context.Context<SqlClient>>;141}142143/**144 * The platform's handler over its ports, the env cartridge composed with145 * the real parser and the fake env's master key, its Project DOs in146 * process; datekit made by ines-v and its first commit landed.147 */148const world = (kept: Kept) =>149 Effect.gen(function* () {150 // The stage's env as the Worker decodes it, with the people's tokens.151 const env = {152 ...fakeEnv(),153 SESSION_TOKENS: JSON.stringify(154 Object.fromEntries(155 Object.entries(tokens).map(([handle, each]) => [each, handle])156 )157 ),158 };159160 const config = yield* decodeEnv(env).pipe(Effect.orDie);161162 const base = yield* Layer.build(163 Layer.mergeAll(164 LanderIsogit,165 CheckRunnerMemory.layer(new Map()),166 rules,167 EvidenceStoreMemory,168 FrontPageMemory.layer({ credits: [], entries: [], projects: [] }),169 ProjectionMemory,170 MemoryRateLimits(WorkerCaps),171 Layer.succeed(Fetch, untouchable<Fetch["Service"]>("Fetch")),172 Layer.succeed(Upstream, untouchable<Upstream["Service"]>("Upstream")),173 envOn(config, EnvSchemaParserEnvSpec)174 ).pipe(Layer.provideMerge(RepoHostMemory))175 );176177 const noRuns = Layer.succeed(178 AnswerRuns,179 AnswerRuns.of({ start: () => Effect.void })180 );181182 const { namespace } = yield* inProcessNamespace((name) =>183 Effect.gen(function* () {184 const sql = yield* Layer.build(185 SqliteClient.layer({ filename: ":memory:" }).pipe(Layer.orDie)186 );187188 kept.databases.set(name, sql);189190 return yield* projectShell({191 name,192 ports: Layer.mergeAll(193 Layer.succeedContext(base),194 AlarmsMemory,195 noRuns196 ),197 sql: Layer.succeedContext(sql),198 });199 })200 );201202 const ports = Context.merge(203 base,204 yield* Layer.build(DoProjects(namespace))205 );206207 const { dispose, handler } = serve(208 platformOn(config, Layer.succeedContext(ports))209 );210211 yield* Effect.addFinalizer(() => Effect.promise(dispose));212213 // The handler logs through the keeper too, as the Worker's would.214 const logging = yield* Layer.build(215 Logger.layer([keeper(kept.logged)], { mergeWithExisting: true })216 );217218 // ines-v makes datekit and pushes its first commit, its env schema in it.219 const ines = Person.make({ handle: Handle.make("ines-v") });220 const api = yield* Context.get(ports, Projects).create(project);221 const client = yield* gitClient(memoryFs());222223 yield* api.initProject(ines, {});224225 const first = yield* client.commit(226 "Start",227 [228 ["package.json", '{ "name": "datekit" }\n'],229 [".env.schema", datekitSchema],230 ],231 []232 );233234 yield* Context.get(ports, RepoHost)235 .push(repo, client.source, [236 {237 from: Option.none(),238 ref: RefName.make("refs/heads/main"),239 to: first,240 },241 ])242 .pipe(Effect.orDie);243244 yield* api.recordFirstPush(ines, first);245246 // Every request reaches the handler as a fetch would send it, and247 // every response body is kept as it went out.248 const context = yield* Effect.context();249250 const fetch: typeof globalThis.fetch = (input, init) =>251 Effect.runPromiseWith(context)(252 Effect.gen(function* () {253 const response = yield* Effect.promise(() =>254 handler(new Request(input, init), logging)255 );256257 kept.bodies.push(258 yield* Effect.promise(() => response.clone().text())259 );260261 return response;262 })263 );264265 /** A client of the contracts over `/rpc`, as `who` (a bearer) or as anyone. */266 return (who?: keyof typeof tokens) =>267 RpcClient.make(Contracts).pipe(268 Effect.provide(269 RpcClient.layerProtocolHttp({270 transformClient: HttpClient.mapRequest((request) =>271 who === undefined272 ? request273 : HttpClientRequest.bearerToken(request, tokens[who])274 ),275 url: `${origin}/rpc`,276 }).pipe(277 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson]),278 Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetch))279 )280 )281 );282 }).pipe(Effect.orDie);283284/** The project's rows and events as its DO's SQLite keeps them. */285const storedIn = (kept: Kept) =>286 Effect.gen(function* () {287 const sql = yield* Effect.orDie(288 Effect.fromNullishOr(kept.databases.get(project))289 );290291 return yield* ProjectStore.use((store) =>292 Effect.all({293 events: store.eventsSince(0, 500),294 rows: store.load(),295 })296 ).pipe(297 Effect.provide(298 ProjectStoreSqlite.pipe(Layer.provide(Layer.succeedContext(sql)))299 )300 );301 });302303/**304 * bram (no decider) tries to set datekit's token, then ines-v sets it, both305 * over `/rpc` with their tokens; then anyone reads the env shape. Every306 * response body, log line and stored row and event is kept.307 */308const settingTheToken = (kept: Kept) =>309 Effect.gen(function* () {310 const clientAs = yield* world(kept);311 const ines = yield* clientAs("ines-v");312 const bram = yield* clientAs("bram");313 const anyone = yield* clientAs();314315 const refused = yield* Effect.flip(316 bram.setEnv({ key: token, project, value: Redacted.make(value) })317 );318319 const set = yield* ines.setEnv({320 key: token,321 project,322 value: Redacted.make(value),323 });324325 return {326 refused,327 set,328 shown: yield* anyone.envShape({ project }),329 stored: yield* storedIn(kept),330 };331 }).pipe(332 Effect.provide(333 Logger.layer([keeper(kept.logged)], { mergeWithExisting: true })334 )335 );336337const keptFresh = (): Kept => ({338 bodies: [],339 databases: new Map(),340 logged: [],341});342343describe("a write-only value over the platform", () => {344 it.effect(345 "is set by a decider over /rpc, refused to anyone else, sealed in the DO, and shown to anyone as who and when",346 () =>347 Effect.gen(function* () {348 const { refused, set, shown, stored } =349 yield* settingTheToken(keptFresh());350351 const row = stored.rows.envValues.find(({ key }) => key === token);352353 const sealed = yield* Schema.decodeUnknownEffect(SealedValue)(354 row?.sealed355 );356357 expect({ refused, setBy: set.setBy }).toStrictEqual({358 refused: new NotDecider({}),359 setBy: "ines-v",360 });361 expect(362 shown.items.find(({ key }) => key === token)?.value363 ).toStrictEqual({ setAt: set.setAt, setBy: "ines-v" });364 expect(Object.values(sealed).join(" ")).not.toContain(value);365 expect(366 stored.events.flatMap(({ event }) =>367 ProjectEvent.guards.LedgerAppended(event) ? [event.entry] : []368 )369 ).toStrictEqual([370 LedgerEntry.cases.ValueSet.make({371 at: set.setAt,372 by: Handle.make("ines-v"),373 key: token,374 seq: 1,375 }),376 ]);377 })378 );379380 it.effect(381 "is in no response body, log line, row or event, while the set is logged by key and setter",382 () =>383 Effect.gen(function* () {384 const kept = keptFresh();385 const { stored } = yield* settingTheToken(kept);386387 expect(kept.bodies.length).toBeGreaterThanOrEqual(3);388 expect(389 kept.logged.filter((line) =>390 line.includes('"a write-only value was set"')391 )392 ).toStrictEqual([393 `["a write-only value was set"] {"by":"ines-v","key":"SENTRY_AUTH_TOKEN"} `,394 ]);395 expect({396 bodies: kept.bodies.filter((body) => body.includes(value)),397 events: JSON.stringify(stored.events).includes(value),398 logged: kept.logged.filter((line) => line.includes(value)),399 rows: JSON.stringify(stored.rows).includes(value),400 }).toStrictEqual({401 bodies: [],402 events: false,403 logged: [],404 rows: false,405 });406 })407 );408});
modified:packages/project/src/visibility/env.ts+505 added-11 removed
1/**2 * The visibility cartridge's env (W6; 614 builds it): the env shape parsed3 * from every `.env.schema` at the landed SHA, write-only values sealed by4 * the platform's master key, placeholders and proxies for checks of5 * unlanded code, the scan for stored values, and `ProxyWidened` decisions,6 * as the `ProjectEnv` port.2 * The visibility cartridge's env (W6 614; ADR 0009), as the `ProjectEnv`3 * port:4 *8 * A stub until 614: it answers the port's neutral defaults (no items, no9 * values, nothing to scan for).5 * - The env shape: every `.env.schema` at the landed SHA (the repo's root6 * first, then each workspace package's folder), parsed through the7 * parser seam and never resolved, read once per commit, with each8 * sensitive item's who and when from the Project DO's rows. Never a value.9 * - Write-only values: only a person the policy lets set values (the10 * deciders unless `visibility.env.setters` names others) sets one, only11 * for a `@sensitive` item of the shape, sealed by the vault under the12 * platform's master key; the row and a public `ValueSet` ledger entry are13 * the call's writes, and nothing returns the value.14 * - The env a check runs with: a placeholder for every sensitive item and15 * the `@proxy` items, so unlanded code never sees a value.16 * - The scan: the one place a stored value is opened, to find it in a text17 * or a blob, and it answers with the item's key alone.18 * - After a landing: a `ProxyWidened` decision for each item whose value19 * may now reach a host it could not before (Q20; VL §8.7 #4).20 */11import { Layer } from "effect";21import { RepoHost, Revision } from "@repo/artifacts/repo-host";22import { Hostname } from "@repo/protocol/domain/common";23import type { Evidence } from "@repo/protocol/domain/common";24import { DecisionSubject } from "@repo/protocol/domain/decision";25import type { Decision } from "@repo/protocol/domain/decision";26import type { EnvItem, EnvSchemaView } from "@repo/protocol/domain/env";27import type { Policy } from "@repo/protocol/domain/policy";28import type { Territory } from "@repo/protocol/domain/territory";29import { LedgerEntry } from "@repo/protocol/domain/visibility";30import { RepoName, RepoPath, sameHandle } from "@repo/protocol/ids";31import type {32 DecisionId,33 EnvKey,34 Handle,35 LandedSha,36 ProjectName,37} from "@repo/protocol/ids";38import {39 NotDecider,40 NotSensitive,41 UnknownEnvItem,42} from "@repo/protocol/refusal";43import { EnvSchemaParser } from "@repo/visibility/env-schema";44import { envSchemaViewOf } from "@repo/visibility/env-shape";45import { scanBytes, scanText } from "@repo/visibility/leak-scan";46import type { Watched } from "@repo/visibility/leak-scan";47import { SealedValue, WriteOnlyValues } from "@repo/visibility/vault";48import {49 Array,50 Cache,51 Data,52 Duration,53 Effect,54 Exit,55 Layer,56 Option,57 Schema,58} from "effect";5960import { openDecision } from "../attention/decisions.ts";61import { decidersOn, isDecider, nextDecisionId } from "../deciders.ts";13import { noEnv, ProjectEnv } from "../env-port.ts";62import { noRunEnv, ProjectEnv } from "../env-port.ts";63import type { EnvPort, EnvSchemaFile } from "../env-port.ts";64import { ProjectEventInput } from "../events.ts";65import type { ProjectSnapshot } from "../project-store.ts";66import type { EnvValueRow } from "../project-store/rows.ts";67import { noPlan, policyIn } from "../visibility-port.ts";6869/** The env schema's name, in the repo's root and in a package's folder. */70const schemaName = ".env.schema";7172/** The root's env schema: where the shape lives when nothing else says. */73const rootSchema = RepoPath.make(schemaName);7475/** A character that makes a path segment a glob. */76const GLOB = /[*?[{]/u;7778/**79 * The folder a territory's glob covers: its fixed head (`packages/week/**`80 * → `packages/week`), or, for a glob naming one file, that file's folder.81 * The root is `""`.82 */83const folderOf = (glob: string): string => {84 const segments = glob85 .split("/")86 .filter((segment) => segment !== "" && segment !== ".");8788 const fixed = Array.takeWhile(segments, (segment) => !GLOB.test(segment));8990 return (fixed.length === segments.length ? fixed.slice(0, -1) : fixed).join(91 "/"92 );93};9495/**96 * Where a project's env schemas live: `.env.schema` in the repo's root,97 * then `<package folder>/.env.schema` for each workspace package the98 * policy's territories name, in order, each once.99 */100export const schemaFilesAt = (101 modules: readonly Territory[]102): readonly RepoPath[] =>103 Array.dedupe([104 schemaName,105 ...modules.flatMap(({ paths }) =>106 paths.flatMap((glob) => {107 const folder = folderOf(glob);108109 return folder === "" ? [] : [`${folder}/${schemaName}`];110 })111 ),112 ]).map((path) => RepoPath.make(path));113114/** Whether `pattern` (a host, or a glob `*.example.com`) covers `host`. */115const covers = (pattern: string, host: string) =>116 pattern === host ||117 (pattern.startsWith("*.") && host.endsWith(pattern.slice(1)));118119/**120 * The hosts an item's value may reach through the platform's proxy: its121 * `@proxy` domains, lower-cased, unless the rule blocks every request. Only122 * a sensitive item holds a value, so any other reaches none.123 */124const reachOf = (item: EnvItem | undefined): readonly string[] =>125 item?.sensitive === true &&126 item.proxy !== undefined &&127 item.proxy.block !== true128 ? Array.dedupe(item.proxy.domains.map((host) => host.toLowerCase()))129 : [];130131/** The hosts `key`'s value may reach in `view`: none when the view has no such item. */132const reachIn = (view: Pick<EnvSchemaView, "items">, key: EnvKey) =>133 reachOf(view.items.find((item) => item.key === key));134135/** A widened `@proxy`: the item, and every host its value may now reach. */136export interface Widened {137 readonly hosts: readonly Hostname[];138 readonly item: EnvKey;139}140141/**142 * Each item of `after` whose value may reach a host that no host or glob143 * of `before` covered: a new `@proxy` domain, a new proxied item, or a rule144 * that blocked every request and no longer does. A narrowing, an unchanged145 * rule and a newly blocked one widen nothing. The hosts are all the item's146 * hosts after, as hostnames.147 */148export const widenedProxies = (149 before: Pick<EnvSchemaView, "items">,150 after: Pick<EnvSchemaView, "items">151): readonly Widened[] =>152 after.items.flatMap((item) => {153 const was = reachIn(before, item.key);154 const reach = reachOf(item);155156 return reach.some((host) => !was.some((each) => covers(each, host)))157 ? [{ hosts: reach.filter(Schema.is(Hostname)), item: item.key }]158 : [];159 });160161/** One commit's env schemas, as the cache keeps them. */162class ReadAt extends Data.Class<{163 readonly at: LandedSha;164 readonly files: readonly RepoPath[];165 readonly project: ProjectName;166}> {}167168/**169 * A commit's env shape, read once: its items without any value's who and170 * when (the DO's rows add those), and the schema that declared each item.171 */172interface Read {173 readonly declaredIn: ReadonlyMap<EnvKey, RepoPath>;174 readonly schema: EnvSchemaFile;175}176177/** A shape with no schema in it: no items. */178const unread: Read = {179 declaredIn: new Map(),180 schema: { file: rootSchema, imports: [], items: [] },181};182183/** How many commits' shapes one project keeps read. */184const readCapacity = 16;185186/**187 * Several schemas as one shape: the root's items, then each package's not188 * already declared (the first schema to declare a key holds it); the file189 * is the first schema read, the imports are every schema's, and the190 * current env key is the first one named.191 */192const merged = (views: readonly EnvSchemaView[]): Read => {193 const [first] = views;194195 if (first === undefined) {196 return unread;197 }198199 const declaredIn = new Map<EnvKey, RepoPath>();200 const items: EnvItem[] = [];201202 for (const view of views) {203 for (const item of view.items) {204 if (!declaredIn.has(item.key)) {205 declaredIn.set(item.key, view.file);206 items.push(item);207 }208 }209 }210211 const currentEnv = Array.findFirst(views, (view) =>212 Option.fromUndefinedOr(view.currentEnvKey)213 );214215 return {216 declaredIn,217 schema: {218 file: first.file,219 imports: Array.dedupe(views.flatMap(({ imports }) => imports)),220 items,221 ...(Option.isSome(currentEnv) && { currentEnvKey: currentEnv.value }),222 },223 };224};225226/** The project's landed SHA and its row, once something landed. */227const landedIn = (snapshot: ProjectSnapshot) =>228 Option.flatMap(snapshot.project, (row) =>229 row.landed === undefined230 ? Option.none()231 : Option.some({ landed: row.landed, row })232 );233234/**235 * Whether `handle` may set write-only values: one of the setters the236 * policy's `visibility.env` names, or, when it names the deciders or the237 * project declares no visibility, a decider.238 */239const maySet = (policy: Policy, handle: Handle) => {240 const setters = policy.visibility?.env.setters ?? "deciders";241242 return setters === "deciders"243 ? isDecider(policy, handle)244 : setters.some((each) => sameHandle(each, handle));245};246247/** An item with who set its value and when, from its row: only a sensitive item has one. */248const withValue = (249 item: EnvItem,250 rows: ReadonlyMap<EnvKey, EnvValueRow>251): EnvItem => {252 const row = rows.get(item.key);253254 return item.sensitive && row !== undefined255 ? { ...item, value: { setAt: row.setAt, setBy: row.setBy } }256 : item;257};258259const encodeSealed = Schema.encodeEffect(Schema.toCodecJson(SealedValue));260261const decodeSealed = Schema.decodeUnknownEffect(262 Schema.toCodecJson(SealedValue)263);264265/** A host list as evidence shows it: `none` before an item had any. */266const hostsText = (hosts: readonly string[]) =>267 hosts.length === 0 ? "none" : hosts.join(", ");268269/**270 * The `ProjectEnv` port over the parser seam, the vault and the project's271 * repos (the public namespace's): the name 609's stub exported, so the272 * cartridge's `index.ts` and the platform compose it unchanged.273 */15export const ProjectEnvLive: Layer.Layer<never> = Layer.succeed(274export const ProjectEnvLive: Layer.Layer<275 never,276 never,277 EnvSchemaParser | WriteOnlyValues | RepoHost278> = Layer.effect(279 ProjectEnv,17 noEnv280 Effect.gen(function* () {281 const parser = yield* EnvSchemaParser;282 const vault = yield* WriteOnlyValues;283 const host = yield* RepoHost;284285 /** One schema at a commit, as the public sees it; none where the commit has no such file, or it cannot be read. */286 const viewOf = (key: ReadAt, file: RepoPath) =>287 host288 .readFile(289 RepoName.make(key.project),290 Revision.Commit({ sha: key.at }),291 file292 )293 .pipe(294 Effect.orDie,295 Effect.flatMap(296 Option.match({297 onNone: () => Effect.succeedNone,298 onSome: (bytes) =>299 parser.parse(file, new TextDecoder().decode(bytes)).pipe(300 Effect.map((parsed) =>301 Option.some(302 envSchemaViewOf({303 at: key.at,304 file,305 parsed,306 project: key.project,307 })308 )309 ),310 Effect.catchTag("EnvSchemaUnreadable", ({ reason }) =>311 Effect.as(312 Effect.logWarning(313 `the env schema ${file} at ${key.at} cannot be read: ${reason}`314 ),315 Option.none<EnvSchemaView>()316 )317 )318 ),319 })320 )321 );322323 // Read once per commit: a landed commit's schemas never change. A324 // failed read is not kept, so the next call reads again.325 const reads = yield* Cache.makeWith(326 (key: ReadAt) =>327 Effect.map(328 Effect.forEach(key.files, (file) => viewOf(key, file)),329 (views) => merged(Array.getSomes(views))330 ),331 {332 capacity: readCapacity,333 timeToLive: (exit) =>334 Exit.isSuccess(exit) ? Duration.infinity : Duration.zero,335 }336 );337338 /** The shape at `at`, from the schemas the snapshot's policy places. */339 const readAt = (at: LandedSha, snapshot: ProjectSnapshot) =>340 Option.match(snapshot.project, {341 onNone: () => Effect.succeed(unread),342 onSome: (row) =>343 Cache.get(344 reads,345 new ReadAt({346 at,347 files: schemaFilesAt(348 Option.match(policyIn(snapshot), {349 onNone: () => [],350 onSome: ({ modules }) => modules,351 })352 ),353 project: row.project,354 })355 ),356 });357358 /** The shape at the landed SHA; none before anything landed. */359 const landedRead = (snapshot: ProjectSnapshot) =>360 Option.match(landedIn(snapshot), {361 onNone: () => Effect.succeed(unread),362 onSome: ({ landed }) => readAt(landed, snapshot),363 });364365 /** Every stored value, opened, to look for; dropped when the scan ends. */366 const watched = (rows: readonly EnvValueRow[]) =>367 Effect.forEach(rows, (row) =>368 decodeSealed(row.sealed).pipe(369 Effect.orDie,370 Effect.flatMap(vault.open),371 Effect.map((value): Watched => ({ key: row.key, value }))372 )373 );374375 const port: EnvPort = {376 onLanded: ({ after, before, now }, snapshot) =>377 Effect.gen(function* () {378 const live = Option.all({379 before,380 landed: landedIn(snapshot),381 policy: policyIn(snapshot),382 });383384 if (Option.isNone(live)) {385 return noPlan;386 }387388 const { landed, policy } = live.value;389 const was = yield* readAt(live.value.before, snapshot);390 const is = yield* readAt(after, snapshot);391 const decisions = new Map<DecisionId, Decision>();392393 for (const { hosts, item } of widenedProxies(was.schema, is.schema)) {394 const id = nextDecisionId(snapshot.decisions, decisions);395396 const evidence: readonly Evidence[] = [397 { label: "before", value: hostsText(reachIn(was.schema, item)) },398 { label: "after", value: hostsText(reachIn(is.schema, item)) },399 ];400401 decisions.set(402 id,403 openDecision({404 deciders: decidersOn(405 policy,406 [is.declaredIn.get(item) ?? rootSchema],407 landed.row.initializer408 ),409 evidence,410 expireDays: policy.budget.expireDays,411 id,412 now,413 project: landed.row.project,414 subject: DecisionSubject.cases.ProxyWidened.make({415 hosts,416 item,417 }),418 })419 );420 }421422 return {423 effects: [],424 writes: { decisions: [...decisions.values()] },425 };426 }),427 // A landed run would get the values opened; until the check job has428 // a field for them (611 adds it), a landed run sees the placeholders429 // too, and nothing here opens a value for any run.430 runEnv: (_landed, snapshot) =>431 Effect.map(landedRead(snapshot), ({ schema }) => {432 const sensitive = schema.items.filter((item) => item.sensitive);433434 return sensitive.length === 0435 ? noRunEnv436 : {437 placeholders: sensitive.map(({ key }) => key),438 proxies: sensitive.filter((item) => item.proxy !== undefined),439 };440 }),441 scan: (scanned, snapshot) =>442 Array.isReadonlyArrayEmpty(snapshot.envValues)443 ? Effect.succeedNone444 : Effect.map(watched(snapshot.envValues), (values) =>445 "text" in scanned446 ? scanText(scanned.text, values)447 : scanBytes(scanned.blob, values)448 ),449 set: ({ acknowledgeShort, by, key, now, value }, snapshot) =>450 Effect.gen(function* () {451 const policy = policyIn(snapshot);452453 if (!Option.exists(policy, (each) => maySet(each, by.handle))) {454 return yield* new NotDecider({});455 }456457 const { schema } = yield* landedRead(snapshot);458 const item = schema.items.find((each) => each.key === key);459460 if (item === undefined) {461 return yield* new UnknownEnvItem({ key });462 }463464 if (!item.sensitive) {465 return yield* new NotSensitive({ key });466 }467468 const sealed = yield* vault.put({ acknowledgeShort, key, value });469470 // Who set which item's value, for the platform's own logs, as the471 // public ledger says it: never the value.472 yield* Effect.logInfo("a write-only value was set").pipe(473 Effect.annotateLogs({ by: by.handle, key })474 );475476 const entry = LedgerEntry.cases.ValueSet.make({477 at: now,478 by: by.handle,479 key,480 seq: Math.max(0, ...snapshot.ledger.map(({ seq }) => seq)) + 1,481 });482483 return {484 result: { key, setAt: now, setBy: by.handle },485 writes: {486 envValues: [487 {488 key,489 sealed: yield* Effect.orDie(encodeSealed(sealed)),490 setAt: now,491 setBy: by.handle,492 },493 ],494 events: [ProjectEventInput.LedgerAppended({ at: now, entry })],495 ledger: [entry],496 },497 };498 }),499 view: (at, snapshot) =>500 Effect.map(readAt(at, snapshot), ({ schema }) => {501 const rows = new Map(snapshot.envValues.map((row) => [row.key, row]));502503 return {504 ...schema,505 items: schema.items.map((item) => withValue(item, rows)),506 };507 }),508 };509510 return port;511 })512);
added:packages/project/test/visibility/env.test.ts+835 added
1/**2 * The visibility cartridge's env (W6 614), through the project service over3 * memory adapters: datekit's env shape at the landed SHA, write-only values4 * a decider sets and nobody reads back, placeholders and proxies for checks5 * of unlanded code, the scan that finds a stored value, and the decision a6 * widened `@proxy` opens. The parser is the `/memory` fake holding datekit's7 * committed schema as `@env-spec/parser` reads it (a case below holds the8 * fake to the real parser), but where two landings must read two texts:9 * there the real adapter reads the committed text.10 */11import { describe, expect, it } from "@effect/vitest";12import { RefName, RepoHost } from "@repo/artifacts/repo-host";13import { Brand } from "@repo/brand";14import { Hostname } from "@repo/protocol/domain/common";15import { DecisionSubject } from "@repo/protocol/domain/decision";16import { EnvItem } from "@repo/protocol/domain/env";17import { ProjectEvent } from "@repo/protocol/domain/event";18import { Territory } from "@repo/protocol/domain/territory";19import { LedgerEntry } from "@repo/protocol/domain/visibility";20import {21 EnvKey,22 Handle,23 LandedSha,24 LaneName,25 RepoName,26 RepoPath,27 RequestId,28} from "@repo/protocol/ids";29import { Anonymous, Person } from "@repo/protocol/principal";30import {31 NotDecider,32 NotSensitive,33 UnknownEnvItem,34 ValueTooShort,35} from "@repo/protocol/refusal";36import { advanceTo, at } from "@repo/testkit/clock";37import type { Files } from "@repo/testkit/git-client";38import { aProject, withAsk } from "@repo/testkit/scenarios";39import type { Scenario } from "@repo/testkit/scenarios";40import { EnvSchemaParser } from "@repo/visibility/env-schema";41import type { ParsedEnvSchema } from "@repo/visibility/env-schema";42import { EnvSchemaParserEnvSpec } from "@repo/visibility/env-schema/env-spec";43import { EnvSchemaParserMemory } from "@repo/visibility/env-schema/memory";44import {45 admitLength,46 SealedValue,47 WriteOnlyValues,48} from "@repo/visibility/vault";49import { Context, Effect, Layer, Option, Redacted, Ref, Schema } from "effect";5051import datekitText from "../../../../examples/datekit/.env.schema?raw";52import { noRunEnv, ProjectEnv } from "../../src/env-port.ts";53import { ProjectStore } from "../../src/project-store.ts";54import { projectService } from "../../src/project.ts";55import type { ProjectApi } from "../../src/project.ts";56import {57 ProjectEnvLive,58 schemaFilesAt,59 widenedProxies,60} from "../../src/visibility/env.ts";61import { CheckScript, mergedAt, Pusher, worldOf } from "../world.ts";6263const scenario = aProject({ deciders: ["ines-v"], people: ["bram"] });6465const { project } = scenario;6667const repo = RepoName.make(project);6869const mainRef = RefName.make("refs/heads/main");7071const ines = Person.make({ handle: Handle.make("ines-v") });7273const bram = Person.make({ handle: Handle.make("bram") });7475const anyone = Anonymous.make({});7677const noon = at("2026-10-07T12:00:00Z");7879const token = EnvKey.make("SENTRY_AUTH_TOKEN");8081/** A token-shaped value of 20 characters: what ines-v sets. */82const value = "sntrys_eyJpYXQiOjE3M";8384const envFile = RepoPath.make(".env.schema");8586/** datekit's committed `.env.schema` (507), as `@env-spec/parser` reads it (through 603's adapter). */87const datekitParsed: ParsedEnvSchema = {88 header: [89 {90 name: "currentEnv",91 value: {92 fn: "ref",93 named: [],94 positional: ["APP_ENV"],95 text: "ref(APP_ENV)",96 },97 },98 { name: "defaultRequired", value: "infer" },99 { name: "defaultSensitive", value: false },100 ],101 imports: [],102 items: [103 {104 decorators: [105 {106 name: "type",107 value: {108 fn: "enum",109 named: [],110 positional: ["development", "test", "production"],111 text: "enum(development, test, production)",112 },113 },114 ],115 key: "APP_ENV",116 value: "development",117 },118 {119 decorators: [{ name: "type", value: "url" }],120 description: "Error reporting DSN. Public: it ships in builds.",121 key: "SENTRY_DSN",122 value: "https://public@o0.ingest.example.invalid/1",123 },124 {125 decorators: [126 { name: "sensitive", value: true },127 {128 name: "required",129 value: {130 fn: "forEnv",131 named: [],132 positional: ["production"],133 text: "forEnv(production)",134 },135 },136 { name: "tag", value: { named: [], positional: ["release"] } },137 {138 name: "proxy",139 value: {140 named: [141 { key: "domain", value: "sentry.io" },142 { key: "path", value: "/api/**" },143 ],144 positional: [],145 },146 },147 ],148 description:149 "Source-map upload token. Release step only; never enters a check.",150 key: "SENTRY_AUTH_TOKEN",151 },152 {153 decorators: [],154 description: "Where locale data lives.",155 key: "DATEKIT_LOCALE_DIR",156 value: "./locales",157 },158 ],159};160161const item = Schema.decodeUnknownSync(EnvItem);162163/** A package's schema beside datekit's: `APP_ENV` again, and a key of its own, the header silent. */164const weekParsed: ParsedEnvSchema = {165 header: [],166 imports: [],167 items: [168 { decorators: [], key: "APP_ENV", value: "test" },169 { decorators: [], key: "WEEK_API_KEY" },170 ],171};172173/** How many times the parser was asked to parse. */174class Parses extends Context.Service<175 Parses,176 { readonly count: Effect.Effect<number> }177>()("test/Parses") {}178179/** `inner`, counting its parses. */180const counting = (inner: Layer.Layer<EnvSchemaParser>) =>181 Layer.effectContext(182 Effect.gen(function* () {183 const parser = yield* EnvSchemaParser;184 const count = yield* Ref.make(0);185186 return Context.make(187 EnvSchemaParser,188 EnvSchemaParser.of({189 parse: (file, text) =>190 Effect.andThen(191 Ref.update(count, (n) => n + 1),192 parser.parse(file, text)193 ),194 })195 ).pipe(Context.add(Parses, { count: Ref.get(count) }));196 })197 ).pipe(Layer.provide(inner));198199/** datekit's one sensitive item, as the public sees it before any value. */200const sentryAuthToken = item({201 description:202 "Source-map upload token. Release step only; never enters a check.",203 key: "SENTRY_AUTH_TOKEN",204 proxy: { domains: ["sentry.io"], path: "/api/**" },205 required: "depends",206 sensitive: true,207 tags: ["release"],208});209210/** The project as ines-v first pushes it: a package and its env schema. */211const start = (schema: string): Files => [212 ["package.json", '{ "name": "datekit" }\n'],213 ["src/index.ts", "export const now = () => 0;\n"],214 [".env.schema", schema],215];216217const asBase64 = (text: string) =>218 Schema.encodeEffect(Schema.Uint8ArrayFromBase64)(219 new TextEncoder().encode(text)220 ).pipe(Effect.orDie);221222const fromBase64 = (text: string) =>223 Schema.decodeEffect(Schema.Uint8ArrayFromBase64)(text).pipe(224 Effect.orDie,225 Effect.map((bytes) => new TextDecoder().decode(bytes))226 );227228/**229 * A vault that seals in memory, with 610's length rules: the value stays in230 * the vault's own map and the sealed value only names it, so nothing the231 * store keeps holds it. 610's WebCrypto vault seals for the platform's test232 * (`apps/platform/test/visibility/env-values.test.ts`): under this233 * package's Node types its `crypto.subtle` calls do not typecheck (614's234 * Comments).235 */236const vault = Layer.sync(WriteOnlyValues, () => {237 const kept = new Map<string, Redacted.Redacted>();238239 return WriteOnlyValues.of({240 open: (sealed) =>241 Effect.flatMap(fromBase64(sealed.ciphertext), (id) =>242 Effect.orDie(Effect.fromNullishOr(kept.get(id)))243 ),244 put: (input) =>245 Effect.gen(function* () {246 yield* admitLength(input);247248 const id = `sealed-${kept.size + 1}`;249250 kept.set(id, input.value);251252 return {253 ciphertext: yield* asBase64(id),254 iv: yield* asBase64("iv"),255 keyVersion: 1,256 wrappedKey: yield* asBase64("wrapped"),257 };258 }),259 });260});261262/** The project's world over memory adapters, with the cartridge's env on `parser`. */263const worldWith = <More = never>(264 parser: Layer.Layer<EnvSchemaParser | More>,265 on: Scenario = scenario266) =>267 ProjectEnvLive.pipe(268 Layer.provide(vault),269 Layer.provideMerge(parser),270 Layer.provideMerge(worldOf(on, "memory"))271 );272273const world = worldWith(274 EnvSchemaParserMemory(new Map([[envFile, datekitParsed]]))275);276277/** ines-v makes datekit and pushes its first commit, holding `schema`. */278const begun = (schema: string = datekitText, more: Files = []) =>279 Effect.gen(function* () {280 yield* advanceTo("2026-10-07T12:00:00Z");281282 const api = yield* projectService(project);283284 yield* api.initProject(ines, {});285286 const first = yield* Pusher.use((pusher) =>287 pusher.push(repo, Option.none(), [...start(schema), ...more], "Start")288 );289290 yield* api.recordFirstPush(ines, first);291292 return api;293 });294295/** The token item of the shape anyone reads. */296const tokenItem = (api: ProjectApi) =>297 Effect.map(api.envShape(anyone), ({ items }) =>298 items.find(({ key }) => key === token)299 );300301const stored = ProjectStore.use((store) => store.load());302303describe("the env shape at the landed SHA", () => {304 // The fake above is written by hand; this holds it to datekit's committed305 // file as the real parser reads it, so a drift in either shows here.306 it.effect(307 "is read from datekit's committed .env.schema as the fake holds it",308 () =>309 Effect.gen(function* () {310 const parser = yield* EnvSchemaParser;311312 expect(yield* parser.parse(envFile, datekitText)).toStrictEqual(313 datekitParsed314 );315 }).pipe(Effect.provide(EnvSchemaParserEnvSpec))316 );317318 it.effect(319 "is empty where no schema can be read, so a decider's value is for an unknown item",320 () =>321 Effect.gen(function* () {322 const api = yield* begun();323 const shown = yield* api.envShape(anyone);324325 const refused = yield* Effect.flip(326 api.setEnv(ines, { key: token, value: Redacted.make(value) })327 );328329 const env = yield* ProjectEnv;330331 expect({332 file: shown.file,333 items: shown.items,334 refused,335 run: yield* env.runEnv({ landed: false }, yield* stored),336 stored: (yield* stored).envValues,337 }).toStrictEqual({338 file: envFile,339 items: [],340 refused: new UnknownEnvItem({ key: token }),341 run: noRunEnv,342 stored: [],343 });344 }).pipe(Effect.provide(worldWith(EnvSchemaParserMemory(new Map()))))345 );346347 it.effect(348 "lists datekit's four items, the token sensitive behind sentry.io and with no value",349 () =>350 Effect.gen(function* () {351 const api = yield* begun();352 const shown = yield* api.envShape(anyone);353354 expect({355 currentEnvKey: shown.currentEnvKey,356 file: shown.file,357 keys: shown.items.map(({ key }) => key),358 token: shown.items.find(({ key }) => key === token),359 }).toStrictEqual({360 currentEnvKey: "APP_ENV",361 file: envFile,362 keys: [363 "APP_ENV",364 "SENTRY_DSN",365 "SENTRY_AUTH_TOKEN",366 "DATEKIT_LOCALE_DIR",367 ],368 token: sentryAuthToken,369 });370 }).pipe(Effect.provide(world))371 );372373 it.effect(374 "reads the root's schema first, then each workspace package's, a key declared twice once",375 () =>376 Effect.gen(function* () {377 const api = yield* begun(datekitText, [378 ["packages/week/.env.schema", "APP_ENV=test\nWEEK_API_KEY=\n"],379 ["packages/week/src/week.ts", "export const week = () => 1;\n"],380 ]);381382 const shown = yield* api.envShape(anyone);383384 expect({385 currentEnvKey: shown.currentEnvKey,386 file: shown.file,387 keys: shown.items.map(({ key }) => key),388 week: shown.items.find(({ key }) => key === "WEEK_API_KEY"),389 }).toStrictEqual({390 currentEnvKey: "APP_ENV",391 file: envFile,392 keys: [393 "APP_ENV",394 "SENTRY_DSN",395 "SENTRY_AUTH_TOKEN",396 "DATEKIT_LOCALE_DIR",397 "WEEK_API_KEY",398 ],399 week: item({400 key: "WEEK_API_KEY",401 required: true,402 sensitive: true,403 tags: [],404 }),405 });406 }).pipe(407 Effect.provide(408 worldWith(409 EnvSchemaParserMemory(410 new Map([411 [envFile, datekitParsed],412 [RepoPath.make("packages/week/.env.schema"), weekParsed],413 ])414 ),415 scenario.pipe(416 withAsk({ id: "week-start", territory: "packages/week" })417 )418 )419 )420 )421 );422423 it.effect("parses a commit's schemas once, however often it is read", () =>424 Effect.gen(function* () {425 const api = yield* begun();426427 yield* api.envShape(anyone);428 yield* api.setEnv(ines, { key: token, value: Redacted.make(value) });429 yield* api.envShape(anyone);430 yield* api.scanForValues({ text: value });431432 expect(yield* Parses.use(({ count }) => count)).toBe(1);433 }).pipe(434 Effect.provide(435 worldWith(436 counting(EnvSchemaParserMemory(new Map([[envFile, datekitParsed]])))437 )438 )439 )440 );441});442443describe("a write-only value", () => {444 it.effect(445 "is set by a decider, shown as who and when, stored sealed, and recorded in the ledger",446 () =>447 Effect.gen(function* () {448 const api = yield* begun();449450 const set = yield* api.setEnv(ines, {451 key: token,452 value: Redacted.make(value),453 });454455 const shown = yield* tokenItem(api);456 const rows = yield* stored;457 const row = rows.envValues.find(({ key }) => key === token);458459 const sealed = yield* Schema.decodeUnknownEffect(SealedValue)(460 row?.sealed461 );462463 expect({464 ledger: rows.ledger,465 row: { setAt: row?.setAt, setBy: row?.setBy },466 set,467 }).toStrictEqual({468 ledger: [469 LedgerEntry.cases.ValueSet.make({470 at: noon,471 by: Handle.make("ines-v"),472 key: token,473 seq: 1,474 }),475 ],476 row: { setAt: noon, setBy: "ines-v" },477 set: { key: token, setAt: noon, setBy: "ines-v" },478 });479 expect(shown).toStrictEqual({480 ...sentryAuthToken,481 value: { setAt: noon, setBy: "ines-v" },482 });483 expect(484 `${Object.values(sealed).join(" ")} ${JSON.stringify(rows.envValues)}`485 ).not.toContain(value);486 }).pipe(Effect.provide(world))487 );488489 it.effect(490 "appends the ledger entry as an event, and no event holds the value",491 () =>492 Effect.gen(function* () {493 const api = yield* begun();494495 yield* api.setEnv(ines, { key: token, value: Redacted.make(value) });496497 const events = yield* ProjectStore.use((store) =>498 store.eventsSince(0, 100)499 );500501 const appended = events.flatMap(({ event }) =>502 ProjectEvent.guards.LedgerAppended(event) ? [event.entry] : []503 );504505 expect(appended).toStrictEqual([506 LedgerEntry.cases.ValueSet.make({507 at: noon,508 by: Handle.make("ines-v"),509 key: token,510 seq: 1,511 }),512 ]);513 expect(JSON.stringify(events)).not.toContain(value);514 }).pipe(Effect.provide(world))515 );516517 it.effect(518 "is refused to a non-decider, for an item not sensitive or unknown, and when too short",519 () =>520 Effect.gen(function* () {521 const api = yield* begun();522523 const refused = (524 who: Person,525 key: string,526 text: string,527 acknowledgeShort = false528 ) =>529 Effect.flip(530 api.setEnv(who, {531 acknowledgeShort,532 key: EnvKey.make(key),533 value: Redacted.make(text),534 })535 );536537 const got = {538 byBram: yield* refused(bram, "SENTRY_AUTH_TOKEN", value),539 notSensitive: yield* refused(ines, "APP_ENV", value),540 shortAcknowledged: yield* refused(541 ines,542 "SENTRY_AUTH_TOKEN",543 "ab",544 true545 ),546 tooShort: yield* refused(ines, "SENTRY_AUTH_TOKEN", "abcdefgh"),547 unknown: yield* refused(ines, "NOPE", value),548 };549550 expect(got).toStrictEqual({551 byBram: new NotDecider({}),552 notSensitive: new NotSensitive({ key: EnvKey.make("APP_ENV") }),553 shortAcknowledged: new ValueTooShort({554 key: token,555 minimum: 3,556 next: `${Brand.cli} env set SENTRY_AUTH_TOKEN`,557 }),558 tooShort: ValueTooShort.of(token, 12),559 unknown: new UnknownEnvItem({ key: EnvKey.make("NOPE") }),560 });561562 const acknowledged = yield* api.setEnv(ines, {563 acknowledgeShort: true,564 key: token,565 value: Redacted.make("abcdefgh"),566 });567568 expect(acknowledged.setBy).toBe("ines-v");569 expect((yield* stored).envValues.map(({ key }) => key)).toStrictEqual([570 token,571 ]);572 }).pipe(Effect.provide(world))573 );574});575576describe("the env a check of unlanded code runs with", () => {577 it.effect(578 "names a placeholder for every sensitive item and the @proxy items, and holds no value",579 () =>580 Effect.gen(function* () {581 const api = yield* begun();582583 yield* api.setEnv(ines, { key: token, value: Redacted.make(value) });584585 const env = yield* ProjectEnv;586 const run = yield* env.runEnv({ landed: false }, yield* stored);587588 expect(run).toStrictEqual({589 placeholders: [token],590 proxies: [sentryAuthToken],591 });592 expect(JSON.stringify(run)).not.toContain(value);593 }).pipe(Effect.provide(world))594 );595});596597describe("the scan for stored values", () => {598 it.effect(599 "finds a stored value in a text or a blob by its item, and never the placeholder",600 () =>601 Effect.gen(function* () {602 const api = yield* begun();603604 yield* api.setEnv(ines, { key: token, value: Redacted.make(value) });605606 expect({607 blob: yield* api.scanForValues({608 blob: new TextEncoder().encode(`SENTRY_AUTH_TOKEN=${value}\n`),609 }),610 placeholder: yield* api.scanForValues({611 text: "Authorization: Bearer __SENTRY_AUTH_TOKEN_PLACEHOLDER__",612 }),613 text: yield* api.scanForValues({614 text: `uploading with ${value} to sentry.io`,615 }),616 }).toStrictEqual({617 blob: Option.some(token),618 placeholder: Option.none(),619 text: Option.some(token),620 });621 }).pipe(Effect.provide(world))622 );623});624625/** datekit's schema with the token behind `proxy`'s argument list. */626const proxied = (proxy: string) =>627 [628 "# @defaultSensitive=false",629 "# ---",630 "# @type=enum(development, test, production)",631 "APP_ENV=development",632 "",633 "# @sensitive",634 `# @proxy(${proxy})`,635 "SENTRY_AUTH_TOKEN=",636 "",637 ].join("\n");638639const narrow = proxied('domain="sentry.io"');640641const wide = proxied('domain=["sentry.io", "upload.example.invalid"]');642643/** Where a repo's `main` stands now. */644const tipOf = (name: RepoName) =>645 Effect.gen(function* () {646 const refs = yield* (yield* RepoHost).refs(name).pipe(Effect.orDie);647648 return LandedSha.make(649 Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))650 );651 });652653/**654 * ines-v lands `schema` as datekit's `.env.schema` from her working fork,655 * its checks passing on the merge.656 */657const landSchema = (api: ProjectApi, schema: string, requestId: string) =>658 Effect.gen(function* () {659 const { fork } = yield* api.fork(ines);660 const base = yield* tipOf(fork);661 const main = yield* tipOf(repo);662663 const head = yield* Pusher.use((pusher) =>664 pusher.push(fork, Option.some(base), start(schema), "Change the env")665 );666667 const merged = yield* mergedAt({ base, fork, head, main, repo });668669 yield* CheckScript.use((checker) =>670 Effect.forEach(671 [LaneName.make("lint"), LaneName.make("types")],672 (lane) => checker.script(merged, lane, ["passed"]),673 { discard: true }674 )675 );676677 yield* api.land(ines, {678 base,679 head,680 message: "Change the env",681 requestId: RequestId.make(requestId),682 });683684 return yield* tipOf(repo);685 });686687/** The `ProxyWidened` decisions on ines-v's Today, with their evidence. */688const widenings = (api: ProjectApi) =>689 Effect.map(api.today(ines), ({ decisions }) =>690 decisions.flatMap(({ evidence, subject }) =>691 DecisionSubject.guards.ProxyWidened(subject)692 ? [{ evidence, subject }]693 : []694 )695 );696697describe("a landing that widens a @proxy", () => {698 const read = worldWith(EnvSchemaParserEnvSpec);699700 it.effect(701 "opens a ProxyWidened decision on Today with the hosts before and after; narrowing opens none",702 () =>703 Effect.gen(function* () {704 const api = yield* begun(narrow);705 const before = yield* tipOf(repo);706 const widened = yield* landSchema(api, wide, "land-wide");707 const afterWidening = yield* widenings(api);708709 yield* landSchema(api, narrow, "land-narrow");710711 expect(widened).not.toBe(before);712 expect(afterWidening).toStrictEqual([713 {714 evidence: [715 { label: "before", value: "sentry.io" },716 { label: "after", value: "sentry.io, upload.example.invalid" },717 ],718 subject: DecisionSubject.cases.ProxyWidened.make({719 hosts: [720 Hostname.make("sentry.io"),721 Hostname.make("upload.example.invalid"),722 ],723 item: token,724 }),725 },726 ]);727 expect(yield* widenings(api)).toStrictEqual(afterWidening);728 }).pipe(Effect.provide(read))729 );730});731732const territory = Schema.decodeUnknownSync(Territory);733734describe("where the env schemas live", () => {735 it("is the repo's root, then each workspace package's folder, once each", () => {736 expect(737 schemaFilesAt([738 territory({ module: "week", paths: ["packages/week/**"] }),739 territory({740 module: "format",741 paths: ["packages/format/**", "packages/format/README.md"],742 }),743 territory({ module: "again", paths: ["packages/week/src/**"] }),744 ])745 ).toStrictEqual([746 ".env.schema",747 "packages/week/.env.schema",748 "packages/format/.env.schema",749 "packages/week/src/.env.schema",750 ]);751 });752753 it("is the root alone for a single-package repo", () => {754 expect(755 schemaFilesAt([territory({ module: ".", paths: ["**"] })])756 ).toStrictEqual([".env.schema"]);757 expect(schemaFilesAt([])).toStrictEqual([".env.schema"]);758 });759});760761/** An item behind `@proxy` on `domains`, sensitive as every proxied item is. */762const behind = (763 key: string,764 domains: readonly [string, ...string[]],765 block?: boolean766) =>767 item({768 key,769 proxy: block === undefined ? { domains } : { block, domains },770 required: true,771 sensitive: true,772 tags: [],773 });774775describe("a widened proxy", () => {776 it("is an item whose value may reach a host it could not before, with every host it may reach", () => {777 expect(778 widenedProxies(779 { items: [behind("SENTRY_AUTH_TOKEN", ["sentry.io"])] },780 {781 items: [782 behind("SENTRY_AUTH_TOKEN", [783 "sentry.io",784 "upload.example.invalid",785 ]),786 behind("NPM_TOKEN", ["registry.npmjs.org"]),787 ],788 }789 )790 ).toStrictEqual([791 {792 hosts: ["sentry.io", "upload.example.invalid"],793 item: "SENTRY_AUTH_TOKEN",794 },795 { hosts: ["registry.npmjs.org"], item: "NPM_TOKEN" },796 ]);797 });798799 it("is an unblocked rule that was blocked", () => {800 expect(801 widenedProxies(802 { items: [behind("SENTRY_AUTH_TOKEN", ["sentry.io"], true)] },803 { items: [behind("SENTRY_AUTH_TOKEN", ["sentry.io"])] }804 )805 ).toStrictEqual([{ hosts: ["sentry.io"], item: "SENTRY_AUTH_TOKEN" }]);806 });807808 it("is never a narrowing, an unchanged rule, a newly blocked one, or a dropped item", () => {809 const both = behind("SENTRY_AUTH_TOKEN", [810 "sentry.io",811 "upload.example.invalid",812 ]);813814 expect([815 widenedProxies(816 { items: [both] },817 { items: [behind("SENTRY_AUTH_TOKEN", ["sentry.io"])] }818 ),819 widenedProxies({ items: [both] }, { items: [both] }),820 widenedProxies(821 { items: [both] },822 {823 items: [824 behind(825 "SENTRY_AUTH_TOKEN",826 ["sentry.io", "upload.example.invalid", "evil.example"],827 true828 ),829 ],830 }831 ),832 widenedProxies({ items: [both] }, { items: [] }),833 ]).toStrictEqual([[], [], [], []]);834 });835});
added:packages/project/test/visibility/raw.d.ts+5 added