Skip to content
Myr

env.ts

This file

Path

packages/project/src/visibility/env.ts

475 lines · 14.0 KiB · TypeScript

Last changed by

Merge build/comments-project into mainoscabrielbefore adoption49efd2a

History of this file

Take it

1import { RepoHost, Revision } from "@repo/artifacts/repo-host";2import type { EnvProxy } from "@repo/checks/check-runner";3import { Hostname } from "@repo/protocol/domain/common";4import type { Evidence } from "@repo/protocol/domain/common";5import { DecisionSubject } from "@repo/protocol/domain/decision";6import type { Decision } from "@repo/protocol/domain/decision";7import type { EnvItem, EnvSchemaView } from "@repo/protocol/domain/env";8import type { Policy } from "@repo/protocol/domain/policy";9import type { Territory } from "@repo/protocol/domain/territory";10import { LedgerEntry } from "@repo/protocol/domain/visibility";11import { keyOf, RepoName, RepoPath, sameHandle } from "@repo/protocol/ids";12import type {13  DecisionId,14  EnvKey,15  Handle,16  LandedSha,17  ProjectName,18} from "@repo/protocol/ids";19import {20  NotDecider,21  NotSensitive,22  UnknownEnvItem,23} from "@repo/protocol/refusal";24import { EnvSchemaParser } from "@repo/visibility/env-schema";25import { envSchemaViewOf } from "@repo/visibility/env-shape";26import { scanBytes, scanText } from "@repo/visibility/leak-scan";27import type { Watched } from "@repo/visibility/leak-scan";28import { placeholderFor, proxyMap } from "@repo/visibility/proxy";29import type { ProxyRule } from "@repo/visibility/proxy";30import { SealedValue, WriteOnlyValues } from "@repo/visibility/vault";31import {32  Array,33  Cache,34  Data,35  Duration,36  Effect,37  Exit,38  Layer,39  Option,40  Schema,41} from "effect";4243import { openDecision } from "../attention/decisions.ts";44import { decidersOn, isDecider, nextDecisionId } from "../deciders.ts";45import { noRunEnv, ProjectEnv } from "../env-port.ts";46import type { EnvPort, EnvSchemaFile } from "../env-port.ts";47import { ProjectEventInput } from "../events.ts";48import type { ProjectSnapshot } from "../project-store.ts";49import type { EnvValueRow } from "../project-store/rows.ts";50import { noPlan, policyIn } from "../visibility-port.ts";5152const schemaName = ".env.schema";5354const rootSchema = RepoPath.make(schemaName);5556const GLOB = /[*?[{]/u;5758const folderOf = (glob: string): string => {59  const segments = glob60    .split("/")61    .filter((segment) => segment !== "" && segment !== ".");6263  const fixed = Array.takeWhile(segments, (segment) => !GLOB.test(segment));6465  return (fixed.length === segments.length ? fixed.slice(0, -1) : fixed).join(66    "/"67  );68};6970export const schemaFilesAt = (71  modules: readonly Territory[]72): readonly RepoPath[] =>73  Array.dedupe([74    schemaName,75    ...modules.flatMap(({ paths }) =>76      paths.flatMap((glob) => {77        const folder = folderOf(glob);7879        return folder === "" ? [] : [`${folder}/${schemaName}`];80      })81    ),82  ]).map((path) => RepoPath.make(path));8384const covers = (pattern: string, host: string) =>85  pattern === host ||86  (pattern.startsWith("*.") && host.endsWith(pattern.slice(1)));8788/** Only a sensitive item holds a value, so any other reaches no host. */89const reachOf = (item: EnvItem | undefined): readonly string[] =>90  item?.sensitive === true &&91  item.proxy !== undefined &&92  item.proxy.block !== true93    ? Array.dedupe(item.proxy.domains.map((host) => host.toLowerCase()))94    : [];9596const reachIn = (view: Pick<EnvSchemaView, "items">, key: EnvKey) =>97  reachOf(view.items.find((item) => item.key === key));9899export interface Widened {100  readonly hosts: readonly Hostname[];101  readonly item: EnvKey;102}103104export const widenedProxies = (105  before: Pick<EnvSchemaView, "items">,106  after: Pick<EnvSchemaView, "items">107): readonly Widened[] =>108  after.items.flatMap((item) => {109    const was = reachIn(before, item.key);110    const reach = reachOf(item);111112    return reach.some((host) => !was.some((each) => covers(each, host)))113      ? [{ hosts: reach.filter(Schema.is(Hostname)), item: item.key }]114      : [];115  });116117class ReadAt extends Data.Class<{118  readonly at: LandedSha;119  readonly files: readonly RepoPath[];120  readonly project: ProjectName;121}> {}122123interface Read {124  readonly declaredIn: ReadonlyMap<EnvKey, RepoPath>;125  readonly schema: EnvSchemaFile;126}127128const unread: Read = {129  declaredIn: new Map(),130  schema: { file: rootSchema, imports: [], items: [] },131};132133const readCapacity = 16;134135/** The first schema to declare a key holds it. */136const merged = (views: readonly EnvSchemaView[]): Read => {137  const [first] = views;138139  if (first === undefined) {140    return unread;141  }142143  const declaredIn = new Map<EnvKey, RepoPath>();144  const items: EnvItem[] = [];145146  for (const view of views) {147    for (const item of view.items) {148      if (!declaredIn.has(item.key)) {149        declaredIn.set(item.key, view.file);150        items.push(item);151      }152    }153  }154155  const currentEnv = Array.findFirst(views, (view) =>156    Option.fromUndefinedOr(view.currentEnvKey)157  );158159  return {160    declaredIn,161    schema: {162      file: first.file,163      imports: Array.dedupe(views.flatMap(({ imports }) => imports)),164      items,165      ...(Option.isSome(currentEnv) && { currentEnvKey: currentEnv.value }),166    },167  };168};169170const landedIn = (snapshot: ProjectSnapshot) =>171  Option.flatMap(snapshot.project, (row) =>172    row.landed === undefined173      ? Option.none()174      : Option.some({ landed: row.landed, row })175  );176177const maySet = (policy: Policy, handle: Handle) => {178  const setters = policy.visibility?.env.setters ?? "deciders";179180  return setters === "deciders"181    ? isDecider(policy, handle)182    : setters.some((each) => sameHandle(each, handle));183};184185const withValue = (186  item: EnvItem,187  rows: ReadonlyMap<EnvKey, EnvValueRow>188): EnvItem => {189  const row = rows.get(item.key);190191  return item.sensitive && row !== undefined192    ? { ...item, value: { setAt: row.setAt, setBy: row.setBy } }193    : item;194};195196const encodeSealed = Schema.encodeEffect(Schema.toCodecJson(SealedValue));197198const decodeSealed = Schema.decodeUnknownEffect(199  Schema.toCodecJson(SealedValue)200);201202/** The check job's wire takes no empty method or path. */203const nonEmpty = (text: Option.Option<string>) =>204  Option.getOrUndefined(Option.filter(text, (each) => each !== ""));205206const onTheWire = (rule: ProxyRule): EnvProxy => {207  const method = nonEmpty(rule.method);208  const path = nonEmpty(rule.path);209210  return {211    block: rule.block,212    host: rule.host,213    key: rule.key,214    placeholder: rule.placeholder,215    ...(method !== undefined && { method }),216    ...(path !== undefined && { path }),217  };218};219220const hostsText = (hosts: readonly string[]) =>221  hosts.length === 0 ? "none" : hosts.join(", ");222223export const ProjectEnvLive: Layer.Layer<224  never,225  never,226  EnvSchemaParser | WriteOnlyValues | RepoHost227> = Layer.effect(228  ProjectEnv,229  Effect.gen(function* () {230    const parser = yield* EnvSchemaParser;231    const vault = yield* WriteOnlyValues;232    const host = yield* RepoHost;233234    const viewOf = (key: ReadAt, file: RepoPath) =>235      host236        .readFile(237          RepoName.make(keyOf(key.project)),238          Revision.Commit({ sha: key.at }),239          file240        )241        .pipe(242          Effect.orDie,243          Effect.flatMap(244            Option.match({245              onNone: () => Effect.succeedNone,246              onSome: (bytes) =>247                parser.parse(file, new TextDecoder().decode(bytes)).pipe(248                  Effect.map((parsed) =>249                    Option.some(250                      envSchemaViewOf({251                        at: key.at,252                        file,253                        parsed,254                        project: key.project,255                      })256                    )257                  ),258                  Effect.catchTag("EnvSchemaUnreadable", ({ reason }) =>259                    Effect.as(260                      Effect.logWarning(261                        `the env schema ${file} at ${key.at} cannot be read: ${reason}`262                      ),263                      Option.none<EnvSchemaView>()264                    )265                  )266                ),267            })268          )269        );270271    // A landed commit's schemas never change; a failed read is not kept.272    const reads = yield* Cache.makeWith(273      (key: ReadAt) =>274        Effect.map(275          Effect.forEach(key.files, (file) => viewOf(key, file)),276          (views) => merged(Array.getSomes(views))277        ),278      {279        capacity: readCapacity,280        timeToLive: (exit) =>281          Exit.isSuccess(exit) ? Duration.infinity : Duration.zero,282      }283    );284285    const readAt = (at: LandedSha, snapshot: ProjectSnapshot) =>286      Option.match(snapshot.project, {287        onNone: () => Effect.succeed(unread),288        onSome: (row) =>289          Cache.get(290            reads,291            new ReadAt({292              at,293              files: schemaFilesAt(294                Option.match(policyIn(snapshot), {295                  onNone: () => [],296                  onSome: ({ modules }) => modules,297                })298              ),299              project: row.project,300            })301          ),302      });303304    const landedRead = (snapshot: ProjectSnapshot) =>305      Option.match(landedIn(snapshot), {306        onNone: () => Effect.succeed(unread),307        onSome: ({ landed }) => readAt(landed, snapshot),308      });309310    /** Opened values to scan for; dropped when the scan ends. */311    const watched = (rows: readonly EnvValueRow[]) =>312      Effect.forEach(rows, (row) =>313        decodeSealed(row.sealed).pipe(314          Effect.orDie,315          Effect.flatMap(vault.open),316          Effect.map((value): Watched => ({ key: row.key, value }))317        )318      );319320    const port: EnvPort = {321      onLanded: ({ after, before, now }, snapshot) =>322        Effect.gen(function* () {323          const live = Option.all({324            before,325            landed: landedIn(snapshot),326            policy: policyIn(snapshot),327          });328329          if (Option.isNone(live)) {330            return noPlan;331          }332333          const { landed, policy } = live.value;334          const was = yield* readAt(live.value.before, snapshot);335          const is = yield* readAt(after, snapshot);336          const decisions = new Map<DecisionId, Decision>();337338          for (const { hosts, item } of widenedProxies(was.schema, is.schema)) {339            const id = nextDecisionId(snapshot.decisions, decisions);340341            const evidence: readonly Evidence[] = [342              { label: "before", value: hostsText(reachIn(was.schema, item)) },343              { label: "after", value: hostsText(reachIn(is.schema, item)) },344            ];345346            decisions.set(347              id,348              openDecision({349                deciders: decidersOn(350                  policy,351                  [is.declaredIn.get(item) ?? rootSchema],352                  landed.row.initializer353                ),354                evidence,355                expireDays: policy.budget.expireDays,356                id,357                now,358                project: landed.row.project,359                subject: DecisionSubject.cases.ProxyWidened.make({360                  hosts,361                  item,362                }),363              })364            );365          }366367          return {368            effects: [],369            writes: { decisions: [...decisions.values()] },370          };371        }),372      // Only a run of landed code carries the values; the sandbox's env373      // gateway swaps them in on the way out.374      runEnv: ({ landed }, snapshot) =>375        Effect.gen(function* () {376          const { schema } = yield* landedRead(snapshot);377          const sensitive = schema.items.filter((item) => item.sensitive);378379          if (sensitive.length === 0) {380            return noRunEnv;381          }382383          const unlanded = {384            placeholders: sensitive.map((item) => ({385              key: item.key,386              placeholder: placeholderFor(item),387            })),388            proxies: proxyMap(schema).map(onTheWire),389          };390391          if (!landed) {392            return unlanded;393          }394395          const keys = new Set(sensitive.map(({ key }) => key));396397          return {398            ...unlanded,399            landed,400            values: yield* watched(401              snapshot.envValues.filter((row) => keys.has(row.key))402            ),403          };404        }),405      scan: (scanned, snapshot) =>406        Array.isReadonlyArrayEmpty(snapshot.envValues)407          ? Effect.succeedNone408          : Effect.map(watched(snapshot.envValues), (values) =>409              "text" in scanned410                ? scanText(scanned.text, values)411                : scanBytes(scanned.blob, values)412            ),413      set: ({ acknowledgeShort, by, key, now, value }, snapshot) =>414        Effect.gen(function* () {415          const policy = policyIn(snapshot);416417          if (!Option.exists(policy, (each) => maySet(each, by.handle))) {418            return yield* new NotDecider({});419          }420421          const { schema } = yield* landedRead(snapshot);422          const item = schema.items.find((each) => each.key === key);423424          if (item === undefined) {425            return yield* new UnknownEnvItem({ key });426          }427428          if (!item.sensitive) {429            return yield* new NotSensitive({ key });430          }431432          const sealed = yield* vault.put({ acknowledgeShort, key, value });433434          // Never the value.435          yield* Effect.logInfo("a write-only value was set").pipe(436            Effect.annotateLogs({ by: by.handle, key })437          );438439          const entry = LedgerEntry.cases.ValueSet.make({440            at: now,441            by: by.handle,442            key,443            seq: Math.max(0, ...snapshot.ledger.map(({ seq }) => seq)) + 1,444          });445446          return {447            result: { key, setAt: now, setBy: by.handle },448            writes: {449              envValues: [450                {451                  key,452                  sealed: yield* Effect.orDie(encodeSealed(sealed)),453                  setAt: now,454                  setBy: by.handle,455                },456              ],457              events: [ProjectEventInput.LedgerAppended({ at: now, entry })],458              ledger: [entry],459            },460          };461        }),462      view: (at, snapshot) =>463        Effect.map(readAt(at, snapshot), ({ schema }) => {464          const rows = new Map(snapshot.envValues.map((row) => [row.key, row]));465466          return {467            ...schema,468            items: schema.items.map((item) => withValue(item, rows)),469          };470        }),471    };472473    return port;474  })475);