Skip to content

Commit 668ec5a

Browse files
committed
fix: harden server config parsing and startup validation
readConfig accepted non-numeric and out-of-range PORT values, unvalidated PUBLIC_API_URL strings (failing later with an obscure error inside app boot), ALLOWED_ORIGINS entries with surrounding spaces that could never match an Origin header, and any non-empty TOKEN_ENCRYPTION_KEY in live mode even though the vault requires 32-byte base64. Validate the port range, normalize and verify the public URL (so derived callback links never carry a double slash), trim/filter/dedupe origins to their URL origin form, and check the live encryption key shape at startup with the same round-trip rule the vault enforces. Adds readConfig unit coverage, which previously had none.
1 parent 1ac68f3 commit 668ec5a

2 files changed

Lines changed: 202 additions & 6 deletions

File tree

‎apps/server/src/config.ts‎

Lines changed: 69 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,68 @@ export function browserWorkerUrl(value?: string): string | undefined {
102102
// writes never re-fire here: they are dispatched outside the model loop through
103103
// reviewed, idempotency-keyed actions.
104104
export const MODEL_MAX_RETRIES = 2;
105+
106+
export function parsePort(raw: string | undefined): number {
107+
const port = Number(raw ?? 8787);
108+
if (!Number.isInteger(port) || port < 1 || port > 65535)
109+
throw new Error("PORT must be an integer between 1 and 65535");
110+
return port;
111+
}
112+
113+
export function parsePublicUrl(raw: string | undefined, port: number): string {
114+
const value = (raw ?? `http://localhost:${port}`).trim().replace(/\/+$/, "");
115+
if (!value) throw new Error("PUBLIC_API_URL must be a valid URL");
116+
let parsed: URL;
117+
try {
118+
parsed = new URL(value);
119+
} catch {
120+
throw new Error("PUBLIC_API_URL must be a valid URL");
121+
}
122+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
123+
throw new Error("PUBLIC_API_URL must use http or https");
124+
// Downstream consumers concatenate this value as a base string
125+
// (Auth.sign does `${publicUrl}${path}?owner=...`, callback is
126+
// `${publicUrl}/api/google/callback`), so credentials, queries,
127+
// fragments, and subpaths would produce malformed links or leak secrets.
128+
if (parsed.username || parsed.password)
129+
throw new Error("PUBLIC_API_URL must not contain credentials");
130+
if (parsed.search || parsed.hash)
131+
throw new Error("PUBLIC_API_URL must not contain a query string or fragment");
132+
if (parsed.pathname !== "/" && parsed.pathname !== "")
133+
throw new Error("PUBLIC_API_URL must not contain a subpath");
134+
return parsed.origin;
135+
}
136+
137+
export function parseAllowedOrigins(raw: string | undefined): string[] {
138+
const entries = (raw ?? "http://localhost:8081,http://127.0.0.1:8081")
139+
.split(",")
140+
.map((entry) => entry.trim())
141+
.filter((entry) => entry.length > 0);
142+
const origins: string[] = [];
143+
for (const entry of entries) {
144+
let parsed: URL;
145+
try {
146+
parsed = new URL(entry);
147+
} catch {
148+
throw new Error(`ALLOWED_ORIGINS contains an invalid origin: ${entry}`);
149+
}
150+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
151+
throw new Error(`ALLOWED_ORIGINS contains an invalid origin: ${entry}`);
152+
const origin = parsed.origin;
153+
if (!origins.includes(origin)) origins.push(origin);
154+
}
155+
return origins;
156+
}
157+
158+
export function isValidEncryptionKey(key: string): boolean {
159+
try {
160+
const bytes = Buffer.from(key, "base64");
161+
return bytes.length === 32 && bytes.toString("base64") === key;
162+
} catch {
163+
return false;
164+
}
165+
}
166+
105167
export function readConfig(): Config {
106168
const mode = process.env.WORKSPACE_MODE ?? "sample";
107169
if (mode !== "sample" && mode !== "live")
@@ -131,8 +193,8 @@ export function readConfig(): Config {
131193
"COMPUTER_PROVIDER=e2b-desktop requires a unique COMPUTER_DEPLOYMENT_ID, e.g. from `openssl rand -hex 12`",
132194
);
133195
}
134-
const port = Number(process.env.PORT ?? 8787);
135-
const publicUrl = process.env.PUBLIC_API_URL ?? `http://localhost:${port}`;
196+
const port = parsePort(process.env.PORT);
197+
const publicUrl = parsePublicUrl(process.env.PUBLIC_API_URL, port);
136198
const config: Config = {
137199
mode,
138200
port,
@@ -163,16 +225,17 @@ export function readConfig(): Config {
163225
computerProvider,
164226
computerE2bTemplate: process.env.COMPUTER_E2B_TEMPLATE?.trim() || "desktop",
165227
e2bApiKey,
166-
allowedOrigins: (
167-
process.env.ALLOWED_ORIGINS ?? "http://localhost:8081,http://127.0.0.1:8081"
168-
).split(","),
228+
allowedOrigins: parseAllowedOrigins(process.env.ALLOWED_ORIGINS),
169229
// Only trust X-Forwarded-For/X-Real-IP when the deployment is known to sit
170230
// behind a proxy that sets them; otherwise a direct caller can spoof them.
171231
trustProxy: process.env.TRUST_PROXY === "true",
172232
};
173233
if (
174234
mode === "live" &&
175-
(!config.accessKey || config.accessKey.length < 24 || !config.encryptionKey)
235+
(!config.accessKey ||
236+
config.accessKey.length < 24 ||
237+
!config.encryptionKey ||
238+
!isValidEncryptionKey(config.encryptionKey))
176239
)
177240
throw new Error(
178241
"Live mode requires OPENMUSE_ACCESS_KEY (24+ characters) and TOKEN_ENCRYPTION_KEY (32-byte base64)",

‎tests/config.test.ts‎

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import assert from "node:assert/strict";
2+
import { randomBytes } from "node:crypto";
23
import { test } from "node:test";
34
import {
45
assertApiDeploymentConfig,
@@ -151,3 +152,135 @@ test("computer provider defaults to Docker and e2b-desktop requires a server-sid
151152
}
152153
}
153154
});
155+
156+
const configEnvKeys = [
157+
"WORKSPACE_MODE",
158+
"AGENT_BACKEND",
159+
"PORT",
160+
"PUBLIC_API_URL",
161+
"HOST",
162+
"DATA_DIR",
163+
"OPENMUSE_ACCESS_KEY",
164+
"TOKEN_ENCRYPTION_KEY",
165+
"CPK_INTELLIGENCE_API_KEY",
166+
"ALLOWED_ORIGINS",
167+
"JEV_MODE",
168+
"TYPESAFE_API_KEY",
169+
"COMPUTER_PROVIDER",
170+
"COMPUTER_ENABLED",
171+
"E2B_API_KEY",
172+
"COMPUTER_DEPLOYMENT_ID",
173+
] as const;
174+
175+
function withEnv(env: Record<string, string | undefined>, run: () => void): void {
176+
const saved = new Map<string, string | undefined>();
177+
for (const key of configEnvKeys) {
178+
saved.set(key, process.env[key]);
179+
const value = env[key];
180+
if (value === undefined) delete process.env[key];
181+
else process.env[key] = value;
182+
}
183+
try {
184+
run();
185+
} finally {
186+
for (const key of configEnvKeys) {
187+
const value = saved.get(key);
188+
if (value === undefined) delete process.env[key];
189+
else process.env[key] = value;
190+
}
191+
}
192+
}
193+
194+
function sampleEnv(extra: Record<string, string | undefined> = {}): Record<string, string> {
195+
return {
196+
WORKSPACE_MODE: "sample",
197+
AGENT_BACKEND: "sample",
198+
CPK_INTELLIGENCE_API_KEY: "test-project-key-never-sent",
199+
...extra,
200+
} as Record<string, string>;
201+
}
202+
203+
test("readConfig rejects out-of-range or non-numeric ports", () => {
204+
for (const port of ["abc", "", "0", "-1", "65536", "99999", "8.5", "NaN"]) {
205+
withEnv(sampleEnv({ PORT: port }), () => {
206+
assert.throws(() => readConfig(), { message: /PORT must be an integer between 1 and 65535/ });
207+
});
208+
}
209+
withEnv(sampleEnv({ PORT: "8790" }), () => {
210+
assert.equal(readConfig().port, 8790);
211+
});
212+
});
213+
214+
test("readConfig normalizes the public URL and derives callback links from it", () => {
215+
withEnv(sampleEnv({ PUBLIC_API_URL: "https://example.com/" }), () => {
216+
const config = readConfig();
217+
assert.equal(config.publicUrl, "https://example.com");
218+
assert.equal(config.googleRedirectUri, "https://example.com/api/google/callback");
219+
});
220+
withEnv(sampleEnv({ PUBLIC_API_URL: "https://example.com:8443/" }), () => {
221+
const config = readConfig();
222+
assert.equal(config.publicUrl, "https://example.com:8443");
223+
});
224+
for (const url of ["not a url", "ftp://example.com", "example.com"]) {
225+
withEnv(sampleEnv({ PUBLIC_API_URL: url }), () => {
226+
assert.throws(() => readConfig(), { message: /PUBLIC_API_URL/ });
227+
});
228+
}
229+
});
230+
231+
test("readConfig rejects credentials, queries, fragments, and subpaths in the public URL", () => {
232+
for (const url of [
233+
"https://user@example.com",
234+
"https://user:pass@example.com",
235+
"https://example.com?x=1",
236+
"https://example.com#fragment",
237+
"https://example.com/subpath",
238+
"https://example.com/subpath/",
239+
]) {
240+
withEnv(sampleEnv({ PUBLIC_API_URL: url }), () => {
241+
assert.throws(() => readConfig(), { message: /PUBLIC_API_URL/ });
242+
});
243+
}
244+
});
245+
246+
test("readConfig trims, filters, and deduplicates allowed origins", () => {
247+
withEnv(
248+
sampleEnv({ ALLOWED_ORIGINS: "https://a.example, https://b.example ,,https://a.example/" }),
249+
() => {
250+
assert.deepEqual(readConfig().allowedOrigins, ["https://a.example", "https://b.example"]);
251+
},
252+
);
253+
withEnv(sampleEnv({ ALLOWED_ORIGINS: "not a url" }), () => {
254+
assert.throws(() => readConfig(), { message: /ALLOWED_ORIGINS/ });
255+
});
256+
});
257+
258+
test("readConfig rejects live deployments without a 32-byte encryption key", () => {
259+
const accessKey = "a".repeat(24);
260+
withEnv(
261+
sampleEnv({
262+
WORKSPACE_MODE: "live",
263+
AGENT_BACKEND: "model",
264+
OPENMUSE_ACCESS_KEY: accessKey,
265+
TOKEN_ENCRYPTION_KEY: "too-short",
266+
}),
267+
() => {
268+
assert.throws(() => readConfig(), {
269+
message: /TOKEN_ENCRYPTION_KEY.*32-byte base64/,
270+
});
271+
},
272+
);
273+
withEnv(
274+
sampleEnv({
275+
WORKSPACE_MODE: "live",
276+
AGENT_BACKEND: "model",
277+
OPENMUSE_ACCESS_KEY: accessKey,
278+
TOKEN_ENCRYPTION_KEY: randomBytes(32).toString("base64"),
279+
}),
280+
() => {
281+
const config = readConfig();
282+
assert.equal(config.mode, "live");
283+
assert.equal(config.accessKey, accessKey);
284+
},
285+
);
286+
});

0 commit comments

Comments
 (0)