Merge main and include both packaged validation helpers

This commit is contained in:
Michael D'Angelo
2026-11-04 22:21:51 +00:00
26 changed files with 1208 additions and 234 deletions
@@ -81,6 +81,10 @@ export interface CoordinatorOptions {
run: DeepScanRunState,
signal: AbortSignal,
) => Promise<DeepScanRunState>;
checkFreshTarget?: (
run: DeepScanRunState,
signal: AbortSignal,
) => Promise<void>;
onComplete?: (
draft: ScanDraftInput,
signal: AbortSignal,
@@ -348,6 +352,14 @@ export class DeepScanCoordinator {
await ensureDeepScanDirectories(this.artifacts);
if (this.canceled || this.externallyFailed) return;
if (this.options.checkFreshTarget && isFreshRun(this.state)) {
await this.options.checkFreshTarget(
this.state,
this.discoveryAbortController.signal,
);
}
if (this.canceled || this.externallyFailed) return;
this.setupComplete = true;
const loopResult = await this.runIterations();
if (this.canceled || this.externallyFailed) return;
@@ -1074,6 +1086,15 @@ function cloneState(state: DeepScanRunState): DeepScanRunState {
return { ...state, config: { ...state.config } };
}
function isFreshRun(state: DeepScanRunState): boolean {
return (
!state.discoveryStarted &&
state.dispatchedCount === 0 &&
!state.persistedWorkers?.some((worker) => worker.kind !== "setup") &&
(state.persistedDedupInputs?.length ?? 0) === 0
);
}
function discoverySequence(artifactDir: string): bigint {
return workerLabelSequence(basename(dirname(artifactDir)), "discovery");
}
@@ -1,5 +1,7 @@
import { join } from "node:path";
import { createScanArtifactContext } from "../artifact-context.js";
import { recordCodexSecurityScanDraftViaWorkbench } from "../artifact-scan-draft.js";
import { runPythonWithInput } from "../python_command.js";
import { workbenchArgs } from "../workbench-arguments.js";
import { CodexSdkWorkerExecutor } from "./executor.js";
import type { DeepWorkerParentSandbox } from "./parent-sandbox.js";
@@ -58,6 +60,8 @@ export function startDeepScanEngine(options: {
onStart: options.onStart,
handoffClaimToken,
threadId,
checkFreshTarget: (state, signal) =>
checkFreshTarget(state, signal, options.pythonCommand, pluginRoot),
onComplete: async (draft, signal, publication) => {
const context = await createScanArtifactContext(
run.scanId,
@@ -93,3 +97,33 @@ export function startDeepScanEngine(options: {
},
});
}
export async function checkFreshTarget(
run: DeepScanRunState,
signal: AbortSignal,
pythonCommand: string,
pluginRoot: string,
): Promise<void> {
if (signal.aborted) return;
try {
await runPythonWithInput(
pythonCommand,
[
"-I",
"-X",
"utf8",
join(pluginRoot, "scripts", "check_deep_scan_target.py"),
],
JSON.stringify({
targetPath: run.targetPath,
includePaths: run.includePaths ?? [run.scope],
filePaths: run.filePaths ?? [],
}),
"Deep Scan target check",
signal,
);
} catch (error) {
// Cancellation and elapsed discovery budgets are finalized by the coordinator.
if (!signal.aborted) throw error;
}
}
@@ -76,6 +76,7 @@ export interface CodexSdkWorkerArtifactContext {
}
interface CodexSdkWorkerRuntimeSettings {
hasProviderEnvKey?: boolean;
environment?: Record<string, string>;
config: Record<string, unknown>;
preflightProviderOverrides?: string[];
@@ -290,7 +291,9 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {
await preflightDeepScanWorkerPermissionProfile({
...preflightOptions,
expectedProfile: workerProfile,
allowOpenAiApiKeyFallback: Boolean(openAiApiKey && !codexApiKey),
allowOpenAiApiKeyFallback: Boolean(
openAiApiKey && !codexApiKey && !runtimeSettings.hasProviderEnvKey,
),
});
const inheritedServers = new Set([
...mcpServerNames,
@@ -738,6 +741,23 @@ export async function workerRuntimeSettings(
);
}
if (isRecord(nativeProfileConfig.model_providers)) {
const providerId = workerConfig.model_provider ?? selected.model_provider;
const provider =
typeof providerId === "string"
? nativeProfileConfig.model_providers[providerId]
: undefined;
if (
isRecord(provider) &&
typeof provider.env_key === "string" &&
provider.auth == null
) {
settings.hasProviderEnvKey =
environmentVariable(
settings.environment ?? {},
provider.env_key,
process.platform,
) !== undefined;
}
const providers = preflightProviderDefinitions(
nativeProfileConfig.model_providers,
);
@@ -79,6 +79,7 @@ export const runSchema = z
sdkOwnsCompletion: z.boolean().optional(),
serviceTier: optionalString,
coordinatorGeneration: optionalValue(positiveInteger),
discoveryStarted: z.boolean().optional(),
createdAt: optionalString,
updatedAt: optionalString,
targetPath: requiredString,
@@ -113,9 +113,12 @@ export function runPythonWithInput(
args: string[],
input: string | Buffer,
label: string,
signal?: AbortSignal,
): Promise<string> {
return new Promise((resolve, reject) => {
const child = spawn(python, ["-B", ...args], {
signal,
killSignal: "SIGKILL",
stdio: ["pipe", "pipe", "pipe"],
windowsHide: true,
});
@@ -128,7 +131,16 @@ export function runPythonWithInput(
.setEncoding("utf8")
.on("data", (chunk: string) => errors.push(chunk));
let inputError: Error | undefined;
child.on("error", reject);
child.on("error", (error) => {
if (signal?.aborted) {
// A killed helper can remain in a kernel filesystem call until its mount responds.
child.stdin.destroy();
child.stdout.destroy();
child.stderr.destroy();
child.unref();
}
reject(error);
});
child.stdin.on("error", (error: Error) => {
inputError = error;
});
@@ -0,0 +1,296 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { chmod, mkdir, rm, symlink, watch, writeFile } from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import { after, test } from "node:test";
import type { DeepScanRunState } from "../src/deep-scan/types.js";
import {
createCoordinator,
eventually,
FakeExecutor,
FakeStore,
fixtureRun,
runCoordinator,
temporaryDirectories,
} from "./deep_scan_coordinator_fixture.ts";
import { importSource } from "./import-module.ts";
const python = process.env.PYTHON?.trim() || "python3";
const pluginRoot = resolve(import.meta.dirname, "../..");
const { checkFreshTarget } = await importSource("src/deep-scan/engine.ts", {
loader: { ".md": "text" },
});
function inspect(run: DeepScanRunState) {
return checkFreshTarget(
run,
new AbortController().signal,
python,
pluginRoot,
);
}
after(() => temporaryDirectories.cleanup());
test("only registered paths determine whether the target is empty", async () => {
const { run } = await fixtureRun();
run.includePaths = ["left", "right"];
const left = join(run.targetPath, "left");
const right = join(run.targetPath, "right");
await mkdir(left, { recursive: true });
await mkdir(right);
await writeFile(join(run.targetPath, "outside.py"), "");
const git = (...args: string[]) =>
execFileSync("git", ["-C", run.targetPath, ...args], { stdio: "pipe" });
git("init", "-q");
git("add", "outside.py");
git(
"-c",
"user.name=Fixture",
"-c",
"user.email=fixture@example.com",
"-c",
"commit.gpgsign=false",
"commit",
"-qm",
"outside selection",
);
await assert.rejects(
inspect({ ...run, targetPath: left, includePaths: undefined }),
/target is empty.*no security audit/iu,
);
await assert.rejects(inspect(run), /target is empty.*no security audit/iu);
// Any entry counts, even if normal source inventory would ignore it.
await writeFile(join(right, ".gitignore"), "*");
await inspect(run);
run.includePaths.reverse();
await inspect(run);
await rm(left, { recursive: true });
await writeFile(left, "");
run.includePaths = ["left"];
run.filePaths = ["left"];
await inspect(run);
});
test("a usable selection cannot mask a replaced file or an unsafe sibling", async () => {
const { run } = await fixtureRun();
await mkdir(run.targetPath);
await writeFile(join(run.targetPath, "first"), "");
const external = join(dirname(run.targetPath), "external");
await mkdir(external);
await writeFile(join(external, "source.py"), "");
await symlink(
external,
join(run.targetPath, "link"),
process.platform === "win32" ? "junction" : "dir",
);
await mkdir(join(run.targetPath, "was-file"));
for (const [sibling, error] of [
["missing", /no such file|not found|cannot find/iu],
["link", /symbolic link|outside|reparse|symlink/iu],
["../external", /inside|outside|relative|escapes/iu],
["was-file", /regular file/iu],
] as const) {
run.includePaths = ["first", sibling];
run.filePaths = sibling === "was-file" ? ["first", sibling] : ["first"];
await assert.rejects(inspect(run), error);
}
});
test(
"an unreadable directory preserves its diagnostic unless a sibling can be scanned",
{ skip: process.platform === "win32" || process.getuid?.() === 0 },
async () => {
const { run } = await fixtureRun();
const denied = join(run.targetPath, "denied");
await mkdir(denied, { recursive: true });
await writeFile(join(run.targetPath, "ok"), "");
await chmod(denied, 0);
try {
run.includePaths = ["denied"];
await assert.rejects(inspect(run), /permission denied|EACCES/iu);
run.includePaths.push("ok");
await inspect(run);
} finally {
await chmod(denied, 0o700);
}
},
);
test(
"a POSIX directory and entry retain their original filesystem bytes",
{ skip: process.platform === "win32" },
async () => {
const { run } = await fixtureRun();
const { decodePosixBytes } = await importSource(
"src/helpers/posix-path.ts",
);
const name =
process.platform === "darwin" ? Buffer.from("雪") : Buffer.from([0xff]);
const directory = Buffer.concat([Buffer.from(run.targetPath + "/"), name]);
await mkdir(directory, { recursive: true });
await writeFile(Buffer.concat([directory, Buffer.from("/"), name]), "");
run.includePaths = [decodePosixBytes(name)];
await inspect(run);
},
);
test(
"Windows distinguishes a lone surrogate from its replacement character",
{ skip: process.platform !== "win32" },
async () => {
const { run } = await fixtureRun();
await mkdir(run.targetPath);
run.includePaths = ["selected-\ud800"];
const selected = join(run.targetPath, run.includePaths[0]!);
// Create the unpaired UTF-16 name through Python; Node string paths replace it.
const changeDirectory = (operation: "mkdir" | "rmdir") =>
execFileSync(python, [
"-I",
"-c",
`import os, sys; os.${operation}(bytes.fromhex(sys.argv[1]).decode('utf-16-le','surrogatepass'))`,
Buffer.from(selected, "utf16le").toString("hex"),
]);
changeDirectory("mkdir");
const replacement = join(run.targetPath, "selected-\ufffd");
await mkdir(replacement);
await writeFile(join(replacement, "source.py"), "");
try {
await assert.rejects(inspect(run), /target is empty/iu);
} finally {
changeDirectory("rmdir");
}
},
);
for (const stop of ["cancellation", "deadline"]) {
test(
`a blocked directory read cannot delay ${stop}`,
{ timeout: 15_000 },
async (t) => {
const fixture = await fixtureRun();
const { run } = fixture;
await mkdir(run.targetPath);
const scripts = join(fixture.pluginRoot, "scripts");
await mkdir(scripts, { recursive: true });
const markerDir = join(dirname(run.targetPath), "ready");
await mkdir(markerDir);
const scriptName = "check_deep_scan_target.py";
// Stop the real helper inside enumeration. The marker arms the interruption
// only once the child owns the request, even on slow hosts.
await writeFile(
join(scripts, scriptName),
`
import os, runpy, sys, time
from pathlib import Path
real_scan = os.scandir
def blocked(path):
if os.fsdecode(path) == ${JSON.stringify(run.targetPath)}:
Path(${JSON.stringify(markerDir)}, str(os.getpid())).touch()
time.sleep(30)
return real_scan(path)
os.scandir = blocked
sys.path.insert(0, ${JSON.stringify(join(pluginRoot, "scripts"))})
runpy.run_path(${JSON.stringify(join(pluginRoot, "scripts", scriptName))}, run_name="__main__")
`,
);
const executor = new FakeExecutor();
const coordinator = createCoordinator(
fixture,
new FakeStore(run),
executor,
{
discoveryTimeoutMs: 60_000,
checkFreshTarget: (state, signal) =>
checkFreshTarget(state, signal, python, fixture.pluginRoot),
},
);
const watcher = watch(markerDir, { signal: t.signal });
const ready = watcher.next();
if (stop === "deadline") t.mock.timers.enable({ apis: ["setTimeout"] });
coordinator.start();
try {
const marker = await Promise.race([
ready,
coordinator
.settled()
.then((result: DeepScanRunState) =>
assert.fail(
result.error ?? "coordinator settled before enumeration",
),
),
]);
assert.ok(!marker.done && marker.value.filename);
const pid = Number(marker.value.filename);
assert.ok(Number.isSafeInteger(pid) && pid > 0);
if (stop === "deadline") {
t.mock.timers.tick(60_000);
t.mock.timers.reset();
} else coordinator.cancel("fixture cancellation");
const result = await coordinator.wait(undefined, 5_000);
assert.equal(
result?.status,
stop === "deadline" ? "succeeded" : "canceled",
result?.error,
);
assert.equal(
result.terminalReason,
stop === "deadline" ? "capped" : undefined,
);
assert.equal(executor.discoveryCalls, 0);
await eventually(() => {
try {
process.kill(pid, 0);
return false;
} catch (error) {
return (error as NodeJS.ErrnoException).code === "ESRCH";
}
});
} finally {
t.mock.timers.reset();
coordinator.cancel("fixture cleanup");
await watcher.return?.();
}
},
);
}
test("legacy setup workers still require admission before the first discovery", async () => {
const fixture = await fixtureRun();
const { run } = fixture;
await mkdir(run.targetPath);
run.persistedWorkers = [
{
id: "setup-1",
kind: "setup",
status: "succeeded",
mergeState: "none",
attempt: 0,
promptPath: join(run.scanDir, "setup.md"),
artifactDir: join(run.scanDir, "setup"),
},
];
const executor = new FakeExecutor();
const result = await runCoordinator(fixture, new FakeStore(run), executor, {
checkFreshTarget: inspect,
});
assert.equal(result?.status, "failed");
assert.match(result.error, /target is empty/iu);
assert.equal(executor.discoveryCalls, 0);
});
test("prior dispatch history bypasses fresh admission", async () => {
const fixture = await fixtureRun({ maxDiscoveryRuns: 2 });
fixture.run.dispatchedCount = 1;
const store = new FakeStore(fixture.run);
const executor = new FakeExecutor();
const result = await runCoordinator(fixture, store, executor, {
checkFreshTarget: async () => {
assert.fail("re-entered admission after prior dispatch");
},
});
assert.equal(result?.status, "succeeded", result?.error);
assert.equal(executor.discoveryCalls, 1);
});
@@ -2731,19 +2731,28 @@ async function testBedrockCredentialsReachWorker(
}
async function testExternalProviderCredentialsReachWorker() {
for (const [provider, key] of [
for (const [provider, key, headerKey] of [
["openrouter", "OPENROUTER_API_KEY"],
["fireworks", "FIREWORKS_API_KEY"],
]) {
await withWorkerFixture(async (fixture, promptPath, workingDirectory) => {
["synthetic", "SYNTHETIC_GATEWAY_KEY", "CODEX_API_KEY"],
["synthetic", "SYNTHETIC_GATEWAY_KEY", "OPENAI_API_KEY"],
] as const) {
const verifyCredentials: Parameters<typeof withWorkerFixture>[0] = async (
fixture,
promptPath,
workingDirectory,
) => {
const configPath = path.join(fixture.root, "provider.toml");
const deepPath = path.join(fixture.root, "workers.toml");
const profile = `scan-${provider}`;
const selectedKey = `synthetic-${provider}-scan-key`;
const accountHeaders = headerKey
? { [headerKey]: "private-scan-header" }
: {};
const settings = {
model_provider: provider,
native_profile: profile,
environment: { [key]: selectedKey },
environment: { [key]: selectedKey, ...accountHeaders },
};
await writeFile(configPath, stringifyToml({ model_provider: provider }));
await writeFile(deepPath, stringifyToml({ worker_runtime: settings }));
@@ -2757,11 +2766,18 @@ async function testExternalProviderCredentialsReachWorker() {
base_url: `https://${provider}.example.test/v1`,
wire_api: "responses",
env_key: key,
...(headerKey === "OPENAI_API_KEY"
? { requires_openai_auth: true }
: {}),
...(headerKey
? { env_http_headers: { "X-Scan-Header": headerKey } }
: {}),
},
},
}),
);
await writeFile(promptPath, "synthetic provider credential fixture");
const prompt = "CAPTURE_SYNTHETIC_OPENAI_AUTH";
await writeFile(promptPath, prompt);
const environment = {
CODEX_HOME: fixture.root,
CODEX_SECURITY_CONFIG_PATH: configPath,
@@ -2770,53 +2786,49 @@ async function testExternalProviderCredentialsReachWorker() {
CODEX_API_KEY: undefined,
OPENROUTER_API_KEY: undefined,
FIREWORKS_API_KEY: undefined,
SYNTHETIC_GATEWAY_KEY: undefined,
};
const saved = Object.keys(environment).map(
(name) => [name, process.env[name]] as const,
);
const originalSpawn = childProcess.spawn;
const launches: {
args: readonly string[];
environment: NodeJS.ProcessEnv;
}[] = [];
try {
for (const [name, value] of Object.entries(environment))
restoreEnv(name, value);
childProcess.spawn = ((
command: string,
args: readonly string[],
options: SpawnOptions,
) => {
if (args[0] === "exec")
launches.push({ args, environment: { ...options.env } });
return originalSpawn(command, args, options);
}) as typeof childProcess.spawn;
syncBuiltinESMExports();
const executor = new CodexSdkWorkerExecutor({
parentSandbox: trustedParentSandbox,
});
for (const resumeThreadId of [undefined, "fixture-provider-resume"]) {
launches.length = 0;
for (const turn of ["fresh", "resume", "compare"]) {
process.env[key] = "changed-ambient-key";
await executor.run(
workerRequest(promptPath, workingDirectory, {
resumeThreadId,
}),
if (headerKey) process.env[headerKey] = "changed-ambient-header";
if (turn === "compare") {
await executor.compareFindings(
prompt,
workingDirectory,
new AbortController().signal,
{ type: "object" },
);
} else {
await executor.run(
workerRequest(promptPath, workingDirectory, {
resumeThreadId:
turn === "resume" ? "fixture-provider-resume" : undefined,
}),
);
}
const invocation = await readJson(fixture.markerPath);
assert.equal(
invocation.providerKey ?? invocation.providerHeaders[key],
selectedKey,
);
assert.equal(launches.length, 1);
const launch = launches[0];
assert.equal(launch.environment[key], selectedKey);
assert.equal(launch.environment.OPENAI_API_KEY, undefined);
assert.equal(launch.environment.CODEX_API_KEY, undefined);
assertFlagPair(launch.args, "--profile", profile);
assertConfigOverrides(launch.args, {
assert.deepEqual(invocation.openaiAuthentication, accountHeaders);
assertFlagPair(invocation.argv, "--profile", profile);
assertConfigOverrides(invocation.argv, {
model_provider: provider,
"mcp_servers.codex-security.enabled": false,
"responses_api_metadata.codex_security_worker_role":
turn === "compare" ? "compare" : "discovery",
});
assert.equal(
launch.args.includes("resume"),
resumeThreadId !== undefined,
);
assert.equal(invocation.argv.includes("resume"), turn === "resume");
await writeFile(
deepPath,
stringifyToml({
@@ -2828,10 +2840,12 @@ async function testExternalProviderCredentialsReachWorker() {
);
}
} finally {
childProcess.spawn = originalSpawn;
syncBuiltinESMExports();
for (const [name, value] of saved) restoreEnv(name, value);
}
};
await withWorkerFixture(verifyCredentials, undefined, true, {
account: null,
requiresOpenaiAuth: headerKey === "OPENAI_API_KEY",
});
}
}
@@ -35,7 +35,7 @@ test("Deep engine preserves stopped results for an option-shaped thread ID", asy
const executor = new FakeExecutor({ blockDiscoveryAfterCalls: 0 });
const start = registry.start.bind(registry);
registry.start = (options: CoordinatorOptions) =>
start({ ...options, executor });
start({ ...options, executor, checkFreshTarget: async () => {} });
const calls: string[][] = [];
const { coordinator } = await startDeepScanEngine({
run: store.run,
@@ -1,4 +1,5 @@
import { jsonLineInputSource } from "./support/json-line-input-source.ts";
import { readFixtureCoverage } from "./deep_scan_coverage_fixture.ts";
import type { PersistedDeepScanWorker } from "../src/deep-scan/types.js";
import { readJson, readJsonLines } from "./support/json.ts";
import {
@@ -33,7 +34,9 @@ import { startRpcServer } from "./support/rpc-server.ts";
const execFileAsync = promisify(execFile);
const pluginRoot = path.resolve(mcpAppRoot, "..");
const pluginRoot = await realpath(
path.resolve(mcpAppRoot, "../../../sdk/typescript/_bundled_plugin"),
);
const workbenchPath = path.join(pluginRoot, "scripts", "workbench_db.py");
let parentSandboxState: unknown = readOnlyParentSandboxState(pluginRoot);
@@ -49,11 +52,13 @@ async function testDeepScanStdioLifecycle() {
const fixtureRoot = await temporaryDirectory("codex-security-deep-stdio-");
const targetPath = path.join(fixtureRoot, "target");
const failedTargetPath = path.join(fixtureRoot, "failed-target");
const expiredTargetPath = path.join(fixtureRoot, "expired-target");
const stateDir = path.join(fixtureRoot, "state");
const codexHome = path.join(fixtureRoot, "codex [home]");
const installedPluginRoot = path.join(codexHome, "plugins", "installed");
const runtimeConfigPath = path.join(fixtureRoot, "active-config.toml");
const projectConfigPath = path.join(fixtureRoot, "selected.yaml");
const expiredProjectConfigPath = path.join(fixtureRoot, "expired.yaml");
const startLogPath = path.join(fixtureRoot, "fake-codex-started.jsonl");
const exitLogPath = path.join(fixtureRoot, "fake-codex-exited.jsonl");
const restartControlPath = path.join(
@@ -88,11 +93,14 @@ async function testDeepScanStdioLifecycle() {
await mkdir(targetPath, { recursive: true });
await mkdir(failedTargetPath, { recursive: true });
await mkdir(expiredTargetPath, { recursive: true });
await mkdir(path.join(codexHome, "codex-security"), { recursive: true });
for (const directory of [
"scripts",
"references",
"schemas",
"shared",
"mcp/native",
".codex-plugin",
]) {
await cp(
@@ -153,6 +161,10 @@ max_discovery_runs = 2
);
await writeFakeCodex(fakeCodexPath);
await writeFile(projectConfigPath, "scan: {max_time_minutes: 30}\n");
await writeFile(
expiredProjectConfigPath,
"scan: {mode: deep, max_time_minutes: 0.000001}\n",
);
await writeFile(
runtimeConfigPath,
`model_reasoning_summary = "detailed"
@@ -256,6 +268,35 @@ service_tier = "ultrafast"
[],
);
const expired = await server.request(
5,
"tools/call",
toolCall(
"start_codex_security_deep_scan",
{
targetPath: expiredTargetPath,
projectConfigPath: expiredProjectConfigPath,
},
threadId,
),
);
assertNoError(expired);
const expiredScanId = expired.result.structuredContent.scanId;
const expiredState = await getDeepScan({
environment,
scanId: expiredScanId,
threadId,
});
assert.equal(expiredState.terminalReason, "capped");
assert.equal(expiredState.dispatchedCount, 0);
assert.equal(
expired.result.structuredContent.completion.scan.reportAvailable,
true,
);
const coverage = await readFixtureCoverage(expiredState.scanDir, stateDir);
assert.match(coverage.deferred[0].reason, /discovery time limit elapsed/);
assert.deepEqual(await readLogLines(startLogPath), []);
const targetRequest = {
targetPath,
scope: ".",
@@ -276,7 +317,10 @@ service_tier = "ultrafast"
}),
);
const scanId = await waitForScanId({ server });
const scanId = await waitForScanId({
server,
excludedScanIds: [expiredScanId],
});
await waitForDeepScanWorker({ environment, scanId, threadId });
const [startedWorker] = await waitForJsonLines(startLogPath, 1);
assert.equal(startedWorker.hasExpectedApiKey, true);
@@ -534,7 +578,7 @@ service_tier = "ultrafast"
const failedScanId = await waitForScanId({
server,
requestId: 20,
excludedScanIds: [scanId],
excludedScanIds: [expiredScanId, scanId],
});
await waitForDeepScanWorker({
environment,
@@ -1601,6 +1645,7 @@ async function getDeepScan({
async function waitForDeepScanWorker(input: Parameters<typeof getDeepScan>[0]) {
await waitFor(async () => {
const deepScan = await getDeepScan(input);
if (deepScan.status === "failed") throw new Error(deepScan.error);
const worker = deepScan.workers.find(
(candidate: PersistedDeepScanWorker) =>
candidate.kind === "discovery" && candidate.status === "running",
@@ -1704,8 +1749,10 @@ import { appendFileSync, existsSync, unlinkSync } from "node:fs";
import { spawnSync } from "node:child_process";
const args = process.argv.slice(2);
const input = Buffer.concat(await process.stdin.toArray());
const workbenchArgs = JSON.parse(input.subarray(0, input.indexOf(10)).toString('utf8'));
appendFileSync(process.env.FAKE_WORKBENCH_LAUNCH_LOG, JSON.stringify({ args, workbenchArgs, cwd: process.cwd() }) + '\\n');
const workbenchArgs = args.at(-1).endsWith('workbench_db.py')
? JSON.parse(input.subarray(0, input.indexOf(10)).toString('utf8'))
: [];
if (workbenchArgs.length) appendFileSync(process.env.FAKE_WORKBENCH_LAUNCH_LOG, JSON.stringify({ args, workbenchArgs, cwd: process.cwd() }) + '\\n');
const control = process.env.FAKE_WORKBENCH_CANCEL_FAILURE_CONTROL;
if (workbenchArgs[0] === 'cancel-scan') {
appendFileSync(process.env.FAKE_WORKBENCH_CANCEL_LOG, JSON.stringify(workbenchArgs) + '\\n');
@@ -55,6 +55,7 @@ async function testBeginProtocolAndParsing() {
scanRoot: "/fixture/scans",
});
assert.equal(result.scanId, scanId);
assert.equal(result.discoveryStarted, false);
assert.equal(result.serviceTier, "default");
assert.deepEqual(result.config, {
workers: 6,
@@ -1061,6 +1062,7 @@ function stateResult(
deepScan: {
scanId,
status: "running",
discoveryStarted: false,
targetPath: "/fixture/repository",
scope: ".",
userContext: null,
@@ -22,8 +22,10 @@ import type {
DeepScanPublication,
ScanDraftInput,
} from "../src/artifact-scan-draft.js";
import type { CoordinatorOptions } from "../src/deep-scan/coordinator.js";
import {
DeepScanCoordinator,
DeepScanCoordinatorRegistry,
FakeExecutor,
} from "./deep_scan_coordinator_fixture.ts";
@@ -33,19 +35,24 @@ const pluginRoot = path.resolve(mcpAppRoot, "..");
const workbenchPath = path.join(pluginRoot, "scripts", "workbench_db.py");
const {
WorkbenchDeepScanStore,
startDeepScanEngine,
createScanArtifactContext,
recordCodexSecurityScanDraftViaWorkbench,
saveScanDraftCheckpoint,
} = await importModule({
stdin: {
contents: `export { WorkbenchDeepScanStore } from "./src/deep-scan/store.ts";
export { startDeepScanEngine } from "./src/deep-scan/engine.ts";
export { createScanArtifactContext } from "./src/artifact-context.ts";
export { recordCodexSecurityScanDraftViaWorkbench, saveScanDraftCheckpoint } from "./src/artifact-scan-draft.ts";`,
resolveDir: mcpAppRoot,
},
loader: { ".md": "text" },
});
await testCanonicalParentCheckpointsSurviveSuccessiveWrites();
await testJoiningCallerAdmission(false);
await testJoiningCallerAdmission(true);
await testFreeformFailureMessagesAgainstRealWorkbench();
await testWorkerRetryThreadsRemainInScanUsage();
await testReducerCommitAndFinishAgainstRealWorkbench();
@@ -67,6 +74,99 @@ await testCoordinatorCommitResponseRecovery();
await testCoordinatorCommitResponseRecovery("record-deep-scan-iteration");
await testCoordinatorCommitResponseRecovery("finish-deep-scan");
async function testJoiningCallerAdmission(afterDiscoveryProgress: boolean) {
const { fixtureRoot, targetPath, environment } = await createWorkbenchFixture(
"deep-scan-joining-caller-",
);
const runWorkbench = createWorkbenchRunner(environment);
const owner = new WorkbenchDeepScanStore(runWorkbench);
const joiner = new WorkbenchDeepScanStore(runWorkbench);
const threadId = "admission-thread";
const scanRoot = path.join(fixtureRoot, "scans");
const executor = new FakeExecutor({ blockDiscoveryAfterCalls: 0 });
const registry = new DeepScanCoordinatorRegistry();
const start = registry.start.bind(registry);
registry.start = (options: CoordinatorOptions) =>
start({ ...options, executor });
try {
const created = await owner.begin({ targetPath, threadId, scanRoot });
const lease = { scanId: created.scanId, threadId };
// The joining caller sees the run before its owner starts discovery.
// Admission must use the state returned by the later claim.
const joined = await joiner.begin({ ...lease, scanRoot });
assert.equal(joined.discoveryStarted, false);
if (afterDiscoveryProgress) {
const claimed = await owner.claimCoordinator(lease);
assert.equal(claimed.acquired, true);
await owner.updateProgress({
scanId: created.scanId,
phase: "discovery",
});
const observer = await joiner.claimCoordinator(lease);
assert.equal(observer.acquired, false);
assert.equal(observer.run.discoveryStarted, true);
assert.equal(observer.run.dispatchedCount, 0);
await expireLease(environment, created.scanId);
}
await rm(path.join(targetPath, "fixture.py"));
const { coordinator } = await startDeepScanEngine({
run: joined,
store: joiner,
registry,
runWorkbench,
pluginRoot,
pythonCommand: process.env.PYTHON?.trim() || "python3",
parentSandbox: { filesystemDenies: [] },
threadId,
});
try {
if (afterDiscoveryProgress) {
await Promise.race([
executor.discoveryStarted.promise,
coordinator
.wait(undefined, 30_000)
.then((run: { error?: string } | undefined) =>
assert.fail(
run?.error ?? "Adopted coordinator did not dispatch a worker",
),
),
]);
const recovered = await joiner.get(created.scanId, threadId);
assert.equal(recovered.coordinatorGeneration, 3);
assert.ok(recovered.dispatchedCount > 0);
await assert.rejects(
owner.updateProgress({ scanId: created.scanId, phase: "discovery" }),
/newer generation/,
);
} else {
const terminal = await coordinator.wait(undefined, 30_000);
assert.equal(terminal?.status, "failed");
assert.match(terminal.error, /target is empty.*no security audit/iu);
assert.equal(executor.discoveryCalls, 0);
const persisted = await owner.get(created.scanId, threadId);
assert.equal(persisted.status, "failed");
assert.deepEqual(persisted.persistedWorkers, []);
}
} finally {
coordinator.cancel("fixture cleanup");
await coordinator.wait(undefined, 30_000);
}
} finally {
await rm(fixtureRoot, { recursive: true, force: true });
}
}
async function expireLease(environment: NodeJS.ProcessEnv, scanId: string) {
await execFileAsync(process.env.PYTHON?.trim() || "python3", [
"-c",
`import sqlite3, sys
with sqlite3.connect(sys.argv[1]) as connection:
connection.execute("UPDATE deep_scan_runs SET updated_at = '2000-01-01T00:00:00Z' WHERE scan_id = ?", (sys.argv[2],))`,
path.join(environment.CODEX_SECURITY_STATE_DIR!, "workbench.sqlite3"),
scanId,
]);
}
async function testCoordinatorCommitResponseRecovery(
exhaustOperation?: "record-deep-scan-iteration" | "finish-deep-scan",
) {
@@ -1944,15 +2044,7 @@ async function testReplacementFailureDuringCancellation() {
assert.equal((await store.get(run.scanId, threadId)).status, "running");
// Expire only the lease clock; claim and failure use the real workbench.
await execFileAsync(process.env.PYTHON?.trim() || "python3", [
"-c",
`import sqlite3, sys
connection = sqlite3.connect(sys.argv[1])
connection.execute("UPDATE deep_scan_runs SET updated_at = ? WHERE scan_id = ?", ("2000-01-01T00:00:00Z", sys.argv[2]))
connection.commit()`,
path.join(environment.CODEX_SECURITY_STATE_DIR, "workbench.sqlite3"),
run.scanId,
]);
await expireLease(environment, run.scanId);
await rm(
path.join(
run.scanDir,
+1
View File
@@ -61,6 +61,7 @@
"schemas/tools/review-items.schema.json",
"schemas/tools/scan-draft.schema.json",
"scripts/candidate_identity.py",
"scripts/check_deep_scan_target.py",
"scripts/codex_profile.mjs",
"scripts/codex_session.mjs",
"scripts/deep_scan_config.py",
@@ -0,0 +1,75 @@
"""Check the physical contents of the targets registered for a fresh Deep Scan."""
from __future__ import annotations
import errno
import json
import os
import stat
import sys
from pathlib import Path
def check_selected_targets(root: Path, selections: list[str], file_paths: list[str]) -> None:
files = set(file_paths)
def check_path(selection: str) -> tuple[Path, bool]:
relative = Path(selection)
if (
not selection
or relative.anchor
or ".." in relative.parts
or (os.name == "nt" and ":" in selection)
):
raise ValueError(f"Scope must be inside repo: {selection}")
mode = root.lstat().st_mode
if not stat.S_ISDIR(mode):
raise ValueError(f"Deep Scan repository is no longer a directory: {root}")
target = root
for part in relative.parts:
target /= part
info = target.lstat()
mode = info.st_mode
if stat.S_ISLNK(mode) or getattr(info, "st_reparse_tag", 0) & 0x20000000:
raise ValueError(f"Requested scope must not contain symbolic links: {target}")
if not target.resolve(strict=True).is_relative_to(root):
raise ValueError(f"Scope must be inside repo: {target}")
regular = stat.S_ISREG(mode)
if selection in files and not regular:
raise ValueError(f"Selected file is no longer a regular file: {selection}")
if not regular and not stat.S_ISDIR(mode):
raise OSError(errno.ENOTDIR, "Expected a regular file or directory", str(target))
return target, regular
# Every selection must be valid, even when another file or directory is usable.
for selection in selections:
check_path(selection)
failure = None
for selection in selections:
try:
# A previously validated directory may have changed during another probe.
target, regular = check_path(selection)
if regular:
return
with os.scandir(target) as entries:
if next(entries, None) is not None:
return
except OSError as exc:
if selection in files:
raise
if failure is None:
failure = exc
if failure is not None:
raise failure
raise ValueError("Deep Scan target is empty; no security audit was performed.")
if __name__ == "__main__":
request = json.load(sys.stdin)
try:
check_selected_targets(
Path(request["targetPath"]), request["includePaths"], request["filePaths"]
)
except (OSError, ValueError) as exc:
sys.exit(str(exc))
@@ -17,6 +17,7 @@ import workbench_saved_results as saved_results
from deep_scan_config import resolve_deep_scan_setup
from workbench.handoff import require_current_continuation
from workbench.storage import create_private_directory
from workbench_constants import PHASES
from workbench_source_scopes import capture_source_scopes
from workbench_target import directory_snapshot_regular_file_count
from workbench_validation import optional_text, require_uuid, user_context_argument
@@ -338,6 +339,11 @@ def deep_scan_state(connection: sqlite3.Connection, scan_id: str) -> dict[str, A
"coordinatorGeneration": run["coordinator_generation"],
"status": run["status"],
"phase": run["phase"],
# Older coordinators could persist discovery on the parent before dispatching.
"discoveryStarted": (
PHASES.index(scan["phase"]) >= PHASES.index("discovery")
or run["phase"] in {"discovery", "reducing"}
),
"config": {
"workers": run["workers"],
"subagents": run["subagents"],
@@ -3,9 +3,11 @@ from __future__ import annotations
import hashlib
import json
import os
import runpy
import sqlite3
import uuid
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path
@@ -93,6 +95,33 @@ def start_empty_target_scan(tmp_path: Path, *, config: str | None = None) -> Dee
return DeepScan(state_dir, codex_home, str(run["scanId"]), Path(str(run["scanDir"])))
@pytest.mark.cross_platform
def test_target_admission_reads_one_entry_without_looking_up_its_type(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
script = Path(__file__).resolve().parents[1] / "scripts" / "check_deep_scan_target.py"
check_selected_targets = runpy.run_path(str(script))["check_selected_targets"]
events = []
def entries():
events.append("read")
# A filesystem can report DT_UNKNOWN. Any entry-type lookup here fails.
yield object()
pytest.fail("admission read a second directory entry")
@contextmanager
def scandir(path):
assert Path(path) == tmp_path
try:
yield entries()
finally:
events.append("closed")
monkeypatch.setattr(os, "scandir", scandir)
check_selected_targets(tmp_path, ["."], [])
assert events == ["read", "closed"]
def restore_v53_schema(state_dir: Path) -> None:
with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
connection.execute("DROP TRIGGER classify_legacy_scan_recipe")
@@ -431,6 +460,7 @@ def test_legacy_generation_with_active_worker_observes_grace_then_adopts(tmp_pat
assert adopted["deepScan"]["coordinatorGeneration"] == 2
assert adopted["deepScan"]["workers"][0]["status"] == "canceled"
assert adopted["deepScan"]["dispatchedCount"] == 0
assert adopted["deepScan"]["discoveryStarted"] is True
def test_expired_coordinator_preserves_incomplete_setup(tmp_path: Path) -> None:
@@ -450,6 +480,35 @@ def test_expired_coordinator_preserves_incomplete_setup(tmp_path: Path) -> None:
assert not inventory.exists()
def test_observer_and_successor_see_discovery_progress_before_first_dispatch(
tmp_path: Path,
) -> None:
deep = start_empty_target_scan(tmp_path)
owner = claim_deep_scan_coordinator(deep.state_dir, deep.codex_home, deep.id)["deepScan"]
assert owner["discoveryStarted"] is False
deep.command(
"update-progress",
"--phase",
"discovery",
"--coordinator-generation",
str(owner["coordinatorGeneration"]),
)
before = deep.read("thread-deep-scan")
observed = claim_deep_scan_coordinator(deep.state_dir, deep.codex_home, deep.id)
assert observed["coordinatorDisposition"] == "observing"
assert observed["deepScan"]["updatedAt"] == before["updatedAt"]
expire_deep_scan_coordinator(deep.state_dir, deep.id)
adopted = claim_deep_scan_coordinator(deep.state_dir, deep.codex_home, deep.id)
assert adopted["coordinatorDisposition"] == "adopted"
for run in (before, observed["deepScan"], adopted["deepScan"]):
assert run["phase"] == "setup"
assert run["discoveryStarted"] is True
assert run["dispatchedCount"] == 0
assert run["workers"] == []
@pytest.mark.cross_platform
def test_paused_discovery_resumes_after_restart_with_original_handoff_claim(
tmp_path: Path,
+7
View File
@@ -104,6 +104,13 @@ the stored login. Patch follow-up assessments and `scan --patch` retain the
chosen authentication. Environment keys do not replace the saved login.
The SDK uses `auth` on `run()`, `validate()`, and `preflight()`.
For a scan using a custom native provider, `auto` and `api-key` use the
environment variable declared by `model_providers.<id>.env_key`, including
when a Codex file profile selects that provider. Set that variable before
starting the scan. To use `--auth chatgpt`, select a provider configured for
account authentication. A custom provider that requires its own key cannot
honor that combination.
Stored OpenAI credentials live in
`$CODEX_SECURITY_STATE_DIR/codex-home`, or
`$CODEX_HOME/state/plugins/codex-security/codex-home`. Keep this private home
+138 -81
View File
@@ -67,6 +67,7 @@ import {
NO_CREDENTIALS_MESSAGE,
accountStatus,
configuredCodexHome,
environmentEntry,
CodexLoginHandle,
loginApiKey as persistApiKey,
logout as codexLogout,
@@ -341,12 +342,8 @@ interface PreparedSession {
preflightConfig: JsonObject;
sessionConfig: JsonObject;
modelProvider: unknown;
externalProvider:
| (Omit<
(typeof EXTERNAL_CODEX_PROVIDERS)[keyof typeof EXTERNAL_CODEX_PROVIDERS],
"env_key"
> & { env_key: string })
| null;
providerEnvKey?: string;
nativeProviderEnvironment?: Record<string, string>;
apiKey: string | null;
scanEnvironment: ProcessEnvironment;
authentication: ScanAuthentication;
@@ -987,10 +984,14 @@ export class CodexSecurity {
);
const git = await inspectTrustedExecutable(
"git",
selectedScanEnvironment(
runtime.environment,
options.auth,
session.modelProvider,
withoutProviderKey(
selectedScanEnvironment(
runtime.environment,
options.auth,
session.modelProvider,
session.providerEnvKey,
),
session.providerEnvKey,
),
[
(await gitMarkerRoot(inputs.repository, signal, "outermost")) ??
@@ -2187,11 +2188,14 @@ export class CodexSecurity {
} = session;
let git: InspectedExecutable = {
executable: null,
environment: selectedScanEnvironment(
runtime.environment,
options.auth,
modelProvider,
session.externalProvider?.env_key,
environment: withoutProviderKey(
selectedScanEnvironment(
runtime.environment,
options.auth,
modelProvider,
session.providerEnvKey,
),
session.providerEnvKey,
),
};
for (const root of [
@@ -2253,14 +2257,13 @@ export class CodexSecurity {
runtime.environment,
options.auth,
modelProvider,
session.externalProvider?.env_key,
session.providerEnvKey,
),
),
...(session.apiKey === null
? {}
: {
[session.externalProvider?.env_key ?? "CODEX_API_KEY"]:
session.apiKey,
[session.providerEnvKey ?? "CODEX_API_KEY"]: session.apiKey,
}),
};
const { environment: workerEnvironment, ...workerRuntimeConfig } =
@@ -2269,6 +2272,7 @@ export class CodexSecurity {
modelProvider,
scanDir,
workerProviderEnvironment,
session.nativeProviderEnvironment,
);
const sqliteHome = workerRuntimeConfig["sqlite_home"];
const sqliteEnvironment: Record<string, string> =
@@ -3640,6 +3644,7 @@ export class CodexSecurity {
{
surface: this.#surface,
singleTurn: options.maxCostUsd !== undefined,
nativeProviderEnvironment: session.nativeProviderEnvironment,
},
),
...inferenceOptions,
@@ -4169,7 +4174,7 @@ export class CodexSecurity {
runtimeHome,
python,
modelProvider,
externalProvider,
providerEnvKey,
apiKey,
sessionConfig,
} = session;
@@ -4185,15 +4190,13 @@ export class CodexSecurity {
: runtime.environment,
auth,
modelProvider,
externalProvider?.env_key,
providerEnvKey,
),
),
),
git,
),
...(externalProvider === null
? {}
: { [externalProvider.env_key]: apiKey! }),
...(providerEnvKey === undefined ? {} : { [providerEnvKey]: apiKey! }),
CODEX_HOME: runtime.codexHome,
...runtimePaths,
};
@@ -4238,10 +4241,9 @@ export class CodexSecurity {
? undefined
: this.#codexCommand().command;
let sdkEnvironment = definedEnvironment({
...session.nativeProviderEnvironment,
...withoutOpenAiApiKeys(environment),
...(externalProvider === null
? {}
: { [externalProvider.env_key]: apiKey! }),
...(providerEnvKey === undefined ? {} : { [providerEnvKey]: apiKey! }),
});
if (
process.platform === "win32" &&
@@ -4258,7 +4260,7 @@ export class CodexSecurity {
...(codexPathOverride === undefined
? {}
: { codexPathOverride: executablePathForSpawn(codexPathOverride) }),
...(externalProvider !== null || apiKey === null ? {} : { apiKey }),
...(providerEnvKey !== undefined || apiKey === null ? {} : { apiKey }),
...(runtime.providerProfile === undefined
? {}
: { nativeProfile: runtime.providerProfile.name }),
@@ -4337,7 +4339,6 @@ export class CodexSecurity {
preflightConfig,
sessionConfig: preflightConfig,
modelProvider: "host",
externalProvider: null,
apiKey: null,
scanEnvironment: environment,
authentication: { method: "host", verified: false },
@@ -4360,27 +4361,23 @@ export class CodexSecurity {
);
const commandAuth = hasCommandAuth(requestedConfig);
const modelProvider = scanModelProvider(requestedConfig);
const externalProvider =
!commandAuth && isExternalModelProvider(modelProvider)
? {
...EXTERNAL_CODEX_PROVIDERS[modelProvider],
env_key: scanProviderEnvKey(requestedConfig)!,
}
: null;
const providerEnvKey = commandAuth
? undefined
: scanProviderEnvKey(requestedConfig);
let authentication = scanAuthentication(
this.#dependencies.environment,
options.auth,
modelProvider,
commandAuth,
false,
externalProvider?.env_key,
providerEnvKey,
);
const apiKey =
authentication.method === "api_key"
? environmentApiKey(
this.#dependencies.environment,
modelProvider,
externalProvider?.env_key,
providerEnvKey,
)
: null;
const scanEnvironment = selectedScanEnvironment(
@@ -4389,7 +4386,7 @@ export class CodexSecurity {
: this.#dependencies.environment,
options.auth,
modelProvider,
externalProvider?.env_key,
providerEnvKey,
);
if (this.#dependencies.prepareRuntime === undefined) {
const credentialHome = await prepareCodexSecurityCredentialHome(
@@ -4487,7 +4484,7 @@ export class CodexSecurity {
}
await releaseCredentialHome?.();
releaseCredentialHome = null;
if (externalProvider === null && apiKey !== null) {
if (providerEnvKey === undefined && apiKey !== null) {
this.#runtimeCredentialSource = "api_key";
}
if (
@@ -4518,7 +4515,7 @@ export class CodexSecurity {
runtime.codexHome,
options.auth,
modelProvider,
externalProvider?.env_key,
providerEnvKey,
);
if (
options.safetyIdentifier !== undefined &&
@@ -4533,11 +4530,15 @@ export class CodexSecurity {
);
}
notifyObserver(options, "onAuthentication")(authentication);
const helperEnvironment = withoutProviderKey(
scanEnvironment,
providerEnvKey,
);
const python = await (
this.#dependencies.resolvePluginPython ?? resolvePluginPython
)({
configuredPath: this.config.pythonPath,
environment: scanEnvironment,
environment: helperEnvironment,
protectedRoot,
signal,
});
@@ -4550,9 +4551,23 @@ export class CodexSecurity {
preflightConfig,
sessionConfig,
modelProvider,
externalProvider,
providerEnvKey,
nativeProviderEnvironment:
providerEnvKey !== undefined &&
apiKey !== null &&
!isExternalModelProvider(modelProvider)
? {
...declaredProviderEnvironment(providers, {
...(options.auth === "chatgpt"
? withoutOpenAiApiKeys(this.#dependencies.environment)
: this.#dependencies.environment),
...withoutOpenAiApiKeys(runtime.environment),
}),
[providerEnvKey]: apiKey,
}
: undefined,
apiKey,
scanEnvironment,
scanEnvironment: helperEnvironment,
authentication,
approvalPolicy,
python,
@@ -5057,13 +5072,14 @@ export class CodexSecurity {
return await this.#dependencies.prepareRuntime(this.config, signal);
}
const modelProvider = scanModelProvider(requestedConfig);
const providerEnvKey = scanProviderEnvKey(requestedConfig);
const processEnvironment = selectedScanEnvironment(
hasCommandAuth(requestedConfig)
? withoutOpenAiApiKeys(this.#dependencies.environment)
: this.#dependencies.environment,
auth,
modelProvider,
scanProviderEnvKey(requestedConfig),
providerEnvKey,
);
const codexHome = await realpath(
codexSecurityCredentialHome(processEnvironment),
@@ -5118,7 +5134,7 @@ export class CodexSecurity {
: join(deepScanConfigDirectory, "deep-scan-config.toml");
const credentialsAvailable =
hasCommandAuth(requestedConfig) ||
isExternalModelProvider(modelProvider) ||
providerEnvKey !== undefined ||
modelProvider === "amazon-bedrock"
? false
: await initialCredentialsAvailable(
@@ -5973,32 +5989,31 @@ export function scanAuthentication(
verified: false,
};
}
if (auth === "chatgpt" && !isExternalModelProvider(modelProvider)) {
const provider = isExternalModelProvider(modelProvider)
? EXTERNAL_CODEX_PROVIDERS[modelProvider]
: undefined;
const selectedKey = providerEnvKey ?? provider?.env_key;
if (auth === "chatgpt" && provider === undefined) {
if (selectedKey !== undefined)
throw new ConfigurationError(
`ChatGPT authentication cannot use the ${modelProvider} provider's required ${selectedKey} environment key. Use '--auth api-key' or choose a provider configured for ChatGPT.`,
);
return { method: "stored_credentials", verified: false };
}
const key = environmentApiKeyEntry(
environment,
modelProvider,
providerEnvKey,
);
if (key === null && isExternalModelProvider(modelProvider)) {
const provider = EXTERNAL_CODEX_PROVIDERS[modelProvider];
const key = environmentApiKeyEntry(environment, modelProvider, selectedKey);
if (key === null && selectedKey !== undefined) {
if (preflight && auth === "auto") {
return {
method: "api_key",
source: providerEnvKey ?? provider.env_key,
source: selectedKey,
verified: false,
};
}
throw new AuthenticationRequiredError(
`Set ${providerEnvKey ?? provider.env_key} to run a scan through ${provider.name}.`,
`Set ${selectedKey} to run a scan through ${provider?.name ?? modelProvider}.`,
);
}
if (
auth === "api-key" &&
key === null &&
!isExternalModelProvider(modelProvider)
) {
if (auth === "api-key" && key === null) {
throw new AuthenticationRequiredError(
"API-key authentication requires OPENAI_API_KEY or CODEX_API_KEY. " +
"Set a valid API key or use '--auth chatgpt'.",
@@ -6063,20 +6078,32 @@ export async function runtimeScanAuthentication(
return authentication;
}
/** Local helpers do not authenticate model requests. */
function withoutProviderKey(
environment: ProcessEnvironment,
key: string | undefined,
): ProcessEnvironment {
if (key === undefined) return environment;
const child = { ...environment };
for (const name of Object.keys(child)) {
if (name.toUpperCase() === key.toUpperCase()) delete child[name];
}
forwardExternalImportSetting(environment, child);
return child;
}
/** @internal */
export function selectedScanEnvironment(
environment: ProcessEnvironment,
auth: ScanAuthMode = "auto",
modelProvider?: unknown,
providerEnvKey?: string,
config?: JsonObject,
): ProcessEnvironment {
const standardProviderKey = isExternalModelProvider(modelProvider)
? EXTERNAL_CODEX_PROVIDERS[modelProvider].env_key
: null;
const selectedProviderKey =
standardProviderKey === null
? null
: (providerEnvKey ?? standardProviderKey);
const selectedProviderKey = providerEnvKey ?? standardProviderKey;
const bedrockProvider = modelProvider === "amazon-bedrock";
if (auth !== "chatgpt" && selectedProviderKey === null && !bedrockProvider) {
return environment;
@@ -6105,6 +6132,20 @@ export function selectedScanEnvironment(
return true;
}),
);
if (
config !== undefined &&
providerEnvKey !== undefined &&
standardProviderKey === null &&
!hasCommandAuth(config)
) {
Object.assign(
selected,
declaredProviderEnvironment(
resolveCodexProfile(config)["model_providers"],
auth === "chatgpt" ? withoutOpenAiApiKeys(environment) : environment,
),
);
}
forwardExternalImportSetting(environment, selected);
return selected;
}
@@ -6213,9 +6254,14 @@ function environmentApiKeyEntry(
modelProvider?: unknown,
providerEnvKey?: string,
): { source: string; value: string } | null {
const keys = isExternalModelProvider(modelProvider)
? [providerEnvKey ?? EXTERNAL_CODEX_PROVIDERS[modelProvider].env_key]
: (["OPENAI_API_KEY", "CODEX_API_KEY"] as const);
if (providerEnvKey !== undefined && !isExternalModelProvider(modelProvider)) {
const value = environmentEntry(environment, providerEnvKey);
return value?.trim() ? { source: providerEnvKey, value } : null;
}
const keys =
providerEnvKey === undefined
? ["OPENAI_API_KEY", "CODEX_API_KEY"]
: [providerEnvKey];
for (const requested of keys) {
const value = environmentValue(environment, requested)?.trim();
if (value) return { source: requested, value };
@@ -6686,18 +6732,11 @@ async function requireCurrentDeepScanPlugin(
}
}
function selectedWorkerRuntimeConfig(
config: JsonObject,
selectedProvider: unknown,
workingDirectory: string,
function declaredProviderEnvironment(
providers: unknown,
environment: ProcessEnvironment,
): JsonObject {
const provider =
typeof selectedProvider === "string" ? selectedProvider : undefined;
const resolved = resolveCodexProfile(config);
resolveNestedConfigPaths(resolved, workingDirectory);
const providers = resolved["model_providers"];
const providerEnvironmentNames = isRecord(providers)
): Record<string, string> {
const names = isRecord(providers)
? Object.values(providers)
.flatMap((providerConfig) =>
isRecord(providerConfig)
@@ -6711,8 +6750,8 @@ function selectedWorkerRuntimeConfig(
)
.filter((name): name is string => typeof name === "string")
: [];
const providerEnvironment = Object.fromEntries(
providerEnvironmentNames.flatMap((name) => {
return Object.fromEntries(
names.flatMap((name) => {
const key =
process.platform === "win32"
? Object.keys(environment)
@@ -6723,6 +6762,23 @@ function selectedWorkerRuntimeConfig(
return value === undefined ? [] : [[name, value]];
}),
);
}
function selectedWorkerRuntimeConfig(
config: JsonObject,
selectedProvider: unknown,
workingDirectory: string,
environment: ProcessEnvironment,
nativeProviderEnvironment?: Record<string, string>,
): JsonObject {
const provider =
typeof selectedProvider === "string" ? selectedProvider : undefined;
const resolved = resolveCodexProfile(config);
resolveNestedConfigPaths(resolved, workingDirectory);
const providers = resolved["model_providers"];
const providerEnvironment =
nativeProviderEnvironment ??
declaredProviderEnvironment(providers, environment);
// Workers use separate directories; preserve the parent scan's native paths.
for (const key of [...MODEL_FILE_SETTINGS, "sqlite_home"]) {
const file = resolved[key];
@@ -6840,7 +6896,8 @@ function standaloneFindingForPrompt(finding: string | object): string {
return jsonForPrompt(finding);
}
function definedEnvironment(
/** @internal */
export function definedEnvironment(
environment: ProcessEnvironment,
): Record<string, string> {
const child = Object.fromEntries(
+7 -8
View File
@@ -1656,7 +1656,6 @@ export async function runCodexSkillCommand(
codexHome,
output.auth,
provider,
providerEnvKey,
);
if (output.appServer !== undefined) {
const controller = new AbortController();
@@ -4723,11 +4722,10 @@ export async function main(
config,
scanCodexHome(dependencies.environment),
);
if (hasCommandAuth(effectiveConfig)) return auth;
return await chooseInteractiveAuthentication(
{
auth,
provider: scanModelProvider(effectiveConfig),
config: effectiveConfig,
command: "policy",
signal,
},
@@ -9781,24 +9779,25 @@ function diagnosticValue(value: unknown): string {
async function chooseInteractiveAuthentication(
options: {
auth: ScanAuthMode | undefined;
provider: unknown;
config: JsonObject;
command: "scan" | "policy";
signal: AbortSignal;
},
errorOutput: Writable,
dependencies: CliDependencies,
): Promise<ScanAuthMode | undefined> {
const { auth, provider, signal } = options;
const { auth, config, signal } = options;
if (
errorOutput.isTTY !== true ||
isExternalModelProvider(provider) ||
hasCommandAuth(config) ||
scanProviderEnvKey(config) !== undefined ||
(auth !== undefined && auth !== "auto")
)
return auth;
const authentication = scanAuthentication(
dependencies.environment,
auth,
provider,
scanModelProvider(config),
);
if (authentication.method !== "api_key") return auth;
const prompt =
@@ -10061,7 +10060,7 @@ async function executeScan(
? await chooseInteractiveAuthentication(
{
auth: arguments_.auth,
provider,
config: effectiveConfiguration,
command: "scan",
signal: preparationAbortController.signal,
},
+1
View File
@@ -169,6 +169,7 @@ export async function runComponentScans(
auth,
provider,
providerEnvKey,
configuration,
);
}
const repository = await normalizeRepository(
+8 -2
View File
@@ -127,12 +127,18 @@ export function scanProviderEnvKey(
config: Readonly<JsonObject>,
): string | undefined {
const selected = scanModelProvider(config);
if (!isExternalModelProvider(selected)) return undefined;
if (
typeof selected !== "string" ||
["openai", "ollama", "lmstudio", "amazon-bedrock"].includes(selected)
)
return undefined;
const providers = resolveCodexProfile(config)["model_providers"];
const provider = isObject(providers) ? providers[selected] : undefined;
return isObject(provider) && typeof provider["env_key"] === "string"
? provider["env_key"]
: EXTERNAL_CODEX_PROVIDERS[selected].env_key;
: isExternalModelProvider(selected)
? EXTERNAL_CODEX_PROVIDERS[selected].env_key
: undefined;
}
/** @internal Native Codex validates the auth table, including invalid selections. */
+43 -5
View File
@@ -15,6 +15,9 @@ import { z } from "zod";
import { characterCount, MAX_CODEX_INPUT_CHARACTERS } from "./codex-prompt.js";
import {
scanCodexHome,
scanAuthentication,
selectedScanEnvironment,
definedEnvironment,
type CodexSecuritySurface,
type ScanAuthMode,
} from "./api.js";
@@ -29,6 +32,8 @@ import {
DEFAULT_CODEX_CONFIG,
deepMerge,
hasCommandAuth,
isExternalModelProvider,
scanProviderEnvKey,
mergedCodexConfig,
readCodexFileProfile,
normalizeLegacyWindowsSandboxOverride,
@@ -269,7 +274,11 @@ export async function matchScanFindings(
export async function matchScanFindingsInternal(
input: ScanComparisonInput & SavedComparisonContext,
options: ScanComparisonOptions = {},
runtimeOptions: { surface: CodexSecuritySurface; singleTurn?: boolean },
runtimeOptions: {
surface: CodexSecuritySurface;
singleTurn?: boolean;
nativeProviderEnvironment?: Record<string, string>;
},
): Promise<ScanComparisonResult> {
options.signal?.throwIfAborted();
validateComparisonInput(input);
@@ -543,7 +552,9 @@ export async function matchScanFindingsInternal(
async function startReadOnlyCodexThread(
options: ReadOnlyCodexOptions,
runtimeOptions: Parameters<typeof runReadOnlyCodex>[3],
runtimeOptions: Parameters<typeof runReadOnlyCodex>[3] & {
nativeProviderEnvironment?: Record<string, string>;
},
): Promise<{
thread: ReturnType<ReadOnlyCodex["startThread"]>;
cleanup?: () => Promise<void>;
@@ -635,12 +646,19 @@ async function startReadOnlyCodexThread(
const effectiveFeatures = resolveCodexProfile(
scanCyberAccessConfig(providerConfig, options.cyberAccessProgram),
)["features"] as JsonObject | undefined;
const modelProvider = scanModelProvider(providerConfig);
const nativeKey =
!commandAuth && !isExternalModelProvider(modelProvider)
? scanProviderEnvKey(providerConfig)
: undefined;
const environment = await comparisonEnvironment(
source,
accountStatus,
options.signal,
undefined,
providerConfig,
nativeKey,
options.auth,
);
const command = resolveCodexCommand(environment);
const codexOptions: CodexOptions = {
@@ -649,9 +667,11 @@ async function startReadOnlyCodexThread(
env: environment,
// The SDK forwards its apiKey option as CODEX_API_KEY for Codex exec.
apiKey:
environmentEntry(environment, "OPENAI_API_KEY")?.trim() ||
environmentEntry(environment, "CODEX_API_KEY")?.trim() ||
undefined,
nativeKey !== undefined
? undefined
: environmentEntry(environment, "OPENAI_API_KEY")?.trim() ||
environmentEntry(environment, "CODEX_API_KEY")?.trim() ||
undefined,
config: {
...sdkConfig,
windows,
@@ -717,6 +737,15 @@ async function startReadOnlyCodexThread(
codexOptions.configOverrides = permissions.configOverrides;
requestedPermissionProfile = permissions.permissionProfileId;
}
if (
nativeKey !== undefined &&
runtimeOptions.nativeProviderEnvironment !== undefined
) {
codexOptions.env = {
...runtimeOptions.nativeProviderEnvironment,
...environment,
};
}
const codex =
profile === undefined
? new Codex(codexOptions)
@@ -1221,6 +1250,8 @@ export async function comparisonEnvironment(
signal?: AbortSignal,
prepareCredentialHome: typeof prepareCodexSecurityCredentialHome = prepareCodexSecurityCredentialHome,
config?: JsonObject,
nativeKey?: string,
auth: ScanAuthMode = "api-key",
): Promise<Record<string, string>> {
signal?.throwIfAborted();
const environment = Object.fromEntries(
@@ -1235,6 +1266,13 @@ export async function comparisonEnvironment(
environment[key] = home;
}
}
if (nativeKey !== undefined && config !== undefined) {
const provider = scanModelProvider(config);
scanAuthentication(environment, auth, provider, false, false, nativeKey);
return definedEnvironment(
selectedScanEnvironment(environment, auth, provider, nativeKey, config),
);
}
if (
hasCommandAuth(config ?? (await readCodexHomeConfig(environment, signal)))
) {
@@ -266,6 +266,7 @@ describe("one-shot scan events", () => {
"OPENROUTER_API_KEY",
"FIREWORKS_API_KEY",
"CHEAPER_INFERENCE_API_KEY",
"CUSTOM_GATEWAY_TOKEN",
] as const) {
for (const status of ["not_granted", "unknown"] as const) {
const { warnings } = await runTacEvents(
@@ -11,7 +11,7 @@ import { createInterface } from "node:readline";
import { executablePathForSpawn, resolveCodexCommand } from "../src/runtime.js";
import { copyCredentialTestPlugin, PLUGIN_ROOT } from "./plugin-root.js";
import { profileConfigOverrides } from "../../../plugins/codex-security/scripts/codex_profile.mjs";
import { TestClient } from "./support/api-client.js";
import { TestClient, mockWorkbench } from "./support/api-client.js";
import { preparedRuntime } from "./support/api-events.js";
import { createApiTestFixtures } from "./support/temporary-directories.js";
@@ -273,6 +273,8 @@ test.each([
await mkdir(sourceHome, { mode: 0o700 });
await mkdir(sharedHome, { recursive: true, mode: 0o700 });
const providerId =
selection === "file custom only" ? "synthetic.gateway" : "openrouter";
const ready = [
Promise.withResolvers<void>(),
Promise.withResolvers<void>(),
@@ -377,9 +379,9 @@ test.each([
join(sourceHome, `review-${index}.config.toml`),
stringifyToml({
model: "gpt-5.6-terra",
model_provider: "openrouter",
model_provider: providerId,
model_providers: {
openrouter: provider,
[providerId]: provider,
"required.gateway": {
name: "Managed selection",
wire_api: "responses",
@@ -576,7 +578,7 @@ test.each([
shellPolicy,
);
expect(settings.config["agents"]).toEqual(resolvedAgents);
expect(settings.config["model_provider"]).toBe("openrouter");
expect(settings.config["model_provider"]).toBe(providerId);
expect(settings.nativeProfile).toBeDefined();
expect(settings.nativeProfile).toBe(options.nativeProfile);
expect(
@@ -594,7 +596,7 @@ test.each([
);
const actual = (
nativeConfig["model_providers"] as JsonObject
)["openrouter"] as JsonObject;
)[providerId] as JsonObject;
expect(actual).toMatchObject(provider);
expect(actual["http_headers"] ?? {}).toEqual(
provider.http_headers ?? {},
@@ -627,7 +629,7 @@ test.each([
await client.preflight(repository, { mode: "deep" }),
).toMatchObject({
model: "gpt-5.6-terra",
modelProvider: "openrouter",
modelProvider: providerId,
});
}
}
@@ -661,6 +663,12 @@ test.each([
);
const fileProviderKeyCases = [
["gateway", "custom only", "SYNTHETIC_GATEWAY_TOKEN"],
["gateway", "account-named primary", "OPENAI_API_KEY"],
["gateway", "declared external header", "SYNTHETIC_GATEWAY_TOKEN"],
["gateway", "declared Codex account header", "SYNTHETIC_GATEWAY_TOKEN"],
["gateway", "declared OpenAI account header", "SYNTHETIC_GATEWAY_TOKEN"],
["gateway", "missing custom primary", "SYNTHETIC_GATEWAY_TOKEN"],
["openrouter", "default", "OPENROUTER_API_KEY"],
["openrouter", "custom only", "SYNTHETIC_CUSTOM_API_KEY"],
["openrouter", "canonical header", "SYNTHETIC_CUSTOM_API_KEY"],
@@ -673,6 +681,12 @@ const fileProviderKeyCases = [
["openrouter", "other external key", "FIREWORKS_API_KEY"],
] as const;
const gatewayHeaders = new Map<string, string>([
["declared external header", "FIREWORKS_API_KEY"],
["declared Codex account header", "CODEX_API_KEY"],
["declared OpenAI account header", "OPENAI_API_KEY"],
]);
test.each(["openrouter", "fireworks"] as const)(
"native file profile accepts the %s custom environment key",
async (providerId) => {
@@ -719,14 +733,24 @@ for (const mode of ["standard", "deep"] as const) {
await mkdir(sourceHome, { mode: 0o700 });
const plugin = await createPluginProbe(root, report);
const canonicalKey = `${providerId.toUpperCase()}_API_KEY`;
const gatewayHeader = gatewayHeaders.get(_selection);
const headerKey =
gatewayHeader ??
(_selection === "canonical header" ? canonicalKey : undefined);
const headerEnvironment =
_selection === "canonical header" ||
_selection === "missing custom primary"
? { [canonicalKey]: " synthetic-header-key " }
headerKey || _selection === "missing custom primary"
? { [headerKey ?? canonicalKey]: " synthetic-header-key " }
: {};
const inheritedEnvironment = {
const inactiveKey = gatewayHeader
? "CHEAPER_INFERENCE_API_KEY"
: "INACTIVE_GATEWAY_TOKEN";
const inactiveEnvironment = gatewayHeader
? { [inactiveKey]: "synthetic-inactive-key" }
: {};
const inheritedEnvironment: Record<string, string> = {
...(_selection === "custom Codex key" ||
_selection === "other external key"
_selection === "other external key" ||
gatewayHeader
? Object.fromEntries(
[
"OPENAI_API_KEY",
@@ -739,12 +763,17 @@ for (const mode of ["standard", "deep"] as const) {
)
: {}),
...headerEnvironment,
...inactiveEnvironment,
...(_selection === "missing custom primary"
? {}
? {
OPENAI_API_KEY: "synthetic-unrelated-account",
INACTIVE_GATEWAY_TOKEN: "synthetic-unrelated-provider",
}
: { [providerKey]: "synthetic-file-key" }),
};
const workerEnvironment = {
...headerEnvironment,
...inactiveEnvironment,
[providerKey]: "synthetic-file-key",
};
const provider = {
@@ -752,14 +781,20 @@ for (const mode of ["standard", "deep"] as const) {
wire_api: "responses",
base_url: "https://provider.example.test/v1",
env_key: providerKey,
...(_selection === "canonical header"
? { env_http_headers: { "X-Synthetic-Token": canonicalKey } }
...(gatewayHeader === "OPENAI_API_KEY"
? { requires_openai_auth: true }
: {}),
...(headerKey
? { env_http_headers: { "X-Synthetic-Token": headerKey } }
: {}),
};
const original = stringifyToml({
model: "synthetic-model",
model_provider: providerId,
model_providers: { [providerId]: provider },
model_providers: {
[providerId]: provider,
inactive: { ...provider, env_key: inactiveKey },
},
features: { shell_tool: false, unified_exec: false },
});
await writeFile(join(sourceHome, "review.config.toml"), original);
@@ -775,6 +810,16 @@ for (const mode of ["standard", "deep"] as const) {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scan,
repositoryRevision: async () => "deadbeef",
runWorkbench: async (options, args, input) => {
if (args[0] === "register-cli-scan") {
expect(options.environment).not.toHaveProperty(providerKey);
if (gatewayHeader) {
expect(options.environment).not.toHaveProperty(gatewayHeader);
expect(options.environment).not.toHaveProperty(inactiveKey);
}
}
return mockWorkbench(args, input);
},
createCodex: (options) => {
launched = true;
return {
@@ -789,9 +834,13 @@ for (const mode of ["standard", "deep"] as const) {
"CODEX_API_KEY",
"OPENROUTER_API_KEY",
"FIREWORKS_API_KEY",
"CHEAPER_INFERENCE_API_KEY",
]) {
expect(environment[name]).toBe(
name === providerKey || name === canonicalKey
name === providerKey ||
name === canonicalKey ||
name === headerKey ||
name === inactiveKey
? inheritedEnvironment[name]
: undefined,
);
@@ -844,6 +893,7 @@ for (const mode of ["standard", "deep"] as const) {
]) {
expect(text).not.toContain("synthetic-file-key");
expect(text).not.toContain("synthetic-header-key");
expect(text).not.toContain("synthetic-inactive-key");
}
throw new Error("synthetic file provider child checked");
},
@@ -860,6 +910,21 @@ for (const mode of ["standard", "deep"] as const) {
verified: false,
});
expect(preflight.modelProvider).toBe(providerId);
if (
providerId === "gateway" &&
(_selection === "custom only" ||
_selection === "account-named primary")
) {
const request = { mode, auth: "chatgpt" as const };
const guidance = `ChatGPT authentication cannot use the gateway provider's required ${providerKey}`;
await expect(client.preflight(repository, request)).rejects.toThrow(
guidance,
);
await expect(client.run(repository, request)).rejects.toThrow(
guidance,
);
expect(launched).toBe(false);
}
if (_selection === "missing custom primary") {
await expect(
client.preflight(repository, { mode, auth: "api-key" }),
@@ -1196,6 +1261,7 @@ test.each([
env_key: providerKey,
env_http_headers: {
"X-Synthetic-Token": headerKey,
...(!external ? { "X-Synthetic-Primary": providerKey } : {}),
"X-Synthetic-Missing": "SYNTHETIC_UNSET_KEY",
},
},
@@ -1225,16 +1291,14 @@ test.each([
startThread: () => ({
id: null,
async runStreamed() {
expect(options.apiKey).toBe(
external ? undefined : "synthetic-account-key",
);
expect(options.apiKey).toBeUndefined();
expect(options.env!["OPENAI_API_KEY"]).toBeUndefined();
const selectedKey = external
? "synthetic-custom-key"
: providerEnvironment[providerKey];
expect(options.env![providerKey]).toBe(selectedKey);
const status = await nativeRequest(
{
...options.env!,
...(options.apiKey === undefined
? {}
: { CODEX_API_KEY: options.apiKey }),
},
options.env!,
repository,
[],
// Tool enumeration starts the real MCP child without a model turn.
@@ -1259,12 +1323,7 @@ test.each([
...(process.platform === "win32"
? { [headerKey]: " synthetic-child-header " }
: {}),
...(external
? { [providerKey]: "synthetic-custom-key" }
: {}),
...(providerKey === "CODEX_API_KEY"
? { CODEX_API_KEY: "synthetic-account-key" }
: {}),
[providerKey]: selectedKey,
},
});
for (const text of [
+62 -16
View File
@@ -13708,10 +13708,33 @@ if __name__ == "__main__":
undefined,
],
["managed provider selection retains matching", "managed", undefined],
[
"post-scan inference needs a declared Codex header",
"CODEX_API_KEY",
undefined,
],
[
"post-scan inference needs a declared OpenAI header",
"OPENAI_API_KEY",
undefined,
],
["relative model files preserve scan origin", "model-files", undefined],
] as const)(
"keeps a completed scan when %s",
async (_scenario, failure, warning) => {
async (_scenario, variant, warning) => {
const nativeHeader =
variant === "OPENAI_API_KEY" || variant === "CODEX_API_KEY"
? variant
: undefined;
const failure = nativeHeader ? "managed" : variant;
const gatewayEnvironment: Record<string, string> = nativeHeader
? {
GATEWAY_TOKEN: "synthetic-gateway-primary",
CODEX_API_KEY: "synthetic-unrelated",
OPENAI_API_KEY: "synthetic-unrelated",
[nativeHeader]: " synthetic-required-header ",
}
: {};
const limited = failure === "budget" || failure === "budget-context";
const { root, repository, codexHome, scanDir } = await scanDirectories();
const current = {
@@ -13771,8 +13794,11 @@ if __name__ == "__main__":
wire_api: "responses",
env_http_headers: {
"X-Synthetic-Context": "SYNTHETIC_MATCH_HEADER",
...(nativeHeader ? { "X-Gateway-Header": nativeHeader } : {}),
},
auth: { command: "synthetic-auth" },
...(nativeHeader
? { env_key: "GATEWAY_TOKEN" }
: { auth: { command: "synthetic-auth" } }),
},
...(failure === "managed"
? { "synthetic.managed": managedProvider }
@@ -13797,6 +13823,13 @@ if __name__ == "__main__":
}
const kind = args.includes("mcp") ? "mcp" : args.includes("app-server") ? "preflight" : "exec";
const call = { kind, args };
if (${Boolean(nativeHeader)}) {
call.credentials = {
GATEWAY_TOKEN: process.env.GATEWAY_TOKEN,
OPENAI_API_KEY: process.env.OPENAI_API_KEY,
CODEX_API_KEY: process.env.CODEX_API_KEY,
};
}
if (kind !== "exec") {
call.metadata = config.model_providers;
appendFileSync(${JSON.stringify(startupCallsPath)}, JSON.stringify(call) + "\\n");
@@ -13825,7 +13858,7 @@ if __name__ == "__main__":
const request = JSON.parse(line);
if (request.id === undefined) continue;
const result = request.method === "config/read"
? { config: { ...config, model_provider: "synthetic.managed" } }
? { config: { ...config, model_provider: ${JSON.stringify(nativeHeader ? "synthetic.provider" : "synthetic.managed")} } }
: request.method === "permissionProfile/list"
? { data: [{ id: config.default_permissions, allowed: true }], nextCursor: null }
: {};
@@ -13876,9 +13909,11 @@ if __name__ == "__main__":
},
{
...scanRuntimeDependencies(codexHome, scanDir),
environment: gatewayEnvironment,
prepareRuntime: runtimePreparer(codexHome, () => ({
environment: {
SYNTHETIC_MATCH_HEADER: "synthetic-comparison-header",
...gatewayEnvironment,
...(failure === "managed"
? {
PATH: process.env["PATH"] ?? "",
@@ -14086,7 +14121,7 @@ if __name__ == "__main__":
);
const ownerSpy =
failure === "managed"
failure === "managed" && !nativeHeader
? spyOn(
ownerArtifacts,
"writeScanOwnerSuggestions",
@@ -14117,7 +14152,7 @@ if __name__ == "__main__":
: undefined;
try {
const result = await client.run(repository, {
ownerSuggestions: failure === "managed",
ownerSuggestions: ownerSpy !== undefined,
...(limited ? { maxCostUsd: 1 } : {}),
cyberAccessProgram: "daybreak_blue",
onProgress() {},
@@ -14176,18 +14211,16 @@ if __name__ == "__main__":
.trim()
.split("\n")
.map((line) => JSON.parse(line));
expect(ownerSpy).toHaveBeenCalledTimes(1);
expect(result.ownerSuggestionsPath).toBe(
join(scanDir, "owner-suggestions.json"),
if (ownerSpy) {
expect(ownerSpy).toHaveBeenCalledTimes(1);
expect(result.ownerSuggestionsPath).toBe(
join(scanDir, "owner-suggestions.json"),
);
}
const startup = ["mcp", "preflight", "exec"];
expect(calls.map(({ kind }) => kind)).toEqual(
ownerSpy ? [...startup, ...startup] : startup,
);
expect(calls.map(({ kind }) => kind)).toEqual([
"mcp",
"preflight",
"exec",
"mcp",
"preflight",
"exec",
]);
const metadata = {
"synthetic.provider": {
name: "Synthetic provider",
@@ -14199,6 +14232,19 @@ if __name__ == "__main__":
requires_openai_auth: false,
},
};
if (nativeHeader) {
for (const call of calls) {
if (call.kind === "exec") {
expect(call.credentials).toEqual({
GATEWAY_TOKEN: "synthetic-gateway-primary",
[nativeHeader]: " synthetic-required-header ",
});
} else {
expect(call.credentials).not.toHaveProperty("OPENAI_API_KEY");
expect(call.credentials).not.toHaveProperty("CODEX_API_KEY");
}
}
}
expect(calls[0].metadata).toEqual(metadata);
expect(calls[1].metadata).toEqual(metadata);
expect(calls[2]).toMatchObject({
@@ -1,5 +1,6 @@
import { readJsonLines } from "./support/json.js";
import { runProviderSkill } from "./support/cli-provider-authentication.js";
import { TestClient } from "./support/api-client.js";
import { resolving } from "./support/promises.js";
import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
@@ -1152,6 +1153,45 @@ describe("CLI authentication", () => {
}
});
test("scan rejects an explicit ChatGPT login with a required native provider key", async () => {
const home = await createCredentialHome();
await writeFile(join(home, "review.config.toml"), GATEWAY_CONFIGURATION);
const environment = {
CODEX_HOME: home,
GATEWAY_API_KEY: "synthetic-provider-secret",
OPENAI_API_KEY: "synthetic-unrelated-secret",
};
const { runCli, stdout, stderr } = createCliTest(main);
const deps = dependencies({
environment,
currentDirectory: stateDirectory,
});
deps.createSecurity = (config) => new TestClient(config, { environment });
expect(
await runCli(
[
"scan",
".",
"--dry-run",
"--auth",
"chatgpt",
"--codex",
'profile="review"',
],
deps,
),
).toBe(2);
expect(stderr.text()).toContain(
"ChatGPT authentication cannot use the gateway provider's required GATEWAY_API_KEY",
);
expect(stdout.text() + stderr.text()).not.toContain(
"synthetic-provider-secret",
);
expect(stdout.text() + stderr.text()).not.toContain(
"synthetic-unrelated-secret",
);
});
test("keeps selected dry-run authentication metadata safe and machine readable", async () => {
const { stdout, stderr, runCli } = createCliTest(main);
+75 -35
View File
@@ -251,13 +251,28 @@ describe("semantic scan comparison", () => {
);
test.each([false, true])(
"preserves literal metadata keys in SDK arguments with provider profile %p",
"preserves literal metadata and provider header values in SDK children with a private profile %p",
async (withProfile) => {
const home = await temporaryDirectory();
const repository = await temporaryDirectory();
await writeFile(join(repository, "source.ts"), "export {};\n");
const gateway = (env_key = "SYNTHETIC_GATEWAY_TOKEN") => ({
model_provider: "gateway",
model_providers: {
gateway: {
name: "Synthetic",
wire_api: "responses",
base_url: "https://provider.example.test/v1",
env_key,
env_http_headers: { "X-Gateway-Key": "CODEX_API_KEY" },
},
},
});
const preload = join(home, "capture-codex.mjs");
await writeFile(
join(home, "config.toml"),
stringify({
...(withProfile ? {} : gateway()),
responses_api_metadata: {
"team.tag": "from-home",
"overlap.tag": "home",
@@ -270,51 +285,65 @@ describe("semantic scan comparison", () => {
"for await (const _chunk of process.stdin) {}",
"const send = (event) => console.log(JSON.stringify(event));",
'send({ type: "thread.started", thread_id: "fixture-thread" });',
'send({ type: "item.completed", item: { id: "reply", type: "agent_message", text: JSON.stringify(process.argv.slice(2)) } });',
"const { SYNTHETIC_GATEWAY_TOKEN: primary, CODEX_API_KEY: header, OPENAI_API_KEY: account } = process.env;",
"const text = JSON.stringify({ args: process.argv.slice(2), credentials: { primary, header, account } });",
'send({ type: "item.completed", item: { id: "reply", type: "agent_message", text } });',
'send({ type: "turn.completed", usage: { input_tokens: 0, cached_input_tokens: 0, output_tokens: 0 } });',
"process.exit(0);",
].join("\n"),
);
let captured: CodexOptions | undefined;
const profileClient = captureProfileClient();
const { codex } = fakeCodex({ matches: [], uncertain: [] });
const { codex } = fakeCodex(
withProfile
? { components: [{ name: "Source", paths: ["source.ts"] }] }
: { matches: [], uncertain: [] },
);
const startThread = observeCodexOptions(codex, (options) => {
captured = options;
});
try {
await matchScanFindings(
{ before: [finding("before")], after: [finding("after")] },
{
environment: {
PATH: process.env["PATH"],
SystemRoot: process.env["SystemRoot"],
CODEX_HOME: home,
CODEX_SECURITY_STATE_DIR: join(home, "state"),
OPENAI_API_KEY: "synthetic-key",
},
workingDirectory: home,
config: {
codexOverrides: {
responses_api_metadata: {
"caller.tag": "from-caller",
"overlap.tag": "caller",
},
...(withProfile
? {
model_provider: "synthetic",
model_providers: {
synthetic: {
name: "Synthetic",
wire_api: "responses",
base_url: "https://provider.example.test/v1",
},
},
}
: {}),
const options = {
environment: {
PATH: process.env["PATH"],
SystemRoot: process.env["SystemRoot"],
CODEX_HOME: home,
CODEX_SECURITY_STATE_DIR: join(home, "state"),
OPENAI_API_KEY: "synthetic-unrelated-account",
CODEX_API_KEY: " synthetic-header ",
SYNTHETIC_GATEWAY_TOKEN: "synthetic-primary",
},
workingDirectory: home,
config: {
codexOverrides: {
responses_api_metadata: {
"caller.tag": "from-caller",
"overlap.tag": "caller",
},
...(withProfile ? gateway() : {}),
},
},
);
};
if (withProfile) {
await planComponents(repository, options);
await expect(
planComponents(repository, { ...options, auth: "chatgpt" }),
).rejects.toThrow(
"ChatGPT authentication cannot use the gateway provider's required SYNTHETIC_GATEWAY_TOKEN",
);
await expect(
planComponents(repository, {
...options,
config: { codexOverrides: gateway("CODEX_API_KEY") },
environment: { ...options.environment, CODEX_API_KEY: undefined },
}),
).rejects.toThrow("Set CODEX_API_KEY");
expect(startThread).toHaveBeenCalledTimes(1);
} else
await matchScanFindings(
{ before: [finding("before")], after: [finding("after")] },
options,
);
} finally {
startThread.mockRestore();
profileClient.spy.mockRestore();
@@ -332,7 +361,18 @@ describe("semantic scan comparison", () => {
const turn = await capture
.startThread({ workingDirectory: home, skipGitRepoCheck: true })
.run("Capture the invocation.");
const args: string[] = JSON.parse(turn.finalResponse);
const {
args,
credentials,
}: {
args: string[];
credentials: Record<string, string>;
} = JSON.parse(turn.finalResponse);
expect(credentials).toEqual({
primary: "synthetic-primary",
header: " synthetic-header ",
});
expect(captured!.apiKey).toBeUndefined();
const metadataOverrides = args
.flatMap((arg, index) => (arg === "--config" ? [args[index + 1]!] : []))
.filter((value) => value.startsWith("responses_api_metadata"));
@@ -343,7 +383,7 @@ describe("semantic scan comparison", () => {
"caller.tag": "from-caller",
"overlap.tag": "caller",
codex_security_surface: "sdk",
codex_security_command: "compare",
codex_security_command: withProfile ? "scan-components" : "compare",
codex_security_package_version: VERSION,
...(withProfile ? { codex_security_provider: "custom" } : {}),
},