@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 624 lines 20.9 KB
Raw
1 import { describe, expect, it } from "@alchemy.run/test";
2 import * as TestCore from "@alchemy.run/test/Core";
3 import * as Config from "effect/Config";
4 import type { ConfigError } from "effect/Config";
5 import * as ConfigProvider from "effect/ConfigProvider";
6 import * as Effect from "effect/Effect";
7 import * as FileSystem from "effect/FileSystem";
8 import * as Layer from "effect/Layer";
9 import * as Logger from "effect/Logger";
10 import * as Option from "effect/Option";
11 import * as PlatformError from "effect/PlatformError";
12 import { MinimumLogLevel } from "effect/References";
13 import { evalStack } from "@/EvalStack.ts";
14 import {
15 AlchemyContext,
16 Secrets,
17 Stack,
18 Stage,
19 inMemoryState,
20 type SecretProviders,
21 type StackSecrets,
22 } from "@/index.ts";
23 import { loadConfigProvider } from "@/Util/ConfigProvider.ts";
24
25 const files = (contents: Record<string, string>) =>
26 FileSystem.layerNoop({
27 exists: (path) => Effect.succeed(path in contents),
28 readFileString: (path) =>
29 path in contents
30 ? Effect.succeed(contents[path])
31 : Effect.fail(
32 PlatformError.systemError({
33 _tag: "NotFound",
34 module: "FileSystem",
35 method: "readFileString",
36 pathOrDescriptor: path,
37 }),
38 ),
39 });
40
41 /**
42 * Run with the real process environment temporarily changed; `undefined`
43 * removes a variable. Tests using this must be `{ exclusive: true }`.
44 */
45 const withProcessEnv = <A, E, R>(
46 values: Record<string, string | undefined>,
47 effect: Effect.Effect<A, E, R>,
48 ) =>
49 Effect.acquireRelease(
50 Effect.sync(() => {
51 const previous = Object.fromEntries(
52 Object.keys(values).map((key) => [key, process.env[key]]),
53 );
54 for (const [key, value] of Object.entries(values)) {
55 if (value === undefined) delete process.env[key];
56 else process.env[key] = value;
57 }
58 return previous;
59 }),
60 (previous) =>
61 Effect.sync(() => {
62 for (const [key, value] of Object.entries(previous)) {
63 if (value === undefined) delete process.env[key];
64 else process.env[key] = value;
65 }
66 }),
67 ).pipe(Effect.andThen(effect));
68
69 /** Build a stack with the given `secrets` and return its output. */
70 const runStack = <A>(
71 name: string,
72 secrets: StackSecrets | undefined,
73 body: Effect.Effect<A, ConfigError>,
74 ) =>
75 Stack(name, { providers: Layer.empty, state: inMemoryState(), secrets }, body).pipe(
76 Effect.map((stack) => stack.output),
77 Effect.provideService(AlchemyContext, {
78 dotAlchemy: ".alchemy",
79 dev: false,
80 adopt: false,
81 }),
82 );
83
84 /** Run under a stage and a fake file system. */
85 const withFiles = <A, E, R>(
86 contents: Record<string, string>,
87 effect: Effect.Effect<A, E, R>,
88 stage = "test",
89 ) =>
90 effect.pipe(Effect.provideService(Stage, stage), Effect.provide(files(contents)), Effect.scoped);
91
92 const values = Effect.all({
93 value: Config.String("ALCHEMY_DOTENV_TEST_VALUE"),
94 fallback: Config.String("ALCHEMY_DOTENV_TEST_FALLBACK"),
95 empty: Config.String("ALCHEMY_DOTENV_TEST_EMPTY"),
96 });
97
98 describe("stack secrets", { tags: ["unit", "local"] }, () => {
99 it.effect("scratch deploys and plans retain per-call config overrides", () =>
100 TestCore.toEffect(
101 Effect.gen(function* () {
102 const stack = TestCore.scratchStack({ providers: Layer.empty }, "scratch-config-overrides");
103 const read = Config.String("ALCHEMY_SCRATCH_CONFIG_VALUE");
104 yield* stack.destroy();
105 for (const value of ["first", "second"]) {
106 const config = ConfigProvider.fromEnv({
107 env: { ALCHEMY_SCRATCH_CONFIG_VALUE: value },
108 });
109 expect(
110 yield* stack
111 .deploy(read)
112 .pipe(Effect.provideService(ConfigProvider.ConfigProvider, config)),
113 ).toBe(value);
114 yield* stack
115 .plan(
116 read.pipe(
117 Effect.tap((actual) =>
118 Effect.sync(() => {
119 expect(actual).toBe(value);
120 }),
121 ),
122 ),
123 )
124 .pipe(Effect.provideService(ConfigProvider.ConfigProvider, config));
125 }
126 yield* stack.destroy();
127 }),
128 { providers: Layer.empty, state: inMemoryState() },
129 ),
130 );
131
132 it.effect("the CLI loads .env without mutating process.env when secrets is omitted", () => {
133 const before = process.env.ALCHEMY_DOTENV_TEST_VALUE;
134 return withFiles(
135 { ".env": "ALCHEMY_DOTENV_TEST_VALUE=default" },
136 loadConfigProvider(Option.none()).pipe(
137 Effect.flatMap((config) =>
138 runStack("dotenv-default", undefined, Config.String("ALCHEMY_DOTENV_TEST_VALUE")).pipe(
139 Effect.provideService(ConfigProvider.ConfigProvider, config),
140 ),
141 ),
142 Effect.map((output) => {
143 expect(output).toBe("default");
144 expect(process.env.ALCHEMY_DOTENV_TEST_VALUE).toBe(before);
145 }),
146 ),
147 );
148 });
149
150 it.effect("omitting secrets preserves the caller's complete ConfigProvider", () =>
151 withFiles(
152 { ".env": "ALCHEMY_DOTENV_TEST_FALLBACK=must-not-be-loaded" },
153 runStack(
154 "inherited-config",
155 undefined,
156 Effect.all({
157 value: Config.String("ALCHEMY_DOTENV_TEST_VALUE"),
158 profile: Config.String("ALCHEMY_PROFILE"),
159 absent: Config.String("ALCHEMY_DOTENV_TEST_FALLBACK").pipe(Config.option),
160 }),
161 ).pipe(
162 Effect.provideService(
163 ConfigProvider.ConfigProvider,
164 ConfigProvider.fromUnknown({
165 ALCHEMY_DOTENV_TEST_VALUE: "injected",
166 ALCHEMY_PROFILE: "injected-profile",
167 }),
168 ),
169 Effect.map((output) => {
170 expect(output.value).toBe("injected");
171 expect(output.profile).toBe("injected-profile");
172 expect(Option.isNone(output.absent)).toBe(true);
173 }),
174 ),
175 ),
176 );
177
178 it.effect("ignores a missing default .env", () =>
179 withFiles(
180 {},
181 runStack("dotenv-missing-default", undefined, Effect.succeed("ok")).pipe(
182 Effect.map((output) => expect(output).toBe("ok")),
183 ),
184 ),
185 );
186
187 it.effect("isolates stage-specific config when stacks share a secrets layer", () => {
188 const source = Secrets.DotEnv(({ stage }) => ({ path: `${stage}.env` }));
189 const stack = runStack(
190 "dotenv-isolation",
191 [source],
192 Config.String("ALCHEMY_DOTENV_TEST_VALUE"),
193 );
194 return Effect.all(
195 [
196 stack.pipe(Effect.provideService(Stage, "dev")),
197 stack.pipe(Effect.provideService(Stage, "prod")),
198 ],
199 { concurrency: "unbounded" },
200 ).pipe(
201 Effect.map((outputs) => expect(outputs).toEqual(["dev", "prod"])),
202 Effect.provide(
203 files({
204 "dev.env": "ALCHEMY_DOTENV_TEST_VALUE=dev",
205 "prod.env": "ALCHEMY_DOTENV_TEST_VALUE=prod",
206 }),
207 ),
208 Effect.scoped,
209 );
210 });
211
212 it.effect("loads ordered path arrays from plain and stage-based options", () =>
213 withFiles(
214 {
215 "base.env":
216 "ALCHEMY_DOTENV_TEST_VALUE=base\nALCHEMY_DOTENV_TEST_FALLBACK=base\nALCHEMY_DOTENV_TEST_EMPTY=base",
217 "prod.env": "ALCHEMY_DOTENV_TEST_VALUE=prod\nALCHEMY_DOTENV_TEST_EMPTY=",
218 },
219 Effect.gen(function* () {
220 for (const source of [
221 Secrets.DotEnv({ path: ["base.env", "prod.env"] }),
222 Secrets.DotEnv(({ stage }) => ({
223 path: ["base.env", `${stage}.env`] as const,
224 })),
225 ]) {
226 expect(yield* runStack("dotenv-paths", [source], values)).toEqual({
227 value: "prod",
228 fallback: "base",
229 empty: "",
230 });
231 }
232 }),
233 "prod",
234 ),
235 );
236
237 it.effect("secrets may be a single provider, a list, or a callback picking either", () => {
238 const seen: Array<{ stack: string; dev: boolean }> = [];
239 const stack = runStack(
240 "secrets-by-stage",
241 ({ stage, stack, alchemyContext }) => {
242 seen.push({ stack: stack.name, dev: alchemyContext.dev });
243 return stage === "dev"
244 ? Secrets.DotEnv({ path: "dev.env" })
245 : [Secrets.DotEnv({ path: "other.env" })];
246 },
247 Config.String("ALCHEMY_DOTENV_TEST_VALUE"),
248 );
249 return Effect.all([
250 stack.pipe(Effect.provideService(Stage, "dev")),
251 stack.pipe(Effect.provideService(Stage, "prod")),
252 ]).pipe(
253 Effect.map((outputs) => {
254 expect(outputs).toEqual(["dev", "other"]);
255 expect(seen).toEqual([
256 { stack: "secrets-by-stage", dev: false },
257 { stack: "secrets-by-stage", dev: false },
258 ]);
259 }),
260 Effect.provide(
261 files({
262 "dev.env": "ALCHEMY_DOTENV_TEST_VALUE=dev",
263 "other.env": "ALCHEMY_DOTENV_TEST_VALUE=other",
264 }),
265 ),
266 Effect.scoped,
267 );
268 });
269
270 it.effect("identifies the missing file in a path array", () =>
271 withFiles(
272 { "base.env": "" },
273 runStack(
274 "dotenv-missing-path",
275 [Secrets.DotEnv({ path: ["base.env", "missing.env"] })],
276 Effect.void,
277 ).pipe(
278 Effect.flip,
279 Effect.map((error) => expect(error.message).toContain("missing.env")),
280 ),
281 ),
282 );
283
284 it.effect("explicit arrays exclude automatic and ambient dotenv values", () =>
285 withFiles(
286 { ".env": "ALCHEMY_DOTENV_TEST_DEFAULT=default", "explicit.env": "" },
287 Effect.gen(function* () {
288 for (const secrets of [
289 [],
290 [Secrets.DotEnv({ path: [] })],
291 [Secrets.DotEnv({ path: "explicit.env" })],
292 ]) {
293 const output = yield* runStack(
294 "dotenv-explicit",
295 secrets,
296 Config.String("ALCHEMY_DOTENV_TEST_DEFAULT").pipe(Config.option),
297 );
298 expect(Option.isNone(output)).toBe(true);
299 }
300 }).pipe(
301 Effect.provide(
302 ConfigProvider.layer(
303 ConfigProvider.fromEnv({
304 env: { ALCHEMY_DOTENV_TEST_DEFAULT: "ambient" },
305 }),
306 ),
307 ),
308 ),
309 ),
310 );
311
312 it.effect("selects files by stage and preserves earlier keys and empty overrides", () =>
313 withFiles(
314 {
315 "base.env":
316 "ALCHEMY_DOTENV_TEST_VALUE=base\nALCHEMY_DOTENV_TEST_FALLBACK=base\nALCHEMY_DOTENV_TEST_EMPTY=base",
317 "config/prod.env": "ALCHEMY_DOTENV_TEST_VALUE=production\nALCHEMY_DOTENV_TEST_EMPTY=",
318 },
319 runStack(
320 "dotenv-order",
321 [
322 Secrets.DotEnv({ path: "base.env" }),
323 Secrets.DotEnv(({ stage }) => ({ path: `config/${stage}.env` })),
324 ],
325 values,
326 ).pipe(
327 Effect.map((output) =>
328 expect(output).toEqual({
329 value: "production",
330 fallback: "base",
331 empty: "",
332 }),
333 ),
334 ),
335 "prod",
336 ),
337 );
338
339 it.effect("provides secrets to state, providers, and subsequent stack operations", () => {
340 const observed: string[] = [];
341 return TestCore.toEffect(
342 evalStack(
343 Stack(
344 "dotenv-services",
345 {
346 state: Layer.unwrap(
347 Config.String("ALCHEMY_DOTENV_TEST_VALUE").pipe(
348 Effect.map((value) => {
349 observed.push(`state:${value}`);
350 }),
351 Effect.map(() => inMemoryState()),
352 Effect.orDie,
353 ),
354 ),
355 providers: Layer.effectDiscard(
356 Config.String("ALCHEMY_DOTENV_TEST_VALUE").pipe(
357 Effect.map((value) => {
358 observed.push(`providers:${value}`);
359 }),
360 Effect.orDie,
361 ),
362 ),
363 secrets: [Secrets.DotEnv({ path: "services.env" })],
364 },
365 Config.String("ALCHEMY_DOTENV_TEST_VALUE"),
366 ).pipe(Effect.provide(files({ "services.env": "ALCHEMY_DOTENV_TEST_VALUE=secret" }))),
367 (stack) =>
368 Effect.gen(function* () {
369 expect(stack.output).toBe("secret");
370 expect(yield* Config.String("ALCHEMY_DOTENV_TEST_VALUE")).toBe("secret");
371 expect(observed).toEqual(["state:secret", "providers:secret"]);
372 }),
373 { stage: "test" },
374 ),
375 { providers: Layer.empty, state: inMemoryState() },
376 );
377 });
378
379 it.effect("fails for an explicitly missing file", () =>
380 withFiles(
381 {},
382 runStack(
383 "dotenv-missing-explicit",
384 [Secrets.DotEnv({ path: "missing.env" })],
385 Effect.void,
386 ).pipe(
387 Effect.flip,
388 Effect.map((error) => {
389 expect(error._tag).toBe("ConfigError");
390 expect(error.message).toContain("missing.env");
391 }),
392 ),
393 ),
394 );
395
396 it.effect("does not replace an explicit empty path with .env", () =>
397 withFiles(
398 { ".env": "ALCHEMY_DOTENV_TEST_VALUE=default" },
399 runStack("dotenv-empty-path", Secrets.DotEnv({ path: "" }), Effect.void).pipe(
400 Effect.flip,
401 Effect.map((error) => expect(error._tag).toBe("ConfigError")),
402 ),
403 ),
404 );
405
406 it.effect("reapplies a shared provider at each position in the list", () => {
407 const first = Secrets.DotEnv({ path: "first.env" });
408 return withFiles(
409 {
410 "first.env": "ALCHEMY_DOTENV_TEST_VALUE=first",
411 "second.env": "ALCHEMY_DOTENV_TEST_FALLBACK=second",
412 },
413 runStack(
414 "dotenv-repeated-provider",
415 [first, Secrets.DotEnv({ path: "second.env" }), first],
416 Config.String("ALCHEMY_DOTENV_TEST_FALLBACK"),
417 ).pipe(Effect.map((output) => expect(output).toBe("second"))),
418 );
419 });
420
421 it.effect("accepts native ConfigProvider layers; layerAdd merges, layer replaces", () =>
422 withFiles(
423 {},
424 Effect.gen(function* () {
425 const merged = yield* runStack(
426 "native-config-layers",
427 [
428 ConfigProvider.layerAdd(
429 ConfigProvider.fromEnv({
430 env: {
431 ALCHEMY_DOTENV_TEST_VALUE: "first",
432 ALCHEMY_DOTENV_TEST_FALLBACK: "fallback",
433 },
434 }),
435 { asPrimary: true },
436 ),
437 ConfigProvider.layerAdd(
438 ConfigProvider.fromEnv({
439 env: { ALCHEMY_DOTENV_TEST_VALUE: "last" },
440 }),
441 { asPrimary: true },
442 ),
443 ],
444 Effect.all([
445 Config.String("ALCHEMY_DOTENV_TEST_VALUE"),
446 Config.String("ALCHEMY_DOTENV_TEST_FALLBACK"),
447 ]),
448 );
449 expect(merged).toEqual(["last", "fallback"]);
450
451 // A plain ConfigProvider.layer replaces everything before it.
452 const replaced = yield* runStack(
453 "native-config-layer-replaces",
454 [
455 ConfigProvider.layerAdd(
456 ConfigProvider.fromEnv({
457 env: { ALCHEMY_DOTENV_TEST_FALLBACK: "fallback" },
458 }),
459 { asPrimary: true },
460 ),
461 ConfigProvider.layer(
462 ConfigProvider.fromEnv({
463 env: { ALCHEMY_DOTENV_TEST_VALUE: "only" },
464 }),
465 ),
466 ],
467 Effect.all([
468 Config.String("ALCHEMY_DOTENV_TEST_VALUE"),
469 Config.String("ALCHEMY_DOTENV_TEST_FALLBACK").pipe(Config.option),
470 ]),
471 );
472 expect(replaced[0]).toBe("only");
473 expect(Option.isNone(replaced[1])).toBe(true);
474 }),
475 ),
476 );
477
478 it.effect(
479 "ProcessEnv() preserves empty overrides; legacy --env-file keeps file precedence",
480 () => {
481 const key = "ALCHEMY_DOTENV_TEST_PROCESS";
482 return withFiles(
483 { "process.env": "ALCHEMY_DOTENV_TEST_PROCESS=file" },
484 withProcessEnv(
485 { [key]: "shell" },
486 Effect.gen(function* () {
487 for (const value of ["shell", ""]) {
488 process.env[key] = value;
489 const output = yield* runStack(
490 "dotenv-process",
491 [Secrets.DotEnv({ path: "process.env" }), Secrets.ProcessEnv()],
492 Config.String(key),
493 );
494 expect(output).toBe(value);
495 const provider = yield* loadConfigProvider(Option.some("process.env"));
496 expect(
497 yield* Config.String(key).pipe(Effect.provide(ConfigProvider.layer(provider))),
498 ).toBe("file");
499 expect(process.env[key]).toBe(value);
500 }
501 }),
502 ),
503 );
504 },
505 { exclusive: true },
506 );
507
508 it.effect("logs which keys each provider loaded at debug level", () => {
509 const messages: string[] = [];
510 const capture = Logger.make(({ message }) => {
511 messages.push(String(message));
512 });
513 return withFiles(
514 {
515 "base.env": "ALCHEMY_DOTENV_TEST_VALUE=hunter2\nALCHEMY_DOTENV_TEST_FALLBACK=base",
516 "prod.env": "ALCHEMY_DOTENV_TEST_VALUE=hunter2",
517 "empty.env": "",
518 },
519 runStack(
520 "dotenv-logging",
521 [Secrets.DotEnv({ path: "base.env" }), Secrets.DotEnv({ path: ["prod.env", "empty.env"] })],
522 Effect.void,
523 ).pipe(
524 Effect.provide(Logger.layer([capture])),
525 Effect.provideService(MinimumLogLevel, "Debug"),
526 Effect.map(() => {
527 expect(messages.slice(0, 2)).toEqual([
528 "Loaded 2 secrets from dotenv (base.env): ALCHEMY_DOTENV_TEST_FALLBACK, ALCHEMY_DOTENV_TEST_VALUE",
529 "Loaded 1 secrets from dotenv (prod.env, empty.env): ALCHEMY_DOTENV_TEST_VALUE",
530 ]);
531 // The implicit shell closes the list; it logs a count, never names.
532 expect(messages[2]).toMatch(/^Loaded \d+ secrets from the process environment$/);
533 expect(messages).toHaveLength(3);
534 // Keys only, never values.
535 expect(messages.join("\n")).not.toContain("hunter2");
536 }),
537 ),
538 );
539 });
540
541 it.effect(
542 "the shell closes the list unless ProcessEnv() is placed or disabled",
543 () => {
544 const key = "ALCHEMY_DOTENV_TEST_PROCESS_POS";
545 const read = (secrets: SecretProviders | undefined) =>
546 runStack("dotenv-process-position", secrets, Config.String(key));
547 const file = Secrets.DotEnv({ path: "pos.env" });
548 return withFiles(
549 { "pos.env": "ALCHEMY_DOTENV_TEST_PROCESS_POS=file" },
550 withProcessEnv(
551 { [key]: "shell" },
552 Effect.gen(function* () {
553 // Implicitly last: the shell wins over any list...
554 expect(yield* read([file])).toBe("shell");
555 expect(yield* read([])).toBe("shell");
556 // ...unless it is placed, in which case position decides...
557 expect(yield* read([Secrets.ProcessEnv(), file])).toBe("file");
558 expect(yield* read([file, Secrets.ProcessEnv()])).toBe("shell");
559 // ...or disabled, in which case it is never consulted.
560 expect(yield* read([file, Secrets.ProcessEnv({ disabled: true })])).toBe("file");
561 const disabled = yield* read([Secrets.ProcessEnv({ disabled: true })]).pipe(
562 Effect.flip,
563 );
564 expect(disabled._tag).toBe("ConfigError");
565 const byStage = Secrets.ProcessEnv(({ stage }) => ({
566 disabled: stage === "prod",
567 }));
568 expect(yield* read([file, byStage]).pipe(Effect.provideService(Stage, "dev"))).toBe(
569 "shell",
570 );
571 expect(yield* read([file, byStage]).pipe(Effect.provideService(Stage, "prod"))).toBe(
572 "file",
573 );
574 }),
575 ),
576 );
577 },
578 { exclusive: true },
579 );
580
581 it.effect(
582 "ALCHEMY_PROFILE comes from the real process environment, never a provider",
583 () => {
584 const read = (secrets: SecretProviders) =>
585 runStack(
586 "dotenv-profile-pinned",
587 secrets,
588 Config.option(Config.String("ALCHEMY_PROFILE")),
589 ).pipe(Effect.map(Option.getOrUndefined));
590 const file = Secrets.DotEnv({ path: "profile.env" });
591 // A provider listed after the file must also see the pinned value, since
592 // that is where its credentials resolve the profile from.
593 const seenByProvider: Array<string | undefined> = [];
594 const observer = ConfigProvider.layerAdd(
595 Effect.gen(function* () {
596 seenByProvider.push(
597 Option.getOrUndefined(yield* Config.option(Config.String("ALCHEMY_PROFILE"))),
598 );
599 return ConfigProvider.fromEnv({ env: {} });
600 }),
601 { asPrimary: true },
602 );
603 return withFiles(
604 { "profile.env": "ALCHEMY_PROFILE=file" },
605 withProcessEnv(
606 { ALCHEMY_PROFILE: undefined },
607 Effect.gen(function* () {
608 // A provider's ALCHEMY_PROFILE is filtered out...
609 expect(yield* read([file])).toBeUndefined();
610 expect(yield* read([file, Secrets.ProcessEnv()])).toBeUndefined();
611 expect(yield* read([file, observer])).toBeUndefined();
612 // ...while the shell's is seen even without ProcessEnv() listed.
613 process.env.ALCHEMY_PROFILE = "shell";
614 expect(yield* read([file])).toBe("shell");
615 expect(yield* read([])).toBe("shell");
616 expect(yield* read([file, observer])).toBe("shell");
617 expect(seenByProvider).toEqual([undefined, "shell"]);
618 }),
619 ),
620 );
621 },
622 { exclusive: true },
623 );
624 });