Skip to content

Commit c275238

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 cb82379 commit c275238

2 files changed

Lines changed: 167 additions & 7 deletions

File tree

‎apps/server/src/config.ts‎

Lines changed: 58 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,57 @@ export function assertApiDeploymentConfig(
5252
);
5353
}
5454

55+
export function parsePort(raw: string | undefined): number {
56+
const port = Number(raw ?? 8787);
57+
if (!Number.isInteger(port) || port < 1 || port > 65535)
58+
throw new Error("PORT must be an integer between 1 and 65535");
59+
return port;
60+
}
61+
62+
export function parsePublicUrl(raw: string | undefined, port: number): string {
63+
const value = (raw ?? `http://localhost:${port}`).trim().replace(/\/+$/, "");
64+
if (!value) throw new Error("PUBLIC_API_URL must be a valid URL");
65+
let parsed: URL;
66+
try {
67+
parsed = new URL(value);
68+
} catch {
69+
throw new Error("PUBLIC_API_URL must be a valid URL");
70+
}
71+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
72+
throw new Error("PUBLIC_API_URL must use http or https");
73+
return value;
74+
}
75+
76+
export function parseAllowedOrigins(raw: string | undefined): string[] {
77+
const entries = (raw ?? "http://localhost:8081,http://127.0.0.1:8081")
78+
.split(",")
79+
.map((entry) => entry.trim())
80+
.filter((entry) => entry.length > 0);
81+
const origins: string[] = [];
82+
for (const entry of entries) {
83+
let parsed: URL;
84+
try {
85+
parsed = new URL(entry);
86+
} catch {
87+
throw new Error(`ALLOWED_ORIGINS contains an invalid origin: ${entry}`);
88+
}
89+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
90+
throw new Error(`ALLOWED_ORIGINS contains an invalid origin: ${entry}`);
91+
const origin = parsed.origin;
92+
if (!origins.includes(origin)) origins.push(origin);
93+
}
94+
return origins;
95+
}
96+
97+
export function isValidEncryptionKey(key: string): boolean {
98+
try {
99+
const bytes = Buffer.from(key, "base64");
100+
return bytes.length === 32 && bytes.toString("base64") === key;
101+
} catch {
102+
return false;
103+
}
104+
}
105+
55106
export function readConfig(): Config {
56107
const mode = process.env.WORKSPACE_MODE ?? "sample";
57108
if (mode !== "sample" && mode !== "live")
@@ -61,8 +112,8 @@ export function readConfig(): Config {
61112
throw new Error("AGENT_BACKEND must be sample, model or agui");
62113
if (mode === "live" && backend === "sample")
63114
throw new Error("Live workspaces cannot use the sample agent");
64-
const port = Number(process.env.PORT ?? 8787);
65-
const publicUrl = process.env.PUBLIC_API_URL ?? `http://localhost:${port}`;
115+
const port = parsePort(process.env.PORT);
116+
const publicUrl = parsePublicUrl(process.env.PUBLIC_API_URL, port);
66117
const config: Config = {
67118
mode,
68119
port,
@@ -86,13 +137,14 @@ export function readConfig(): Config {
86137
computerEnabled: process.env.COMPUTER_ENABLED === "true",
87138
computerImage: process.env.COMPUTER_IMAGE ?? "openmuse-computer:local",
88139
computerDeploymentId: process.env.COMPUTER_DEPLOYMENT_ID,
89-
allowedOrigins: (
90-
process.env.ALLOWED_ORIGINS ?? "http://localhost:8081,http://127.0.0.1:8081"
91-
).split(","),
140+
allowedOrigins: parseAllowedOrigins(process.env.ALLOWED_ORIGINS),
92141
};
93142
if (
94143
mode === "live" &&
95-
(!config.accessKey || config.accessKey.length < 24 || !config.encryptionKey)
144+
(!config.accessKey ||
145+
config.accessKey.length < 24 ||
146+
!config.encryptionKey ||
147+
!isValidEncryptionKey(config.encryptionKey))
96148
)
97149
throw new Error(
98150
"Live mode requires OPENMUSE_ACCESS_KEY (24+ characters) and TOKEN_ENCRYPTION_KEY (32-byte base64)",

‎tests/config.test.ts‎

Lines changed: 109 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import assert from "node:assert/strict";
2+
import { randomBytes } from "node:crypto";
23
import { test } from "node:test";
3-
import { assertApiDeploymentConfig, type Config } from "../apps/server/src/config.ts";
4+
import { assertApiDeploymentConfig, type Config, readConfig } from "../apps/server/src/config.ts";
45

56
const sampleConfig: Config = {
67
mode: "sample",
@@ -46,3 +47,110 @@ test("every API mode accepts a non-empty Intelligence key", () => {
4647
);
4748
}
4849
});
50+
51+
const configEnvKeys = [
52+
"WORKSPACE_MODE",
53+
"AGENT_BACKEND",
54+
"PORT",
55+
"PUBLIC_API_URL",
56+
"HOST",
57+
"DATA_DIR",
58+
"OPENMUSE_ACCESS_KEY",
59+
"TOKEN_ENCRYPTION_KEY",
60+
"CPK_INTELLIGENCE_API_KEY",
61+
"ALLOWED_ORIGINS",
62+
] as const;
63+
64+
function withEnv(env: Record<string, string | undefined>, run: () => void): void {
65+
const saved = new Map<string, string | undefined>();
66+
for (const key of configEnvKeys) {
67+
saved.set(key, process.env[key]);
68+
const value = env[key];
69+
if (value === undefined) delete process.env[key];
70+
else process.env[key] = value;
71+
}
72+
try {
73+
run();
74+
} finally {
75+
for (const key of configEnvKeys) {
76+
const value = saved.get(key);
77+
if (value === undefined) delete process.env[key];
78+
else process.env[key] = value;
79+
}
80+
}
81+
}
82+
83+
function sampleEnv(extra: Record<string, string | undefined> = {}): Record<string, string> {
84+
return {
85+
WORKSPACE_MODE: "sample",
86+
AGENT_BACKEND: "sample",
87+
CPK_INTELLIGENCE_API_KEY: "test-project-key-never-sent",
88+
...extra,
89+
} as Record<string, string>;
90+
}
91+
92+
test("readConfig rejects out-of-range or non-numeric ports", () => {
93+
for (const port of ["abc", "", "0", "-1", "65536", "99999", "8.5", "NaN"]) {
94+
withEnv(sampleEnv({ PORT: port }), () => {
95+
assert.throws(() => readConfig(), { message: /PORT must be an integer between 1 and 65535/ });
96+
});
97+
}
98+
withEnv(sampleEnv({ PORT: "8790" }), () => {
99+
assert.equal(readConfig().port, 8790);
100+
});
101+
});
102+
103+
test("readConfig normalizes the public URL and derives callback links from it", () => {
104+
withEnv(sampleEnv({ PUBLIC_API_URL: "https://example.com/" }), () => {
105+
const config = readConfig();
106+
assert.equal(config.publicUrl, "https://example.com");
107+
assert.equal(config.googleRedirectUri, "https://example.com/api/google/callback");
108+
});
109+
for (const url of ["not a url", "ftp://example.com", "example.com"]) {
110+
withEnv(sampleEnv({ PUBLIC_API_URL: url }), () => {
111+
assert.throws(() => readConfig(), { message: /PUBLIC_API_URL/ });
112+
});
113+
}
114+
});
115+
116+
test("readConfig trims, filters, and deduplicates allowed origins", () => {
117+
withEnv(
118+
sampleEnv({ ALLOWED_ORIGINS: "https://a.example, https://b.example ,,https://a.example/" }),
119+
() => {
120+
assert.deepEqual(readConfig().allowedOrigins, ["https://a.example", "https://b.example"]);
121+
},
122+
);
123+
withEnv(sampleEnv({ ALLOWED_ORIGINS: "not a url" }), () => {
124+
assert.throws(() => readConfig(), { message: /ALLOWED_ORIGINS/ });
125+
});
126+
});
127+
128+
test("readConfig rejects live deployments without a 32-byte encryption key", () => {
129+
const accessKey = "a".repeat(24);
130+
withEnv(
131+
sampleEnv({
132+
WORKSPACE_MODE: "live",
133+
AGENT_BACKEND: "model",
134+
OPENMUSE_ACCESS_KEY: accessKey,
135+
TOKEN_ENCRYPTION_KEY: "too-short",
136+
}),
137+
() => {
138+
assert.throws(() => readConfig(), {
139+
message: /TOKEN_ENCRYPTION_KEY.*32-byte base64/,
140+
});
141+
},
142+
);
143+
withEnv(
144+
sampleEnv({
145+
WORKSPACE_MODE: "live",
146+
AGENT_BACKEND: "model",
147+
OPENMUSE_ACCESS_KEY: accessKey,
148+
TOKEN_ENCRYPTION_KEY: randomBytes(32).toString("base64"),
149+
}),
150+
() => {
151+
const config = readConfig();
152+
assert.equal(config.mode, "live");
153+
assert.equal(config.accessKey, accessKey);
154+
},
155+
);
156+
});

0 commit comments

Comments
 (0)