Skip to content

Commit dec7879

Browse files
committed
fix(config): bound global runtime dotenv file reads with size limit
Replace unbounded fs.readFileSync in readDotEnvFile with readRegularFileSync capped at 1 MiB so CLI/Gateway startup dotenv loading also gets the bounded read protection — not just the state-dir service-env path. This addresses the P1 review finding that the original fix only capped the helper-level reader while the shared readDotEnvFile used by loadGlobalRuntimeDotEnvFiles was still unbounded.
1 parent 890ede1 commit dec7879

2 files changed

Lines changed: 98 additions & 1 deletion

File tree

‎src/infra/dotenv-global.test.ts‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
2+
import { tmpdir } from "node:os";
3+
import { join } from "node:path";
4+
import { afterEach, describe, expect, it, vi } from "vitest";
5+
import { readDotEnvFile } from "./dotenv-global.js";
6+
7+
const logWarnSpy = vi.hoisted(() => vi.fn());
8+
9+
vi.mock("../logging/subsystem.js", () => ({
10+
createSubsystemLogger: () => ({ warn: logWarnSpy }),
11+
}));
12+
13+
const cleanups: Array<() => void> = [];
14+
15+
afterEach(() => {
16+
logWarnSpy.mockClear();
17+
for (const fn of cleanups.splice(0)) {
18+
fn();
19+
}
20+
});
21+
22+
function tmpDir(): string {
23+
const d = mkdtempSync(join(tmpdir(), "openclaw-dotenv-global-"));
24+
cleanups.push(() => rmSync(d, { recursive: true, force: true }));
25+
return d;
26+
}
27+
28+
function tmpFile(name: string, contents: string): string {
29+
const d = tmpDir();
30+
const p = join(d, name);
31+
writeFileSync(p, contents, "utf8");
32+
return p;
33+
}
34+
35+
describe("readDotEnvFile", () => {
36+
it("reads a small .env file", () => {
37+
const filePath = tmpFile(".env", "API_KEY=secret\nOTHER_KEY=value\n");
38+
const result = readDotEnvFile({ filePath });
39+
expect(result).not.toBeNull();
40+
expect(result!.entries).toContainEqual({ key: "API_KEY", value: "secret" });
41+
expect(result!.entries).toContainEqual({ key: "OTHER_KEY", value: "value" });
42+
expect(logWarnSpy).not.toHaveBeenCalled();
43+
});
44+
45+
it("reads a symlinked .env file", () => {
46+
const d = tmpDir();
47+
const realPath = join(d, "real.env");
48+
writeFileSync(realPath, "REAL_KEY=from_symlink_target\n", "utf8");
49+
const linkPath = join(d, ".env");
50+
symlinkSync(realPath, linkPath);
51+
const result = readDotEnvFile({ filePath: linkPath });
52+
expect(result).not.toBeNull();
53+
expect(result!.entries).toContainEqual({
54+
key: "REAL_KEY",
55+
value: "from_symlink_target",
56+
});
57+
});
58+
59+
it("returns null for a missing file (quiet)", () => {
60+
const d = tmpDir();
61+
const result = readDotEnvFile({ filePath: join(d, "nonexistent.env"), quiet: true });
62+
expect(result).toBeNull();
63+
expect(logWarnSpy).not.toHaveBeenCalled();
64+
});
65+
66+
it("warns when an oversized .env file is skipped", () => {
67+
const d = tmpDir();
68+
// Create a file larger than 1 MiB so the bounded read rejects it.
69+
const filePath = join(d, "oversized.env");
70+
const large = Buffer.alloc(2 * 1024 * 1024, "x");
71+
large.write("KEY=value\n", 0, "utf8");
72+
writeFileSync(filePath, large);
73+
const result = readDotEnvFile({ filePath, quiet: false });
74+
expect(result).toBeNull();
75+
expect(logWarnSpy).toHaveBeenCalledWith(
76+
expect.stringContaining("skipping oversized .env file (max"),
77+
);
78+
});
79+
});

‎src/infra/dotenv-global.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,15 @@ import { createSubsystemLogger } from "../logging/subsystem.js";
77
import { resolveConfigDir } from "../utils.js";
88
import { resolveRequiredHomeDir } from "./home-dir.js";
99
import { normalizeEnvVarKey } from "./host-env-security.js";
10+
import { readRegularFileSync } from "./regular-file.js";
1011

1112
// Global dotenv loading imports operator-level gateway env files without
1213
// overriding variables already present in the process environment.
1314
const logger = createSubsystemLogger("infra:dotenv");
1415

16+
/** Maximum bytes to read from any dotenv file. */
17+
const MAX_DOTENV_FILE_BYTES = 1024 * 1024;
18+
1519
type DotEnvEntry = {
1620
key: string;
1721
value: string;
@@ -36,14 +40,28 @@ export function readDotEnvFile(params: {
3640
}): LoadedDotEnvFile | null {
3741
let content: Buffer;
3842
try {
39-
content = fs.readFileSync(params.filePath);
43+
// Resolve symlinks so a symlinked .env file works while the bounded
44+
// read still rejects oversized targets.
45+
const resolved = fs.realpathSync(params.filePath);
46+
const { buffer } = readRegularFileSync({
47+
filePath: resolved,
48+
maxBytes: MAX_DOTENV_FILE_BYTES,
49+
});
50+
content = buffer;
4051
} catch (error) {
4152
if (!params.quiet) {
4253
const code =
4354
error && typeof error === "object" && "code" in error ? String(error.code) : undefined;
4455
if (code !== "ENOENT") {
4556
logger.warn(`Failed to read ${params.filePath}: ${String(error)}`, { error });
4657
}
58+
// Surface oversized files so operators know a configured file was
59+
// skipped rather than leaving them silently ignored.
60+
if (error instanceof Error && error.message?.startsWith("File exceeds")) {
61+
logger.warn(
62+
`skipping oversized .env file (max ${MAX_DOTENV_FILE_BYTES} bytes): ${params.filePath}`,
63+
);
64+
}
4765
}
4866
return null;
4967
}

0 commit comments

Comments
 (0)