Skip to content

Commit b52ec47

Browse files
tim-smartgithub-actions[bot]
authored andcommitted
feat(tim): import tim-smart#5
Load direnv environments for provider sessions Source: tim-smart#5 Source head: 8f5fc87 Source commits: e4f0701,0d1463af61e0bd174f698b2519ebf3b207a2eaca,a66e4160d5f4b79140ec8fbcbc6aa66af750a991,8f5fc87c13f4628c179cda44d4f32f7fe4d316b2 Imported: complete product delta from the source PR. (cherry picked from commit 0da8bfe)
1 parent 37524db commit b52ec47

32 files changed

Lines changed: 2880 additions & 1979 deletions

apps/server/src/processRunner.test.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ type ChildProcessCommand = {
1919
readonly args: ReadonlyArray<string>;
2020
readonly options: {
2121
readonly shell?: boolean | string;
22+
readonly env?: NodeJS.ProcessEnv;
23+
readonly extendEnv?: boolean;
2224
};
2325
};
2426

@@ -80,6 +82,24 @@ const runWith =
8082
);
8183

8284
describe("runProcess", () => {
85+
it.effect("can launch with an exact non-extending environment", () => {
86+
const environment = { PATH: "/project/bin", KEEP: "value" };
87+
const spawner = makeSpawner((command) =>
88+
Effect.sync(() => {
89+
expect(command.options.env).toEqual(environment);
90+
expect(command.options.extendEnv).toBe(false);
91+
return makeHandle({ stdout: "ok" });
92+
}),
93+
);
94+
95+
return runWith(spawner)({
96+
command: "/project/bin/direnv",
97+
args: ["export", "json"],
98+
env: environment,
99+
extendEnv: false,
100+
});
101+
});
102+
83103
it.effect("collects stdout through an injected ChildProcessSpawner", () =>
84104
Effect.gen(function* () {
85105
const spawner = makeSpawner((command) =>

apps/server/src/processRunner.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ export interface ProcessRunInput {
2323
readonly spawnCwd?: string | undefined;
2424
readonly timeout?: Duration.Input | undefined;
2525
readonly env?: NodeJS.ProcessEnv | undefined;
26+
readonly extendEnv?: boolean | undefined;
2627
readonly stdin?: string | undefined;
2728
readonly maxOutputBytes?: number | undefined;
2829
readonly outputMode?: "error" | "truncate" | undefined;
@@ -290,7 +291,7 @@ const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
290291
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
291292
const outputMode = input.outputMode ?? "error";
292293
const truncatedMarker = input.truncatedMarker ?? "";
293-
const extendEnv = input.env !== undefined;
294+
const extendEnv = input.env === undefined ? false : (input.extendEnv ?? true);
294295
const spawnCommand = yield* resolveSpawnCommand(
295296
input.command,
296297
input.args,
Lines changed: 236 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,236 @@
1+
import { describe, expect, it, vi } from "@effect/vitest";
2+
import { NodeServices } from "@effect/platform-node";
3+
import * as Effect from "effect/Effect";
4+
import * as FileSystem from "effect/FileSystem";
5+
import * as Layer from "effect/Layer";
6+
import * as Path from "effect/Path";
7+
import { ChildProcessSpawner } from "effect/unstable/process";
8+
9+
import * as ProcessRunner from "../processRunner.ts";
10+
import { DirenvEnvironment, DirenvEnvironmentError, layer } from "./DirenvEnvironment.ts";
11+
12+
const successfulOutput = (
13+
stdout: string,
14+
stderr = "",
15+
code = 0,
16+
): ProcessRunner.ProcessRunOutput => ({
17+
stdout,
18+
stderr,
19+
code: ChildProcessSpawner.ExitCode(code),
20+
timedOut: false,
21+
stdoutTruncated: false,
22+
stderrTruncated: false,
23+
});
24+
25+
function testLayer(run: ProcessRunner.ProcessRunner["Service"]["run"]) {
26+
return layer.pipe(
27+
Layer.provide(Layer.succeed(ProcessRunner.ProcessRunner, { run })),
28+
Layer.provideMerge(NodeServices.layer),
29+
);
30+
}
31+
32+
const makeDirenvExecutable = Effect.fn("makeDirenvExecutable")(function* (directory: string) {
33+
const fileSystem = yield* FileSystem.FileSystem;
34+
const path = yield* Path.Path;
35+
const binDirectory = path.join(directory, "bin");
36+
const executable = path.join(binDirectory, "direnv");
37+
yield* fileSystem.makeDirectory(binDirectory, { recursive: true });
38+
yield* fileSystem.writeFileString(executable, "#!/bin/sh\nexit 0\n");
39+
yield* fileSystem.chmod(executable, 0o755);
40+
return { binDirectory, executable };
41+
});
42+
43+
/** A temp project with an `.envrc` and a fake direnv on PATH. */
44+
const setupDirenvProject = Effect.fn("setupDirenvProject")(function* () {
45+
const fileSystem = yield* FileSystem.FileSystem;
46+
const path = yield* Path.Path;
47+
const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-direnv-" });
48+
const envrcPath = path.join(cwd, ".envrc");
49+
yield* fileSystem.writeFileString(envrcPath, "export VALUE=next\n");
50+
const { binDirectory, executable } = yield* makeDirenvExecutable(cwd);
51+
return { cwd, envrcPath, binDirectory, executable };
52+
});
53+
54+
describe("DirenvEnvironment", () => {
55+
describe("new worktree approval", () => {
56+
it.effect("approves the exact .envrc in a newly created worktree", () => {
57+
const run = vi.fn<ProcessRunner.ProcessRunner["Service"]["run"]>(() =>
58+
Effect.succeed(successfulOutput("")),
59+
);
60+
return Effect.gen(function* () {
61+
const { cwd, envrcPath, binDirectory, executable } = yield* setupDirenvProject();
62+
const environment = { PATH: binDirectory, KEEP: "value" };
63+
const direnvEnvironment = yield* DirenvEnvironment;
64+
65+
yield* direnvEnvironment.allow({ cwd, environment });
66+
67+
expect(run).toHaveBeenCalledOnce();
68+
expect(run.mock.calls[0]?.[0]).toMatchObject({
69+
command: executable,
70+
args: ["allow", envrcPath],
71+
cwd,
72+
env: environment,
73+
extendEnv: false,
74+
});
75+
}).pipe(Effect.provide(testLayer(run)));
76+
});
77+
78+
it.effect("does not approve an ancestor .envrc outside the new worktree", () => {
79+
const run = vi.fn<ProcessRunner.ProcessRunner["Service"]["run"]>();
80+
return Effect.gen(function* () {
81+
const fileSystem = yield* FileSystem.FileSystem;
82+
const path = yield* Path.Path;
83+
const parent = yield* fileSystem.makeTempDirectoryScoped({
84+
prefix: "t3-direnv-worktree-parent-",
85+
});
86+
const cwd = path.join(parent, "worktree");
87+
yield* fileSystem.makeDirectory(cwd);
88+
yield* fileSystem.writeFileString(path.join(parent, ".envrc"), "export VALUE=parent\n");
89+
const direnvEnvironment = yield* DirenvEnvironment;
90+
91+
yield* direnvEnvironment.allow({ cwd, environment: { PATH: "/not-used" } });
92+
93+
expect(run).not.toHaveBeenCalled();
94+
}).pipe(Effect.provide(testLayer(run)));
95+
});
96+
});
97+
98+
it.effect(
99+
"returns the environment unchanged without inspecting PATH when no .envrc exists",
100+
() => {
101+
const run = vi.fn<ProcessRunner.ProcessRunner["Service"]["run"]>();
102+
return Effect.gen(function* () {
103+
const fileSystem = yield* FileSystem.FileSystem;
104+
const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-direnv-none-" });
105+
const environment = { PATH: "/not-used", KEEP: "value" };
106+
const resolver = yield* DirenvEnvironment;
107+
108+
expect(yield* resolver.resolve({ cwd, environment })).toBe(environment);
109+
expect(run).not.toHaveBeenCalled();
110+
}).pipe(Effect.provide(testLayer(run)));
111+
},
112+
);
113+
114+
it.effect("discovers a parent-directory .envrc and runs direnv in the requested cwd", () => {
115+
const run = vi.fn<ProcessRunner.ProcessRunner["Service"]["run"]>(() =>
116+
Effect.succeed(successfulOutput("{}")),
117+
);
118+
return Effect.gen(function* () {
119+
const fileSystem = yield* FileSystem.FileSystem;
120+
const path = yield* Path.Path;
121+
const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-direnv-parent-" });
122+
const cwd = path.join(root, "nested", "project");
123+
yield* fileSystem.makeDirectory(cwd, { recursive: true });
124+
yield* fileSystem.writeFileString(path.join(root, ".envrc"), "export PROJECT=parent\n");
125+
const { binDirectory, executable } = yield* makeDirenvExecutable(root);
126+
const environment = { PATH: binDirectory };
127+
const resolver = yield* DirenvEnvironment;
128+
129+
expect(yield* resolver.resolve({ cwd, environment })).toEqual(environment);
130+
expect(run).toHaveBeenCalledOnce();
131+
expect(run.mock.calls[0]?.[0]).toMatchObject({
132+
command: executable,
133+
args: ["export", "json"],
134+
cwd,
135+
env: environment,
136+
extendEnv: false,
137+
});
138+
}).pipe(Effect.provide(testLayer(run)));
139+
});
140+
141+
it.effect(
142+
"returns the environment unchanged when .envrc exists but direnv is unavailable",
143+
() => {
144+
const run = vi.fn<ProcessRunner.ProcessRunner["Service"]["run"]>();
145+
return Effect.gen(function* () {
146+
const fileSystem = yield* FileSystem.FileSystem;
147+
const path = yield* Path.Path;
148+
const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-direnv-missing-" });
149+
yield* fileSystem.writeFileString(path.join(cwd, ".envrc"), "export VALUE=next\n");
150+
const environment = { PATH: "", KEEP: "value" };
151+
const resolver = yield* DirenvEnvironment;
152+
153+
expect(yield* resolver.resolve({ cwd, environment })).toBe(environment);
154+
expect(run).not.toHaveBeenCalled();
155+
}).pipe(Effect.provide(testLayer(run)));
156+
},
157+
);
158+
159+
it.effect("applies additions, overrides, and removals from a successful export", () => {
160+
const run = vi.fn<ProcessRunner.ProcessRunner["Service"]["run"]>(() =>
161+
Effect.succeed(
162+
successfulOutput(JSON.stringify({ ADDED: "new", OVERRIDDEN: "direnv", REMOVED: null })),
163+
),
164+
);
165+
return Effect.gen(function* () {
166+
const { cwd, binDirectory } = yield* setupDirenvProject();
167+
const resolver = yield* DirenvEnvironment;
168+
169+
expect(
170+
yield* resolver.resolve({
171+
cwd,
172+
environment: {
173+
PATH: binDirectory,
174+
OVERRIDDEN: "provider-instance",
175+
REMOVED: "host",
176+
PRESERVED: "yes",
177+
},
178+
}),
179+
).toEqual({
180+
PATH: binDirectory,
181+
ADDED: "new",
182+
OVERRIDDEN: "direnv",
183+
PRESERVED: "yes",
184+
});
185+
}).pipe(Effect.provide(testLayer(run)));
186+
});
187+
188+
it.effect("returns actionable stderr for a blocked .envrc", () => {
189+
const run = vi.fn<ProcessRunner.ProcessRunner["Service"]["run"]>(() =>
190+
Effect.succeed(
191+
successfulOutput(
192+
"",
193+
"secret-environment-value: .envrc is blocked. Run `direnv allow` to approve",
194+
1,
195+
),
196+
),
197+
);
198+
return Effect.gen(function* () {
199+
const { cwd, binDirectory } = yield* setupDirenvProject();
200+
const resolver = yield* DirenvEnvironment;
201+
const error = yield* resolver
202+
.resolve({
203+
cwd,
204+
environment: { PATH: binDirectory, SECRET: "secret-environment-value" },
205+
})
206+
.pipe(Effect.flip);
207+
208+
expect(error).toBeInstanceOf(DirenvEnvironmentError);
209+
expect(error.stage).toBe("execution");
210+
expect(error.message).toContain("direnv allow");
211+
expect(error.message).not.toContain("secret-environment-value");
212+
}).pipe(Effect.provide(testLayer(run)));
213+
});
214+
215+
it.effect("rejects malformed or structurally invalid output without exposing stdout", () => {
216+
let stdout = "";
217+
const run = vi.fn<ProcessRunner.ProcessRunner["Service"]["run"]>(() =>
218+
Effect.succeed(successfulOutput(stdout)),
219+
);
220+
return Effect.gen(function* () {
221+
const { cwd, binDirectory } = yield* setupDirenvProject();
222+
const resolver = yield* DirenvEnvironment;
223+
224+
for (const rawStdout of ["not-json secret-value", '{"SAFE":"value","INVALID":42}']) {
225+
stdout = rawStdout;
226+
const error = yield* resolver
227+
.resolve({ cwd, environment: { PATH: binDirectory } })
228+
.pipe(Effect.flip);
229+
230+
expect(error.stage).toBe("invalid-output");
231+
expect(error.message).not.toContain(rawStdout);
232+
expect(error.cause).toBeUndefined();
233+
}
234+
}).pipe(Effect.provide(testLayer(run)));
235+
});
236+
});

0 commit comments

Comments
 (0)