fix: reject executable pi configuration
This commit is contained in:
@@ -6,6 +6,10 @@ import {
|
||||
loadPiEnabledModels,
|
||||
type PiEnabledModelsResult,
|
||||
} from "./enabled-models.js";
|
||||
import {
|
||||
readConfiguredPiAgentFile,
|
||||
validateDeclarativePiConfig,
|
||||
} from "./managed-config.js";
|
||||
|
||||
export interface PiModel {
|
||||
provider: string;
|
||||
@@ -23,6 +27,7 @@ interface Opts {
|
||||
ttlMs?: number;
|
||||
nowMs?: () => number;
|
||||
loadEnabledModels?: () => PiEnabledModelsResult;
|
||||
readModelsStore?: () => string | undefined;
|
||||
warn?: (message: string) => void;
|
||||
}
|
||||
|
||||
@@ -39,6 +44,11 @@ export function createPiModelLister(cfg: AppConfig, opts: Opts = {}): () => Prom
|
||||
let cache: { at: number; models: PiModel[] } | null = null;
|
||||
|
||||
return async function listModels(): Promise<PiModel[]> {
|
||||
const managedModels = opts.readModelsStore
|
||||
? opts.readModelsStore()
|
||||
: readConfiguredPiAgentFile("models.json", true);
|
||||
if (managedModels !== undefined) validateDeclarativePiConfig(managedModels);
|
||||
|
||||
if (cache && now() - cache.at < ttlMs) return cache.models;
|
||||
|
||||
const enabled = (opts.loadEnabledModels
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import {
|
||||
closeSync, constants, fstatSync, lstatSync, openSync, readFileSync,
|
||||
} from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
const MAX_AGENT_CONFIG_BYTES = 1024 * 1024;
|
||||
|
||||
export const PI_MANAGED_CONFIG_ERROR_CODE = "PI_MANAGED_CONFIG_INVALID";
|
||||
export const PI_MANAGED_CONFIG_ERROR_MESSAGE = "Pi provider/model configuration is invalid";
|
||||
|
||||
export class PiManagedConfigError extends Error {
|
||||
readonly code = PI_MANAGED_CONFIG_ERROR_CODE;
|
||||
|
||||
constructor() {
|
||||
super(PI_MANAGED_CONFIG_ERROR_MESSAGE);
|
||||
}
|
||||
}
|
||||
|
||||
export function isPiManagedConfigError(error: unknown): boolean {
|
||||
return Boolean(
|
||||
error && typeof error === "object"
|
||||
&& (error as { code?: unknown }).code === PI_MANAGED_CONFIG_ERROR_CODE,
|
||||
);
|
||||
}
|
||||
|
||||
export function parsePiConfigJson(raw: string): unknown {
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch {
|
||||
throw new PiManagedConfigError();
|
||||
}
|
||||
}
|
||||
|
||||
/** Reject every Pi shell-backed configuration value, including unknown future nested fields. */
|
||||
export function assertDeclarativePiConfig(value: unknown): void {
|
||||
const pending: unknown[] = [value];
|
||||
while (pending.length > 0) {
|
||||
const current = pending.pop();
|
||||
if (typeof current === "string") {
|
||||
if (current.startsWith("!")) throw new PiManagedConfigError();
|
||||
continue;
|
||||
}
|
||||
if (Array.isArray(current)) {
|
||||
for (const nested of current) pending.push(nested);
|
||||
continue;
|
||||
}
|
||||
if (current && typeof current === "object") {
|
||||
for (const nested of Object.values(current as Record<string, unknown>)) pending.push(nested);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function validateDeclarativePiConfig(raw: string): void {
|
||||
assertDeclarativePiConfig(parsePiConfigJson(raw));
|
||||
}
|
||||
|
||||
export function readConfiguredPiAgentFile(name: "auth.json"): string;
|
||||
export function readConfiguredPiAgentFile(name: "models.json", optional: true): string | undefined;
|
||||
export function readConfiguredPiAgentFile(
|
||||
name: "auth.json" | "models.json",
|
||||
optional = false,
|
||||
): string | undefined {
|
||||
const configuredAgentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
|
||||
const path = join(configuredAgentDir, name);
|
||||
let fd: number | undefined;
|
||||
try {
|
||||
const before = lstatSync(path);
|
||||
if (!before.isFile() || before.isSymbolicLink() || before.size > MAX_AGENT_CONFIG_BYTES) {
|
||||
throw new PiManagedConfigError();
|
||||
}
|
||||
fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
const opened = fstatSync(fd);
|
||||
if (!opened.isFile() || opened.size > MAX_AGENT_CONFIG_BYTES
|
||||
|| before.dev !== opened.dev || before.ino !== opened.ino) {
|
||||
throw new PiManagedConfigError();
|
||||
}
|
||||
return readFileSync(fd, "utf8");
|
||||
} catch (error) {
|
||||
if (optional && (error as NodeJS.ErrnoException)?.code === "ENOENT") return undefined;
|
||||
throw new PiManagedConfigError();
|
||||
} finally {
|
||||
if (fd !== undefined) {
|
||||
try { closeSync(fd); } catch { /* preserve the stable validation outcome */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,10 @@ import {
|
||||
type Settings,
|
||||
} from "../settings/settings-store.js";
|
||||
import type { PiModel } from "./list-models.js";
|
||||
import {
|
||||
PI_MANAGED_CONFIG_ERROR_MESSAGE,
|
||||
isPiManagedConfigError,
|
||||
} from "./managed-config.js";
|
||||
import { createPiProviderSmoke, type PiProviderSmoke } from "./provider-smoke.js";
|
||||
|
||||
const execFile = promisify(nodeExecFile);
|
||||
@@ -105,7 +109,10 @@ export function createPiManagement(config: AppConfig, deps: PiManagementDeps): P
|
||||
let listed: PiModel[];
|
||||
try {
|
||||
listed = await deps.listModels();
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (isPiManagedConfigError(error)) {
|
||||
throw new PiManagementError("pi_management_unavailable", PI_MANAGED_CONFIG_ERROR_MESSAGE);
|
||||
}
|
||||
throw new PiManagementError("pi_management_unavailable", "Pi model choices are unavailable");
|
||||
}
|
||||
const models: Array<{ provider: string; id: string }> = [];
|
||||
@@ -287,6 +294,7 @@ function isTimeout(error: unknown): boolean {
|
||||
}
|
||||
|
||||
function stableMessage(error: unknown, fallback: string): string {
|
||||
if (isPiManagedConfigError(error)) return PI_MANAGED_CONFIG_ERROR_MESSAGE;
|
||||
return error instanceof PiManagementError ? error.message : fallback;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { spawn as nodeSpawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import {
|
||||
closeSync, constants, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync,
|
||||
readFileSync, rmSync, writeFileSync,
|
||||
} from "node:fs";
|
||||
import { homedir, tmpdir } from "node:os";
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { AppConfig } from "../config.js";
|
||||
import { secretValue } from "../config/secret-bundle.js";
|
||||
@@ -12,9 +9,15 @@ import { RpcClient } from "../rpc/rpc-client.js";
|
||||
import { loadPiAuthProviders } from "./auth-providers.js";
|
||||
import { buildPiChildEnv, canonicalPiProvider } from "./provider-credentials.js";
|
||||
import type { PiReasoning } from "./management.js";
|
||||
import {
|
||||
PiManagedConfigError,
|
||||
isPiManagedConfigError,
|
||||
parsePiConfigJson,
|
||||
readConfiguredPiAgentFile,
|
||||
validateDeclarativePiConfig,
|
||||
} from "./managed-config.js";
|
||||
|
||||
const SMOKE_PROMPT = "Provider health check. Reply with exactly OK.";
|
||||
const MAX_AGENT_CONFIG_BYTES = 1024 * 1024;
|
||||
const SMOKE_ARGS = [
|
||||
"--mode", "rpc",
|
||||
"--no-session",
|
||||
@@ -82,14 +85,14 @@ export function createPiProviderSmoke(
|
||||
mkdirSync(isolatedAgentDir, { mode: 0o700 });
|
||||
if (configuredAuthProviders.has(canonicalProvider)) {
|
||||
const authStore = selectedProviderAuthStore(
|
||||
options.readAuthStore?.() ?? readConfiguredAgentFile("auth.json"),
|
||||
options.readAuthStore?.() ?? readConfiguredPiAgentFile("auth.json"),
|
||||
canonicalProvider,
|
||||
);
|
||||
writeFileSync(join(isolatedAgentDir, "auth.json"), authStore, { mode: 0o600, flag: "wx" });
|
||||
writeDeclarativeAgentConfig(join(isolatedAgentDir, "auth.json"), authStore);
|
||||
}
|
||||
const configuredModels = options.readModelsStore
|
||||
? options.readModelsStore()
|
||||
: readConfiguredAgentFile("models.json", true);
|
||||
: readConfiguredPiAgentFile("models.json", true);
|
||||
if (configuredModels !== undefined) {
|
||||
const modelsStore = selectedProviderModelsStore(
|
||||
configuredModels,
|
||||
@@ -97,9 +100,7 @@ export function createPiProviderSmoke(
|
||||
model,
|
||||
);
|
||||
if (modelsStore !== undefined) {
|
||||
writeFileSync(join(isolatedAgentDir, "models.json"), modelsStore, {
|
||||
mode: 0o600, flag: "wx",
|
||||
});
|
||||
writeDeclarativeAgentConfig(join(isolatedAgentDir, "models.json"), modelsStore);
|
||||
}
|
||||
}
|
||||
env.PI_CODING_AGENT_DIR = isolatedAgentDir;
|
||||
@@ -126,6 +127,7 @@ export function createPiProviderSmoke(
|
||||
]);
|
||||
} catch (error) {
|
||||
if (isProviderTimeout(error)) throw providerTimeout();
|
||||
if (isPiManagedConfigError(error)) throw new PiManagedConfigError();
|
||||
throw providerFailure();
|
||||
} finally {
|
||||
if (timer) clearTimeout(timer);
|
||||
@@ -167,43 +169,19 @@ function messageUsesTool(message: any): boolean {
|
||||
&& message.content.some((content: any) => content?.type === "toolCall"));
|
||||
}
|
||||
|
||||
function readConfiguredAgentFile(name: "auth.json"): string;
|
||||
function readConfiguredAgentFile(name: "models.json", optional: true): string | undefined;
|
||||
function readConfiguredAgentFile(
|
||||
name: "auth.json" | "models.json",
|
||||
optional = false,
|
||||
): string | undefined {
|
||||
const configuredAgentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
|
||||
const path = join(configuredAgentDir, name);
|
||||
let fd: number | undefined;
|
||||
try {
|
||||
const before = lstatSync(path);
|
||||
if (!before.isFile() || before.isSymbolicLink() || before.size > MAX_AGENT_CONFIG_BYTES) {
|
||||
throw providerFailure();
|
||||
}
|
||||
fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
const opened = fstatSync(fd);
|
||||
if (!opened.isFile() || opened.size > MAX_AGENT_CONFIG_BYTES
|
||||
|| before.dev !== opened.dev || before.ino !== opened.ino) {
|
||||
throw providerFailure();
|
||||
}
|
||||
return readFileSync(fd, "utf8");
|
||||
} catch (error) {
|
||||
if (optional && (error as NodeJS.ErrnoException)?.code === "ENOENT") return undefined;
|
||||
throw providerFailure();
|
||||
} finally {
|
||||
if (fd !== undefined) {
|
||||
try { closeSync(fd); } catch { /* preserve the sanitized smoke outcome */ }
|
||||
}
|
||||
}
|
||||
function writeDeclarativeAgentConfig(path: string, raw: string): void {
|
||||
validateDeclarativePiConfig(raw);
|
||||
writeFileSync(path, raw, { mode: 0o600, flag: "wx" });
|
||||
}
|
||||
|
||||
function selectedProviderAuthStore(raw: string, provider: string): string {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw providerFailure();
|
||||
const parsed = parsePiConfigJson(raw);
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
||||
throw new PiManagedConfigError();
|
||||
}
|
||||
const entry = Object.entries(parsed as Record<string, unknown>)
|
||||
.find(([key]) => key.trim().toLowerCase() === provider);
|
||||
if (!entry) throw providerFailure();
|
||||
if (!entry) throw new PiManagedConfigError();
|
||||
return JSON.stringify({ [entry[0]]: entry[1] });
|
||||
}
|
||||
|
||||
@@ -212,18 +190,20 @@ const PROVIDER_CONFIG_FIELDS = [
|
||||
] as const;
|
||||
|
||||
function selectedProviderModelsStore(raw: string, provider: string, model: string): string | undefined {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw providerFailure();
|
||||
const parsed = parsePiConfigJson(raw);
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
||||
throw new PiManagedConfigError();
|
||||
}
|
||||
const providers = (parsed as { providers?: unknown }).providers;
|
||||
if (!providers || typeof providers !== "object" || Array.isArray(providers)) {
|
||||
throw providerFailure();
|
||||
throw new PiManagedConfigError();
|
||||
}
|
||||
const entry = Object.entries(providers as Record<string, unknown>)
|
||||
.find(([key]) => key.trim().toLowerCase() === provider);
|
||||
if (!entry) return undefined;
|
||||
const providerConfig = entry[1];
|
||||
if (!providerConfig || typeof providerConfig !== "object" || Array.isArray(providerConfig)) {
|
||||
throw providerFailure();
|
||||
throw new PiManagedConfigError();
|
||||
}
|
||||
const source = providerConfig as Record<string, unknown>;
|
||||
const selected: Record<string, unknown> = {};
|
||||
@@ -231,7 +211,7 @@ function selectedProviderModelsStore(raw: string, provider: string, model: strin
|
||||
if (Object.hasOwn(source, field)) selected[field] = source[field];
|
||||
}
|
||||
if (Object.hasOwn(source, "models")) {
|
||||
if (!Array.isArray(source.models)) throw providerFailure();
|
||||
if (!Array.isArray(source.models)) throw new PiManagedConfigError();
|
||||
let selectedModel: unknown;
|
||||
for (const candidate of source.models) {
|
||||
if (candidate && typeof candidate === "object" && !Array.isArray(candidate)
|
||||
@@ -244,7 +224,7 @@ function selectedProviderModelsStore(raw: string, provider: string, model: strin
|
||||
if (Object.hasOwn(source, "modelOverrides")) {
|
||||
const overrides = source.modelOverrides;
|
||||
if (!overrides || typeof overrides !== "object" || Array.isArray(overrides)) {
|
||||
throw providerFailure();
|
||||
throw new PiManagedConfigError();
|
||||
}
|
||||
if (Object.hasOwn(overrides, model)) {
|
||||
selected.modelOverrides = { [model]: (overrides as Record<string, unknown>)[model] };
|
||||
|
||||
Reference in New Issue
Block a user