fix(backend): inject provider credentials from file
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
import path from "node:path";
|
||||
|
||||
export interface AppConfig {
|
||||
host: string; port: number; harnessDir: string; thtBin: string; piBin: string;
|
||||
authMode: "none" | "mock" | "upstream";
|
||||
@@ -6,6 +8,7 @@ export interface AppConfig {
|
||||
settingsFile: string;
|
||||
dataRoot?: string;
|
||||
ollamaEnsureTimeoutMs: number;
|
||||
modelApiKeyFile?: string;
|
||||
}
|
||||
export function loadConfig(env: Record<string, string | undefined>): AppConfig {
|
||||
const authMode = env.AUTH_MODE ?? "none";
|
||||
@@ -15,6 +18,15 @@ export function loadConfig(env: Record<string, string | undefined>): AppConfig {
|
||||
if (env.THOTH_PUBLIC_EXPOSURE === "true" && authMode !== "upstream") {
|
||||
throw new Error("public exposure requires AUTH_MODE=upstream behind a trusted proxy");
|
||||
}
|
||||
const modelApiKeyFile = env.THT_MODEL_API_KEY_FILE;
|
||||
if (modelApiKeyFile !== undefined && (
|
||||
modelApiKeyFile.trim() !== modelApiKeyFile
|
||||
|| modelApiKeyFile.length === 0
|
||||
|| modelApiKeyFile.includes("\0")
|
||||
|| !path.isAbsolute(modelApiKeyFile)
|
||||
)) {
|
||||
throw new Error("model credential configuration is invalid");
|
||||
}
|
||||
return {
|
||||
host: env.HOST ?? "127.0.0.1",
|
||||
port: Number(env.PORT ?? 8787),
|
||||
@@ -27,5 +39,6 @@ export function loadConfig(env: Record<string, string | undefined>): AppConfig {
|
||||
settingsFile: env.SETTINGS_FILE ?? "data/settings.json",
|
||||
dataRoot: env.THT_DATA_ROOT,
|
||||
ollamaEnsureTimeoutMs: Number(env.OLLAMA_ENSURE_TIMEOUT_MS ?? 60000),
|
||||
modelApiKeyFile,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { spawn as nodeSpawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync } from "node:fs";
|
||||
import type { AppConfig } from "../config.js";
|
||||
import { RpcClient } from "../rpc/rpc-client.js";
|
||||
import { SessionBridge } from "../bridge/session-bridge.js";
|
||||
@@ -17,26 +18,90 @@ type SpawnFn = (
|
||||
options: { cwd: string; env: NodeJS.ProcessEnv },
|
||||
) => ChildProcessWithoutNullStreams;
|
||||
|
||||
const PROVIDER_KEY_ENV: Readonly<Record<string, string>> = {
|
||||
anthropic: "ANTHROPIC_API_KEY",
|
||||
openai: "OPENAI_API_KEY",
|
||||
gemini: "GEMINI_API_KEY",
|
||||
google: "GEMINI_API_KEY",
|
||||
deepseek: "DEEPSEEK_API_KEY",
|
||||
zai: "ZAI_API_KEY",
|
||||
groq: "GROQ_API_KEY",
|
||||
mistral: "MISTRAL_API_KEY",
|
||||
openrouter: "OPENROUTER_API_KEY",
|
||||
xai: "XAI_API_KEY",
|
||||
cerebras: "CEREBRAS_API_KEY",
|
||||
cohere: "COHERE_API_KEY",
|
||||
};
|
||||
const LOCAL_PROVIDERS = new Set(["ollama", "lmstudio", "local", "aritmolab"]);
|
||||
const PROVIDER_ENV_NAMES = new Set(Object.values(PROVIDER_KEY_ENV));
|
||||
|
||||
function normalizedProvider(provider: string | undefined): string | undefined {
|
||||
const value = provider?.trim().toLowerCase();
|
||||
return value || undefined;
|
||||
}
|
||||
|
||||
function readModelCredential(file: string): string {
|
||||
let fd: number | undefined;
|
||||
try {
|
||||
const before = lstatSync(file);
|
||||
if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1) throw new Error();
|
||||
fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
const info = fstatSync(fd);
|
||||
const mode = info.mode & 0o777;
|
||||
const ownedStrict = info.uid === process.getuid?.() && (mode === 0o400 || mode === 0o600);
|
||||
const dockerSecret = file.startsWith("/run/secrets/") && mode === 0o444;
|
||||
if (!info.isFile() || info.nlink !== 1 || (!ownedStrict && !dockerSecret) || info.size > 16_384) {
|
||||
throw new Error();
|
||||
}
|
||||
const value = readFileSync(fd, "utf8");
|
||||
if (!value || /\s/.test(value)) throw new Error();
|
||||
return value;
|
||||
} catch {
|
||||
throw new Error("model provider credential is unavailable");
|
||||
} finally {
|
||||
if (fd !== undefined) closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
export class PiProcessManager {
|
||||
private runtimes = new Map<string, SessionRuntime>();
|
||||
private spawnFn: (sessionId: string, author: string) => ChildProcessWithoutNullStreams;
|
||||
private spawnFn: (
|
||||
sessionId: string, author: string, provider: string | undefined,
|
||||
) => ChildProcessWithoutNullStreams;
|
||||
|
||||
constructor(private cfg: AppConfig, opts?: { spawnFn?: SpawnFn }) {
|
||||
if (opts?.spawnFn) {
|
||||
this.spawnFn = (sessionId: string, author: string) => this.spawnPi(opts.spawnFn!, sessionId, author);
|
||||
this.spawnFn = (sessionId, author, provider) =>
|
||||
this.spawnPi(opts.spawnFn!, sessionId, author, provider);
|
||||
} else {
|
||||
this.spawnFn = (sessionId: string, author: string) => this.spawnPi(nodeSpawn, sessionId, author);
|
||||
this.spawnFn = (sessionId, author, provider) =>
|
||||
this.spawnPi(nodeSpawn, sessionId, author, provider);
|
||||
}
|
||||
}
|
||||
|
||||
private spawnPi(spawnFn: SpawnFn, sessionId: string, author: string): ChildProcessWithoutNullStreams {
|
||||
private spawnPi(
|
||||
spawnFn: SpawnFn, sessionId: string, author: string, provider: string | undefined,
|
||||
): ChildProcessWithoutNullStreams {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
THT_SESSION: sessionId,
|
||||
THT_AUTHOR: author,
|
||||
};
|
||||
delete env.THT_DATA_ROOT;
|
||||
delete env.PI_PROVIDER_API_KEY;
|
||||
delete env.THT_MODEL_API_KEY_FILE;
|
||||
for (const name of PROVIDER_ENV_NAMES) delete env[name];
|
||||
if (this.cfg.dataRoot !== undefined) env.THT_DATA_ROOT = this.cfg.dataRoot;
|
||||
const normalized = normalizedProvider(provider);
|
||||
if (normalized && !LOCAL_PROVIDERS.has(normalized)) {
|
||||
const envName = PROVIDER_KEY_ENV[normalized];
|
||||
if (!envName || !this.cfg.modelApiKeyFile) {
|
||||
throw new Error("model provider credential is unavailable");
|
||||
}
|
||||
env[envName] = readModelCredential(this.cfg.modelApiKeyFile);
|
||||
} else if (this.cfg.modelApiKeyFile && !normalized) {
|
||||
throw new Error("model provider credential is unavailable");
|
||||
}
|
||||
// pi 0.73 removed `--approve`: rpc mode is headless and its argv is intentionally minimal.
|
||||
const child = spawnFn(this.cfg.piBin, ["--mode", "rpc"], {
|
||||
cwd: this.cfg.harnessDir,
|
||||
@@ -67,7 +132,8 @@ export class PiProcessManager {
|
||||
throw new Error("max Pi processes reached");
|
||||
}
|
||||
const author = o.author ?? "dev@local";
|
||||
const child = this.spawnFn(sessionId, author);
|
||||
const provider = o.provider ?? this.cfg.defaults.provider;
|
||||
const child = this.spawnFn(sessionId, author, provider);
|
||||
const rpc = new RpcClient(child);
|
||||
const bridge = new SessionBridge(rpc);
|
||||
const rt: SessionRuntime = { rpc, bridge, child };
|
||||
@@ -88,7 +154,6 @@ export class PiProcessManager {
|
||||
}
|
||||
});
|
||||
|
||||
const provider = o.provider ?? this.cfg.defaults.provider;
|
||||
const model = o.model ?? this.cfg.defaults.model;
|
||||
const thinking = o.thinking ?? this.cfg.defaults.thinking;
|
||||
|
||||
|
||||
@@ -46,3 +46,12 @@ test("loadConfig accepts an authenticated upstream trust boundary", () => {
|
||||
AUTH_MODE: "upstream",
|
||||
}).authMode).toBe("upstream");
|
||||
});
|
||||
|
||||
test("loadConfig accepts only an absolute generic model key file", () => {
|
||||
expect(loadConfig({ THT_MODEL_API_KEY_FILE: "/run/secrets/model_api_key" }).modelApiKeyFile)
|
||||
.toBe("/run/secrets/model_api_key");
|
||||
expect(() => loadConfig({ THT_MODEL_API_KEY_FILE: "relative/key" }))
|
||||
.toThrow(/model credential configuration is invalid/);
|
||||
expect(() => loadConfig({ THT_MODEL_API_KEY_FILE: " /run/secrets/key" }))
|
||||
.toThrow(/model credential configuration is invalid/);
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ import { spawn } from "node:child_process";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { chmodSync, writeFileSync } from "node:fs";
|
||||
import { PiProcessManager } from "../src/pi/pi-process-manager.js";
|
||||
import { loadConfig } from "../src/config.js";
|
||||
|
||||
@@ -149,12 +150,12 @@ test("production spawn uses explicit Pi path and passes portable data root witho
|
||||
expect(options.cwd).toBe("/app/harness");
|
||||
expect(options.env).toMatchObject({
|
||||
PATH: "/usr/local/bin:/usr/bin",
|
||||
PI_PROVIDER_API_KEY: "provider-secret",
|
||||
NODE_EXTRA_CA_CERTS: "/certs/company-ca.pem",
|
||||
THT_DATA_ROOT: "/data",
|
||||
THT_SESSION: "portable-session",
|
||||
THT_AUTHOR: "user@example.test",
|
||||
});
|
||||
expect(options.env).not.toHaveProperty("PI_PROVIDER_API_KEY");
|
||||
} finally {
|
||||
mgr.teardown("portable-session");
|
||||
vi.unstubAllEnvs();
|
||||
@@ -174,9 +175,100 @@ test("session Pi spawn omits ambient THT_DATA_ROOT when config does not provide
|
||||
try {
|
||||
await mgr.spawnFor("no-data-root", {});
|
||||
expect(calls[0][2].env).not.toHaveProperty("THT_DATA_ROOT");
|
||||
expect(calls[0][2].env.PI_PROVIDER_API_KEY).toBe("still-inherited");
|
||||
expect(calls[0][2].env).not.toHaveProperty("PI_PROVIDER_API_KEY");
|
||||
} finally {
|
||||
mgr.teardown("no-data-root");
|
||||
vi.unstubAllEnvs();
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
["anthropic", "ANTHROPIC_API_KEY"],
|
||||
["OpenAI", "OPENAI_API_KEY"],
|
||||
["gemini", "GEMINI_API_KEY"],
|
||||
["google", "GEMINI_API_KEY"],
|
||||
["deepseek", "DEEPSEEK_API_KEY"],
|
||||
["zai", "ZAI_API_KEY"],
|
||||
["openrouter", "OPENROUTER_API_KEY"],
|
||||
])("injects the generic file credential only as %s provider env", async (provider, expectedName) => {
|
||||
const secret = path.resolve(__dirname, `.model-key-${process.pid}-${provider}`);
|
||||
writeFileSync(secret, "provider-secret", { mode: 0o600 });
|
||||
const calls: any[][] = [];
|
||||
const child = recordingChild();
|
||||
child.stderr.resume = () => {};
|
||||
const mgr = new PiProcessManager(loadConfig({
|
||||
PI_BIN: "/usr/local/bin/pi", THT_MODEL_API_KEY_FILE: secret,
|
||||
}), { spawnFn: (...args: any[]) => { calls.push(args); return child as any; } });
|
||||
try {
|
||||
await mgr.spawnFor("credential-session", { provider });
|
||||
const env = calls[0][2].env;
|
||||
expect(env[expectedName]).toBe("provider-secret");
|
||||
expect(env).not.toHaveProperty("PI_PROVIDER_API_KEY");
|
||||
expect(env).not.toHaveProperty("THT_MODEL_API_KEY_FILE");
|
||||
expect(JSON.stringify(calls[0].slice(0, 2))).not.toContain("provider-secret");
|
||||
} finally {
|
||||
mgr.teardown("credential-session");
|
||||
await import("node:fs/promises").then((fs) => fs.unlink(secret));
|
||||
}
|
||||
});
|
||||
|
||||
test("local providers spawn without a model key and scrub ambient generic credentials", async () => {
|
||||
vi.stubEnv("PI_PROVIDER_API_KEY", "ambient-secret");
|
||||
vi.stubEnv("THT_MODEL_API_KEY_FILE", "/ambient/secret-path");
|
||||
vi.stubEnv("OPENAI_API_KEY", "unselected-provider-secret");
|
||||
const calls: any[][] = [];
|
||||
const child = recordingChild();
|
||||
child.stderr.resume = () => {};
|
||||
const mgr = new PiProcessManager(loadConfig({ PI_BIN: "/usr/local/bin/pi" }), {
|
||||
spawnFn: (...args: any[]) => { calls.push(args); return child as any; },
|
||||
});
|
||||
try {
|
||||
await mgr.spawnFor("local-session", { provider: "ollama" });
|
||||
expect(calls[0][2].env).not.toHaveProperty("PI_PROVIDER_API_KEY");
|
||||
expect(calls[0][2].env).not.toHaveProperty("THT_MODEL_API_KEY_FILE");
|
||||
expect(calls[0][2].env).not.toHaveProperty("OPENAI_API_KEY");
|
||||
} finally {
|
||||
mgr.teardown("local-session");
|
||||
vi.unstubAllEnvs();
|
||||
}
|
||||
});
|
||||
|
||||
test.each(["missing", "permissive", "unreadable", "directory", "symlink", "unsupported"])(
|
||||
"hosted provider credential failure is sanitized: %s", async (kind) => {
|
||||
const target = path.resolve(__dirname, `.bad-model-key-${process.pid}-${kind}`);
|
||||
if (kind === "permissive") {
|
||||
writeFileSync(target, "DO_NOT_LEAK", { mode: 0o644 });
|
||||
chmodSync(target, 0o644);
|
||||
} else if (kind === "unreadable") {
|
||||
writeFileSync(target, "DO_NOT_LEAK", { mode: 0o000 });
|
||||
} else if (kind === "directory") {
|
||||
await import("node:fs/promises").then((fs) => fs.mkdir(target));
|
||||
} else if (kind === "symlink") {
|
||||
const source = `${target}-source`;
|
||||
writeFileSync(source, "DO_NOT_LEAK", { mode: 0o600 });
|
||||
await import("node:fs/promises").then((fs) => fs.symlink(source, target));
|
||||
}
|
||||
const cfg = loadConfig({ THT_MODEL_API_KEY_FILE: target });
|
||||
const mgr = new PiProcessManager(cfg, { spawnFn: () => {
|
||||
throw new Error("spawn must not occur");
|
||||
} });
|
||||
try {
|
||||
const provider = kind === "unsupported" ? "unknown-hosted" : "anthropic";
|
||||
await expect(mgr.spawnFor("bad-secret", { provider }))
|
||||
.rejects.toThrow("model provider credential is unavailable");
|
||||
} finally {
|
||||
if (kind === "permissive") await import("node:fs/promises").then((fs) => fs.unlink(target));
|
||||
if (kind === "unreadable") {
|
||||
chmodSync(target, 0o600);
|
||||
await import("node:fs/promises").then((fs) => fs.unlink(target));
|
||||
}
|
||||
if (kind === "directory") await import("node:fs/promises").then((fs) => fs.rmdir(target));
|
||||
if (kind === "symlink") {
|
||||
await import("node:fs/promises").then(async (fs) => {
|
||||
await fs.unlink(target);
|
||||
await fs.unlink(`${target}-source`);
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { test, expect } from "vitest";
|
||||
import { spawn as nodeSpawn } from "node:child_process";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import { chmodSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { buildApp } from "../src/app.js";
|
||||
import { loadConfig } from "../src/config.js";
|
||||
|
||||
@@ -16,9 +18,14 @@ function mutApp(thtRunner: any) {
|
||||
}
|
||||
|
||||
test("POST /sessions usa i settings (workspace/provider/model/thinking) e crea+avvia", async () => {
|
||||
const modelKey = path.join(os.tmpdir(), `thoth-model-key-${process.pid}`);
|
||||
writeFileSync(modelKey, "test-model-key", { mode: 0o600 });
|
||||
chmodSync(modelKey, 0o600);
|
||||
let sessionNewArg: any;
|
||||
let spawnArg: any;
|
||||
const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), {
|
||||
const app = buildApp(loadConfig({
|
||||
THT_HARNESS_DIR: "../harness", THT_MODEL_API_KEY_FILE: modelKey,
|
||||
}), {
|
||||
thtRunner: {
|
||||
ollamaEnsure: async () => ({ ok: true }),
|
||||
sessionNew: async (o: any) => { sessionNewArg = o; return { id: "s1" }; },
|
||||
@@ -36,6 +43,7 @@ test("POST /sessions usa i settings (workspace/provider/model/thinking) e crea+a
|
||||
expect(sessionNewArg.question).toBe("q");
|
||||
const list = await app.inject({ method: "GET", url: "/sessions" });
|
||||
expect(list.json()).toEqual([{ id: "s1" }]);
|
||||
unlinkSync(modelKey);
|
||||
});
|
||||
|
||||
test("POST /sessions/:id/response inoltra al bridge (no error)", async () => {
|
||||
|
||||
Reference in New Issue
Block a user