Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(env-path): take the login-shell PATH only once its whole answer arrives

AdityaUmalefca74e04285d
diff --git a/server/env-path.spawn-error.test.ts b/server/env-path.spawn-error.test.ts
new file mode 100644
index 0000000000..9976b1d71d
--- /dev/null
+++ b/server/env-path.spawn-error.test.ts
@@ -0,0 +1,40 @@
+import { EventEmitter } from "node:events";
+import { describe, expect, it, vi } from "vitest";
+
+// Under descriptor pressure (EMFILE) spawn returns a child without stdout and reports the failure later through "error".
+vi.mock("node:child_process", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("node:child_process")>();
+ return {
+ ...actual,
+ spawn: vi.fn(() => {
+ const child = Object.assign(new EventEmitter(), { stdout: null, pid: undefined });
+ process.nextTick(() => child.emit("error", Object.assign(new Error("spawn EMFILE"), { code: "EMFILE" })));
+ return child;
+ }),
+ };
+});
+
+const { augmentedPath, resetPathCacheForTests } = await import("./env-path.ts");
+const { spawn } = await import("node:child_process");
+
+describe("login-shell PATH probe when spawn fails", () => {
+ it.skipIf(process.platform === "win32")("treats a spawn without stdout as a failed probe, not a crash", async () => {
+ const saved = { SHELL: process.env.SHELL, VITEST: process.env.VITEST };
+ try {
+ process.env.SHELL = "/bin/sh";
+ delete process.env.VITEST;
+ resetPathCacheForTests();
+
+ expect(() => augmentedPath()).not.toThrow();
+ expect(spawn).toHaveBeenCalledTimes(1);
+ await new Promise((resolve) => process.nextTick(resolve));
+ expect(augmentedPath()).toBeTruthy();
+ } finally {
+ if (saved.SHELL === undefined) delete process.env.SHELL;
+ else process.env.SHELL = saved.SHELL;
+ if (saved.VITEST === undefined) delete process.env.VITEST;
+ else process.env.VITEST = saved.VITEST;
+ resetPathCacheForTests();
+ }
+ });
+});
diff --git a/server/env-path.test.ts b/server/env-path.test.ts
index 58d96cedad..ab27d7a284 100644
--- a/server/env-path.test.ts
+++ b/server/env-path.test.ts
@@ -88,7 +88,7 @@ describe("augmentedPath", () => {
posixIt("keeps the last login-shell PATH available during a rescan", async () => {
const shell = join(homedir(), "fake-login-shell");
const rcOnlyBin = join(homedir(), "rc-only", "bin");
- writeFileSync(shell, `#!/bin/sh\nprintf '__OMB_PATH__%s' '${rcOnlyBin}'\n`);
+ writeFileSync(shell, `#!/bin/sh\nprintf '__OMB_PATH__%s__OMB_END__' '${rcOnlyBin}'\n`);
chmodSync(shell, 0o755);
const previousShell = process.env.SHELL;
@@ -116,7 +116,7 @@ describe("augmentedPath", () => {
const shell = join(homedir(), "fake-login-shell");
const rcOnlyBin = join(homedir(), "rc-only", "bin");
// Answers only when it leads its own process group, as a detached (setsid) child does; an attached one shares the server's.
- writeFileSync(shell, `#!/bin/sh\n[ "$(ps -o pgid= -p $$ | tr -d ' ')" = "$$" ] && printf '__OMB_PATH__%s' '${rcOnlyBin}'\n`);
+ writeFileSync(shell, `#!/bin/sh\n[ "$(ps -o pgid= -p $$ | tr -d ' ')" = "$$" ] && printf '__OMB_PATH__%s__OMB_END__' '${rcOnlyBin}'\n`);
chmodSync(shell, 0o755);
const saved = { SHELL: process.env.SHELL, VITEST: process.env.VITEST };
@@ -140,7 +140,7 @@ describe("augmentedPath", () => {
const shell = join(homedir(), "fake-login-shell");
const rcOnlyBin = join(homedir(), "rc-only", "bin");
const jobPid = join(homedir(), "rc-job.pid");
- writeFileSync(shell, `#!/bin/sh\nprintf '__OMB_PATH__%s' '${rcOnlyBin}'\nsleep 30 &\necho $! > '${jobPid}'\n`);
+ writeFileSync(shell, `#!/bin/sh\nprintf '__OMB_PATH__%s__OMB_END__' '${rcOnlyBin}'\nsleep 30 &\necho $! > '${jobPid}'\n`);
chmodSync(shell, 0o755);
const saved = { SHELL: process.env.SHELL, VITEST: process.env.VITEST };
@@ -172,7 +172,7 @@ describe("augmentedPath", () => {
const finished = join(homedir(), "flood-finished");
writeFileSync(
shell,
- `#!/bin/sh\necho $$ > '${shellPid}'\nprintf '__OMB_PATH__%s\\n' '${rcOnlyBin}'\nhead -c 2000000 /dev/zero\n: > '${finished}'\n`,
+ `#!/bin/sh\necho $$ > '${shellPid}'\nprintf '__OMB_PATH__%s__OMB_END__\\n' '${rcOnlyBin}'\nhead -c 2000000 /dev/zero\n: > '${finished}'\n`,
);
chmodSync(shell, 0o755);
// /proc/<pid>/stat: a killed process its parent has not reaped yet (state Z) still answers kill(pid, 0).
@@ -219,12 +219,89 @@ describe("augmentedPath", () => {
}
});
+ posixIt("waits for the login shell's whole answer, even when the rest arrives after the shell exits", async () => {
+ const shell = join(homedir(), "fake-login-shell");
+ const firstBin = join(homedir(), "first", "bin");
+ const restBin = join(homedir(), "rest", "bin");
+ const shellPid = join(homedir(), "split-shell.pid");
+ const go = join(homedir(), "split-answer.go");
+ // The shell exits after half its answer; a job holding its stdout writes the rest once the test says go (bounded at 10 s).
+ writeFileSync(
+ shell,
+ [
+ "#!/bin/sh",
+ `echo $$ > '${shellPid}'`,
+ `printf '__OMB_PATH__%s' '${firstBin}'`,
+ `(i=0; while [ ! -e '${go}' ] && [ $i -lt 200 ]; do sleep 0.05; i=$((i+1)); done; printf ':%s__OMB_END__' '${restBin}') &`,
+ "",
+ ].join("\n"),
+ );
+ chmodSync(shell, 0o755);
+
+ const saved = { SHELL: process.env.SHELL, VITEST: process.env.VITEST };
+ try {
+ process.env.SHELL = shell;
+ delete process.env.VITEST;
+ resetPathCacheForTests();
+
+ augmentedPath();
+ const pid = await vi.waitFor(() => {
+ const written = existsSync(shellPid) ? Number(readFileSync(shellPid, "utf8").trim()) : 0;
+ expect(written).toBeGreaterThan(0);
+ return written;
+ });
+ // Gone from the process table = reaped, and Node emits "exit" as it reaps.
+ await vi.waitFor(() => expect(() => process.kill(pid, 0)).toThrow());
+ writeFileSync(go, "");
+ await vi.waitFor(() => expect(augmentedPath().split(delimiter)).toContain(restBin), { timeout: 5000 });
+ expect(augmentedPath().split(delimiter)).toContain(firstBin);
+ } finally {
+ if (saved.SHELL === undefined) delete process.env.SHELL;
+ else process.env.SHELL = saved.SHELL;
+ if (saved.VITEST === undefined) delete process.env.VITEST;
+ else process.env.VITEST = saved.VITEST;
+ resetPathCacheForTests();
+ }
+ });
+
+ posixIt("stops reading once the login shell's answer is complete, ignoring a background job's later output", async () => {
+ const shell = join(homedir(), "fake-login-shell");
+ const rcOnlyBin = join(homedir(), "rc-only", "bin");
+ const jobStatus = join(homedir(), "late-job.status");
+ writeFileSync(
+ shell,
+ `#!/bin/sh\nprintf '__OMB_PATH__%s__OMB_END__' '${rcOnlyBin}'\n(head -c 200000 /dev/zero; echo $? > '${jobStatus}') &\n`,
+ );
+ chmodSync(shell, 0o755);
+
+ const saved = { SHELL: process.env.SHELL, VITEST: process.env.VITEST };
+ try {
+ process.env.SHELL = shell;
+ delete process.env.VITEST;
+ resetPathCacheForTests();
+
+ augmentedPath();
+ await vi.waitFor(() => expect(augmentedPath().split(delimiter)).toContain(rcOnlyBin));
+ // 141 = 128 + SIGPIPE: the job's write hit a pipe nobody reads any more (0 would mean it was all read).
+ await vi.waitFor(() => expect(existsSync(jobStatus) && readFileSync(jobStatus, "utf8").trim()).toBe("141"), {
+ timeout: 5000,
+ });
+ expect(augmentedPath().split(delimiter)).toContain(rcOnlyBin);
+ } finally {
+ if (saved.SHELL === undefined) delete process.env.SHELL;
+ else process.env.SHELL = saved.SHELL;
+ if (saved.VITEST === undefined) delete process.env.VITEST;
+ else process.env.VITEST = saved.VITEST;
+ resetPathCacheForTests();
+ }
+ });
+
posixIt("keeps the login-shell PATH in the same order after a rescan", async () => {
const knownBin = join(homedir(), ".local", "bin");
mkdirSync(knownBin, { recursive: true });
const shell = join(homedir(), "fake-login-shell");
const rcOnlyBin = join(homedir(), "rc-only", "bin");
- writeFileSync(shell, `#!/bin/sh\nprintf '__OMB_PATH__%s' '${rcOnlyBin}'\n`);
+ writeFileSync(shell, `#!/bin/sh\nprintf '__OMB_PATH__%s__OMB_END__' '${rcOnlyBin}'\n`);
chmodSync(shell, 0o755);
const saved = { PATH: process.env.PATH, SHELL: process.env.SHELL, VITEST: process.env.VITEST };
@@ -260,7 +337,7 @@ describe("augmentedPath", () => {
const shell = join(homedir(), "fake-login-shell");
const ran = join(homedir(), "login-shell-ran");
const rcOnlyBin = join(homedir(), "rc-only", "bin");
- writeFileSync(shell, `#!/bin/sh\n: > '${ran}'\nprintf '__OMB_PATH__%s' '${rcOnlyBin}'\n`);
+ writeFileSync(shell, `#!/bin/sh\n: > '${ran}'\nprintf '__OMB_PATH__%s__OMB_END__' '${rcOnlyBin}'\n`);
chmodSync(shell, 0o755);
const saved = { PATH: process.env.PATH, SHELL: process.env.SHELL, VITEST: process.env.VITEST };
diff --git a/server/env-path.ts b/server/env-path.ts
index f039dc9dc6..bee9264c0e 100644
--- a/server/env-path.ts
+++ b/server/env-path.ts
@@ -141,7 +141,7 @@ function probeLoginShellPath(): void {
const shell = process.env.SHELL || "/bin/zsh";
// -l -i: nvm and friends live in .zshrc/.bashrc, which only interactive shells read; a marker isolates $PATH from rc noise.
// detached: an interactive shell makes its job the terminal's foreground, which stops `openmausbot setup` and its sign-in CLI (SIGTTOU).
- const child = spawn(shell, ["-l", "-i", "-c", 'printf "__OMB_PATH__%s" "$PATH"'], {
+ const child = spawn(shell, ["-l", "-i", "-c", 'printf "__OMB_PATH__%s__OMB_END__" "$PATH"'], {
detached: true,
stdio: ["ignore", "pipe", "ignore"],
});
@@ -153,7 +153,7 @@ function probeLoginShellPath(): void {
if (finished) return;
finished = true;
clearTimeout(deadline);
- child.stdout.destroy();
+ child.stdout?.destroy();
// An interactive shell ignores SIGTERM, and something its rc started in the background can hold stdout open after it exits.
if (exitCode === undefined && child.pid) {
try {
@@ -163,20 +163,19 @@ function probeLoginShellPath(): void {
};
const deadline = setTimeout(finish, PROBE_TIMEOUT_MS);
deadline.unref();
- // Applied as soon as the shell has exited cleanly, not when stdout closes: its rc may leave a background job holding it.
+ // Applied once the shell has exited cleanly and its whole answer has arrived, not when stdout closes: its rc may leave a
+ // background job holding it. Reading stops there, so that job's later output is never part of the answer.
const applyIfDone = (): void => {
if (exitCode !== 0) return;
- const m = /__OMB_PATH__([^\n]*)/.exec(stdout);
- if (!m || !m[1] || m[1] === loginShellPath) return;
- loginShellPath = m[1];
- cached = buildPath();
+ const m = /__OMB_PATH__([^\n]*?)__OMB_END__/.exec(stdout);
+ if (!m) return;
+ if (m[1] && m[1] !== loginShellPath) {
+ loginShellPath = m[1];
+ cached = buildPath();
+ }
+ finish();
};
- child.stdout.setEncoding("utf8").on("data", (chunk: string) => {
- bytes += Buffer.byteLength(chunk);
- if (bytes > PROBE_MAX_OUTPUT_BYTES) return finish();
- stdout += chunk;
- applyIfDone();
- });
+ // Listeners first: spawn can fail (EMFILE) without creating stdout and report it later through "error".
child.on("error", finish);
child.on("exit", (code) => {
exitCode = code;
@@ -184,6 +183,12 @@ function probeLoginShellPath(): void {
else finish();
});
child.on("close", finish);
+ child.stdout?.setEncoding("utf8").on("data", (chunk: string) => {
+ bytes += Buffer.byteLength(chunk);
+ if (bytes > PROBE_MAX_OUTPUT_BYTES) return finish();
+ stdout += chunk;
+ applyIfDone();
+ });
}
export function resetPathCacheForTests(): void {