refactor(scan): reuse catalog configuration and saved program selection

This commit is contained in:
Michael D'Angelo
2026-11-10 18:55:17 +00:00
parent f8c5d090ea
commit 2a11242a45
12 changed files with 575 additions and 918 deletions
+57 -66
View File
@@ -944,11 +944,7 @@ export class CodexSecurity {
metadata ??= {
threadId: (scan["continuationThreadId"] as string) ?? "",
turnResult: { status: "completed" },
requestedCyberAccessProgram: isRecord(recipe)
? ScanSettingsSchema.shape.cyberAccessProgram.parse(
recipe["requestedCyberAccessProgram"],
)
: undefined,
requestedCyberAccessProgram: savedCyberAccessProgram(recipe),
};
else local.retryRecipe = isRecord(recipe) ? recipe : {};
}
@@ -2469,51 +2465,16 @@ export class CodexSecurity {
const sqliteHome = workerRuntimeConfig["sqlite_home"];
const sqliteEnvironment: Record<string, string> =
typeof sqliteHome === "string" ? { CODEX_SQLITE_HOME: sqliteHome } : {};
const { model } = scanModelConfiguration(effectiveConfig);
const requestMetadata = codexSecurityRequestContext(effectiveConfig, {
...this.#operationTelemetry?.context,
surface: this.#surface,
command: "scan",
pluginVersion: runtime.plugin.version,
mode,
}).metadata;
if (
options.resumeScanId === undefined &&
cyberAccessProgram === undefined &&
this.#dependencies.hostedScan === undefined &&
this.#dependencies.resolveScanCyberAccessProgram !== undefined &&
(modelProvider === undefined || modelProvider === "openai")
) {
// An empty sibling inherits the replacement output's project layers.
const archiveWorkspace =
options.archiveExisting && (await readdir(scanDir)).length > 0
? await prepareOutputDir(undefined, "catalog", dirname(scanDir))
: undefined;
try {
cyberAccessProgram =
await this.#dependencies.resolveScanCyberAccessProgram({
command: this.#codexCommand(),
cwd: archiveWorkspace ?? scanDir,
nativeProfile: runtime.providerProfile !== undefined,
environment: definedEnvironment({
...environmentWithGit(workerProviderEnvironment, git),
CODEX_HOME: runtimeHome,
}),
config: {
...workerRuntimeConfig,
responses_api_metadata: requestMetadata,
},
model,
signal,
});
} finally {
if (archiveWorkspace !== undefined)
await cleanupSdkDirectory(archiveWorkspace);
}
}
workerRuntimeConfig["responses_api_metadata"] =
codexSecurityRequestContext(effectiveConfig, {
...this.#operationTelemetry?.context,
surface: this.#surface,
command: "scan",
pluginVersion: runtime.plugin.version,
mode,
}).metadata;
const workerSnapshot: JsonObject = {
...workerRuntimeConfig,
responses_api_metadata: requestMetadata,
...(workerEnvironment === undefined
? {}
: { environment: workerEnvironment }),
@@ -2629,6 +2590,7 @@ export class CodexSecurity {
mode,
pluginVersion: runtime.plugin.version,
};
const { model } = scanModelConfiguration(effectiveConfig);
validateScanCostLimit(options.maxCostUsd, model, pricingContext);
if (mode === "deep" && options.maxCostUsd !== undefined) {
budgetRecovery = {
@@ -2848,10 +2810,6 @@ export class CodexSecurity {
knowledgeBasePaths: knowledgeBase?.sources,
deepScan: deepScanConfiguration?.settings,
});
if (cyberAccessProgram !== undefined) {
// A continuation uses the original program. A new rerun resolves the original intent.
recipe["requestedCyberAccessProgram"] = cyberAccessProgram;
}
if (savedProviderProfile !== undefined) {
recipe["providerProfile"] = {
name: savedProviderProfile.name,
@@ -2892,23 +2850,52 @@ export class CodexSecurity {
options.resumeScanId,
])
: undefined;
const resumeRecipe = resumeRegistration?.["recipe"];
if (cyberAccessProgram === undefined && isRecord(resumeRecipe)) {
cyberAccessProgram = ScanSettingsSchema.shape.cyberAccessProgram.parse(
resumeRecipe["cyberAccessProgram"] ??
resumeRecipe["requestedCyberAccessProgram"],
if (resumeRegistration !== undefined) {
cyberAccessProgram ??= savedCyberAccessProgram(
resumeRegistration["recipe"],
);
} else if (
cyberAccessProgram === undefined &&
this.#dependencies.resolveScanCyberAccessProgram !== undefined &&
(modelProvider === undefined || modelProvider === "openai")
) {
// An empty sibling inherits the replacement output's project layers.
const archiveWorkspace =
options.archiveExisting && (await readdir(scanDir)).length > 0
? await prepareOutputDir(undefined, "catalog", dirname(scanDir))
: undefined;
try {
cyberAccessProgram =
await this.#dependencies.resolveScanCyberAccessProgram({
command: this.#codexCommand(),
cwd: archiveWorkspace ?? scanDir,
nativeProfile: runtime.providerProfile !== undefined,
environment: definedEnvironment({
...environmentWithGit(workerProviderEnvironment, git),
CODEX_HOME: runtimeHome,
}),
config: workerRuntimeConfig,
model,
signal,
});
} finally {
if (archiveWorkspace !== undefined)
await cleanupSdkDirectory(archiveWorkspace);
}
}
if (
runtime.configPath !== undefined &&
cyberAccessProgram !== undefined &&
cyberAccessProgram !== options.cyberAccessProgram
) {
await writeCodexConfig(runtime.configPath, {
...preflightConfig,
codex_security: { cyber_access_program: cyberAccessProgram },
});
// A continuation restores the selection. A new rerun uses the caller's original choice.
recipe["requestedCyberAccessProgram"] = cyberAccessProgram;
if (runtime.configPath !== undefined)
await writeCodexConfig(runtime.configPath, {
...preflightConfig,
codex_security: { cyber_access_program: cyberAccessProgram },
});
}
checkOpen();
const registration =
resumeRegistration !== undefined
? resumeRegistration
@@ -3993,10 +3980,7 @@ export class CodexSecurity {
)(`Could not run post-scan instructions: ${errorMessage(error)}`);
}
}
const inferenceRuntimeConfig: JsonObject = {
...structuredClone(workerRuntimeConfig),
responses_api_metadata: workerSnapshot["responses_api_metadata"]!,
};
const inferenceRuntimeConfig = structuredClone(workerRuntimeConfig);
const inferenceFeatures = inferenceRuntimeConfig["features"];
if (isRecord(inferenceFeatures)) delete inferenceFeatures["plugins"];
const inferenceOptions = {
@@ -6456,6 +6440,13 @@ async function targetInstruction(
return `Scan target: staged and unstaged working-tree changes against ${target.base}.`;
}
function savedCyberAccessProgram(recipe: unknown) {
if (isRecord(recipe))
return ScanSettingsSchema.shape.cyberAccessProgram.parse(
recipe["cyberAccessProgram"] ?? recipe["requestedCyberAccessProgram"],
);
}
function scanRecipe({
repository,
target,
+43 -46
View File
@@ -1,5 +1,5 @@
import type { JsonObject } from "./config.js";
import { isRecord } from "./record.js";
import { asRecord, isRecord } from "./record.js";
type CyberAccessProgram = "standard" | "daybreakBlue" | "daybreakRed";
@@ -8,37 +8,45 @@ export type AppServerRequest = (
params: JsonObject,
) => Promise<JsonObject>;
async function* listPages(
request: AppServerRequest,
method: string,
params: JsonObject,
) {
let cursor: string | undefined;
do {
const { data, nextCursor } = await request(
method,
cursor === undefined ? params : { ...params, cursor },
);
if (Array.isArray(data))
yield data.filter((row): row is JsonObject => isRecord(row));
cursor = typeof nextCursor === "string" ? nextCursor : undefined;
} while (cursor !== undefined);
}
export async function daybreakFeatures(
request: AppServerRequest,
threadId?: string,
) {
const features = new Map<string, unknown>();
let featureCursor: string | undefined;
do {
const result = await request("experimentalFeature/list", {
...(threadId === undefined ? {} : { threadId }),
...(featureCursor === undefined ? {} : { cursor: featureCursor }),
});
const flags = result["data"];
if (Array.isArray(flags)) {
for (const flag of flags) {
if (isRecord(flag) && typeof flag["name"] === "string")
features.set(flag["name"], flag["enabled"]);
}
const pages = listPages(
request,
"experimentalFeature/list",
threadId === undefined ? {} : { threadId },
);
for await (const flags of pages) {
for (const { name, enabled } of flags) {
if (typeof name === "string") features.set(name, enabled);
}
if (threadId !== undefined && features.get("cli_daybreak") === false) break;
if (
features.has("cli_daybreak") &&
features.has("api_key_cyber_access_programs") &&
(threadId !== undefined || features.has("api_key_model_discovery"))
) {
)
break;
}
featureCursor =
typeof result["nextCursor"] === "string"
? result["nextCursor"]
: undefined;
} while (featureCursor !== undefined);
}
return features;
}
@@ -46,29 +54,22 @@ export async function modelCyberAccessPrograms(
model: string,
request: AppServerRequest,
) {
let cursor: string | undefined;
do {
const result = await request("model/list", {
includeHidden: true,
...(cursor === undefined ? {} : { cursor }),
});
const models = result["data"];
const selected = Array.isArray(models)
? models.find((entry) => isRecord(entry) && entry["model"] === model)
: undefined;
if (isRecord(selected)) {
const access = selected["availableAccessPrograms"];
const programs = isRecord(access) ? access["cyber"] : undefined;
return Array.isArray(programs) ? programs : undefined;
}
cursor =
typeof result["nextCursor"] === "string"
? result["nextCursor"]
: undefined;
} while (cursor !== undefined);
for await (const models of listPages(request, "model/list", {
includeHidden: true,
})) {
const selected = models.find((entry) => entry["model"] === model);
if (selected === undefined) continue;
const programs = asRecord(selected["availableAccessPrograms"])?.["cyber"];
return Array.isArray(programs) ? programs : undefined;
}
return undefined;
}
export async function daybreakAccountType(request: AppServerRequest) {
const { account } = await request("account/read", { refreshToken: false });
return asRecord(account)?.["type"];
}
// App-server clients resolve Daybreak from the catalog before starting a turn,
// just as native Codex exec does; the config key alone does not select a program.
export async function appServerCyberAccessProgram(
@@ -89,12 +90,8 @@ export async function appServerCyberAccessProgram(
return undefined;
}
const accountType = async (): Promise<unknown> => {
const result = await request("account/read", { refreshToken: false });
return isRecord(result["account"]) ? result["account"]["type"] : undefined;
};
if (enabled) {
const account = await accountType();
const account = await daybreakAccountType(request);
if (account !== "chatgpt" && account !== "apiKey") {
throw new Error(
"Daybreak requires a signed-in ChatGPT account or an OpenAI API key",
@@ -115,7 +112,7 @@ export async function appServerCyberAccessProgram(
);
}
if (!programs.includes("standard")) return undefined;
const account = await accountType().catch(() => undefined);
const account = await daybreakAccountType(request).catch(() => undefined);
return account === "chatgpt" ||
(account === "apiKey" &&
features.get("api_key_cyber_access_programs") === true)
+5 -6
View File
@@ -10470,7 +10470,6 @@ async function executeScan(
let patchOtel: JsonObject | undefined;
let patchDaybreak: JsonValue = false;
let patchDaybreakFeatures: JsonObject = {};
let followUpCyberAccessProgram = arguments_.cyberAccessProgram;
let selectedAuthentication: ScanAuthentication | null = null;
let repository = "";
let runningMockScan = false;
@@ -11128,9 +11127,6 @@ async function executeScan(
runningMockScan = arguments_.mock === true;
result = await security.run(repository, options);
runningMockScan = false;
followUpCyberAccessProgram ??=
result.requestedCyberAccessProgram ??
registeredScan?.cyberAccessProgram;
scanDir = result.scanDir;
repository = resolve(dependencies.currentDirectory(), repository);
if (arguments_.validate) {
@@ -11204,7 +11200,9 @@ async function executeScan(
knowledgeBaseSnapshot: options.knowledgeBaseSnapshot,
finding,
auth,
cyberAccessProgram: followUpCyberAccessProgram,
cyberAccessProgram:
arguments_.cyberAccessProgram ??
result.requestedCyberAccessProgram,
safetyIdentifier: arguments_.safetyIdentifier,
signal: preparationAbortController.signal,
});
@@ -11569,7 +11567,8 @@ async function executeScan(
requestMetadata: patchRequestMetadata,
otel: patchOtel,
daybreakFeatures: patchDaybreakFeatures,
cyberAccessProgram: followUpCyberAccessProgram,
cyberAccessProgram:
arguments_.cyberAccessProgram ?? result.requestedCyberAccessProgram,
safetyIdentifier: arguments_.safetyIdentifier,
auth,
findingInstructions: patchSelection?.instructions,
+5 -2
View File
@@ -766,7 +766,11 @@ async function startReadOnlyCodexThread(
};
}
let cyberAccessProgram = options.cyberAccessProgram;
if (componentRepository !== undefined && model !== undefined) {
if (
cyberAccessProgram === undefined &&
componentRepository !== undefined &&
model !== undefined
) {
// The helper may use a different credential home than the caller.
// Only send configuration that this Codex process actually receives.
const nativeEnvironment = codexOptions.env ?? environment;
@@ -782,7 +786,6 @@ async function startReadOnlyCodexThread(
...(isRecord(providers) ? { model_providers: providers } : {}),
},
model,
program: cyberAccessProgram,
nativeProfile: profile !== undefined,
signal: options.signal ?? new AbortController().signal,
});
+174 -229
View File
@@ -8,6 +8,7 @@ import {
withoutOpenAiApiKeys,
} from "./auth.js";
import {
daybreakAccountType,
daybreakFeatures,
modelCyberAccessPrograms,
type AppServerRequest,
@@ -28,12 +29,13 @@ import {
nativeProfileClient,
providerPreflightCommand,
} from "./provider-profile.js";
import { isRecord } from "./record.js";
import { asRecord, isRecord } from "./record.js";
import {
expandHome,
prepareOutputDir,
runCodexCommand,
type CodexCommand,
type ProcessEnvironment,
} from "./runtime.js";
interface ScanCyberAccessOptions {
@@ -43,116 +45,117 @@ interface ScanCyberAccessOptions {
config: JsonObject;
model: string;
nativeProfile?: boolean;
program?: CyberAccessProgram;
signal: AbortSignal;
}
const networkFeatures = [
"respect_system_proxy",
"system_proxy_fallback",
"psp",
];
const catalogFeatures = [
"cli_daybreak",
"api_key_model_discovery",
"api_key_cyber_access_programs",
"psp",
"respect_system_proxy",
"system_proxy_fallback",
"secret_auth_storage",
...networkFeatures,
];
const catalogSettings = new Set([
const endpoints = ["chatgpt_base_url", "openai_base_url"];
const catalogSettings = [
...CODEX_AUTH_CONFIG_KEYS,
...endpoints,
"auth_keyring_backend",
"model",
"daybreak",
"model_catalog_json",
"project_root_markers",
"chatgpt_base_url",
"openai_base_url",
]);
"features",
...catalogFeatures.map((key) => `features.${key}`),
];
// Preserve the SDK's ordering of a nested table relative to literal dotted keys.
function pickSettings(source: JsonObject, keys: string[]): JsonObject {
return Object.fromEntries(
Object.entries(source).filter(
([key, value]) => value != null && keys.includes(key),
),
);
}
// Keep the original order of literal dotted flags and tables. A native profile
// replaces the entire feature table, whereas the SDK emits individual leaves.
function catalogConfig(source: JsonObject, nativeProfile = false): JsonObject {
const result: JsonObject = {};
for (const [key, value] of Object.entries(source)) {
if (value == null) continue;
if (key === "features" && isRecord(value)) {
const entries = Object.entries(value);
const selected = entries.filter(
([feature, enabled]) =>
enabled != null && catalogFeatures.includes(feature),
);
// A native profile sends the entire table as one CLI override.
if (nativeProfile || selected.length || !entries.length)
result[key] = Object.fromEntries(selected) as JsonObject;
} else if (
catalogSettings.has(key) ||
(key.startsWith("features.") &&
catalogFeatures.includes(key.slice("features.".length)))
) {
result[key] = value;
}
const config = pickSettings(source, catalogSettings);
const features = config["features"];
if (isRecord(features)) {
const selected = pickSettings(features, catalogFeatures);
if (
nativeProfile ||
Object.keys(selected).length ||
!Object.keys(features).length
)
config["features"] = selected;
else delete config["features"];
}
return result;
return config;
}
function openAiProvider(providers: unknown) {
return isRecord(providers) && isRecord(providers["openai"])
? providers["openai"]
: undefined;
return asRecord(asRecord(providers)?.["openai"]);
}
function privateCatalogUrl(config: JsonObject, nativeProfile = false) {
// The full provider table belongs to the private profile. Literal dotted
// keys are CLI overrides and retain their order above that profile.
let url = openAiProvider(config["model_providers"])?.["model_catalog_url"];
let pinned = false;
for (const [key, value] of Object.entries(config)) {
if (
key === "model_providers.openai.model_catalog_url" &&
typeof value === "string"
) {
url = value;
pinned = true;
} else if (key === "model_providers.openai" && isRecord(value)) {
const next = value["model_catalog_url"];
// Stock SDK nonempty objects set each leaf independently. A native
// profile or explicit empty table replaces the entire provider.
if (
typeof next === "string" ||
nativeProfile ||
!Object.keys(value).length
) {
url = next;
pinned = true;
}
}
}
return { url: typeof url === "string" ? url : undefined, pinned };
// File settings are below the SDK's literal dotted flags. TOML normalization
// places scalars before tables; a whole-table flag can also clear an inherited URL.
function catalogRoute(
config: JsonObject,
nativeProfile = false,
): { url?: string } | undefined {
const table = asRecord(config["model_providers.openai"]);
const override = table?.["model_catalog_url"];
if (typeof override === "string") return { url: override };
if (table && (nativeProfile || !Object.keys(table).length)) return {};
const leaf = config["model_providers.openai.model_catalog_url"];
const url =
typeof leaf === "string"
? leaf
: openAiProvider(config["model_providers"])?.["model_catalog_url"];
return typeof url === "string" ? { url } : undefined;
}
function hasManagedCatalogSettings(layer: unknown): boolean {
if (!isRecord(layer) || !isRecord(layer["name"])) return false;
const source = layer["name"]["type"];
const managedLayers = new Set([
"enterpriseManaged",
"legacyManagedConfigTomlFromMdm",
"legacyManagedConfigTomlFromFile",
]);
/** These workspace routing controls cannot be reproduced by a separate API-key identity. */
function hasManagedRoute(policy: JsonObject, layers: unknown[]) {
const required = asRecord(policy["featureRequirements"]);
const network = asRecord(asRecord(policy["application"])?.["network"]);
if (
source !== "enterpriseManaged" &&
source !== "legacyManagedConfigTomlFromMdm" &&
source !== "legacyManagedConfigTomlFromFile"
policy["chatgptBaseUrl"] != null ||
policy["enforceResidency"] != null ||
network?.["enabled"] === true ||
networkFeatures.some((name) => required?.[name] != null)
)
return false;
const config = layer["config"];
if (!isRecord(config)) return false;
const features = config["features"];
return (
[
"chatgpt_base_url",
"openai_base_url",
"model_catalog_json",
"cli_auth_credentials_store",
"application",
"network",
].some((key) => config[key] != null) ||
(isRecord(features) &&
(features["respect_system_proxy"] != null ||
features["system_proxy_fallback"] != null ||
features["psp"] != null))
);
return true;
return layers.some((layer) => {
const entry = asRecord(layer);
if (!managedLayers.has(String(asRecord(entry?.["name"])?.["type"])))
return false;
const settings = asRecord(entry?.["config"]);
const features = asRecord(settings?.["features"]);
return (
[
"chatgpt_base_url",
"openai_base_url",
"model_catalog_json",
"cli_auth_credentials_store",
"application",
"network",
].some((key) => settings?.[key] != null) ||
networkFeatures.some((key) => features?.[key] != null)
);
});
}
function selectedProgram(model: string, programs: unknown): CyberAccessProgram {
@@ -174,41 +177,17 @@ function selectedProgram(model: string, programs: unknown): CyberAccessProgram {
/** The policy probe masks remote discovery with a bundled catalog. Recover a
* workspace's actual catalog file from the first active layer below that flag. */
function configuredCatalogFile(layers: unknown) {
if (!Array.isArray(layers)) return undefined;
for (const layer of layers) {
function configuredCatalogFile(layers: unknown[]) {
for (const value of layers) {
const layer = asRecord(value);
const path = asRecord(layer?.["config"])?.["model_catalog_json"];
if (
isRecord(layer) &&
!layer["disabledReason"] &&
isRecord(layer["name"]) &&
layer["name"]["type"] !== "sessionFlags" &&
isRecord(layer["config"]) &&
typeof layer["config"]["model_catalog_json"] === "string"
!layer?.["disabledReason"] &&
asRecord(layer?.["name"])?.["type"] !== "sessionFlags" &&
typeof path === "string"
)
return layer["config"]["model_catalog_json"];
return path;
}
return undefined;
}
async function nativeModels(
command: CodexCommand,
cwd: string,
environment: Record<string, string>,
args: string[],
signal: AbortSignal,
) {
const result = await runCodexCommand(
command,
args,
environment,
undefined,
signal,
{ cwd },
);
signal.throwIfAborted();
if (!result.success)
throw new ConfigurationError(result.stderr || result.stdout);
return result.stdout;
}
/** Discover the selected model's programs using the scan's identity before its first turn. */
@@ -219,10 +198,8 @@ export async function resolveScanCyberAccessProgram({
config,
model,
nativeProfile,
program,
signal,
}: ScanCyberAccessOptions): Promise<CyberAccessProgram | undefined> {
if (program !== undefined) return program;
if (command.args?.length || !isBundledExecutable(command.command))
return undefined;
const resolved = resolveCodexProfile(config);
@@ -258,13 +235,9 @@ export async function resolveScanCyberAccessProgram({
delete policyConfig["chatgpt_base_url"];
}
const policyOverrides = serialize(policyConfig);
const providers = isRecord(resolved["model_providers"])
? { ...resolved["model_providers"] }
: {};
delete providers["openai"]; // Its private catalog URL must stay out of argv.
const { url, pinned } = privateCatalogUrl(resolved, nativeProfile);
const route = catalogRoute(resolved, nativeProfile);
const maskCatalog =
Boolean(apiKey || url || pinned) && !projected["model_catalog_json"];
Boolean(apiKey || route) && !projected["model_catalog_json"];
const scratch = await prepareOutputDir(
undefined,
"catalog",
@@ -276,31 +249,44 @@ export async function resolveScanCyberAccessProgram({
if (name.toUpperCase() === "CODEX_SQLITE_HOME") delete env[name];
}
env["CODEX_SQLITE_HOME"] = sqliteHome;
const consent = Object.fromEntries(
Object.entries(resolved).filter(
([key, value]) =>
value != null && (key === "analytics" || key === "analytics.enabled"),
// The policy preflight receives provider names only. Its saved login must never see a project key's route.
const providers = { ...asRecord(resolved["model_providers"]) };
delete providers["openai"];
const policyCommand = await providerPreflightCommand(command, {
...pickSettings(resolved, ["model_provider", "responses_api_metadata"]),
model_providers: providers as JsonObject,
});
policyOverrides.push(
...serialize(pickSettings(resolved, ["analytics", "analytics.enabled"])),
`sqlite_home=${inlineToml(sqliteHome)}`,
);
// The project key uses a private home with no ambient login.
const isolated = Object.fromEntries(
Object.entries(env).filter(
([name]) =>
!["CODEX_ACCESS_TOKEN", "CODEX_HOME"].includes(name.toUpperCase()),
),
);
const catalogCommand = await providerPreflightCommand(
{
...command,
args: [
"-c",
`sqlite_home=${inlineToml(sqliteHome)}`,
...serialize(consent).flatMap((flag) => ["-c", flag]),
],
},
resolved["responses_api_metadata"] == null
? {}
: { responses_api_metadata: resolved["responses_api_metadata"] },
);
const policyCommand = await providerPreflightCommand(catalogCommand, {
...(resolved["model_provider"] != null && {
model_provider: resolved["model_provider"],
}),
model_providers: providers,
});
isolated["CODEX_HOME"] = scratch;
const debugModels = async (
identity: ProcessEnvironment,
bundled = false,
) => {
const args = bundled
? ["-c", "analytics.enabled=false", "debug", "models", "--bundled"]
: ["debug", "models"];
const result = await runCodexCommand(
command,
args,
identity,
undefined,
signal,
{ cwd: scratch },
);
if (!result.success)
throw new ConfigurationError(result.stderr || result.stdout);
return result.stdout;
};
const native = await nativePermissionPreflight();
const probe = <T>(
overrides: string[],
@@ -324,29 +310,26 @@ export async function resolveScanCyberAccessProgram({
if (maskCatalog) {
// Ask the saved workspace for policy without loading a catalog under the wrong identity or route.
const path = join(scratch, "bootstrap-models.json");
const bundled = await nativeModels(
command,
scratch,
{
HOME: scratch,
USERPROFILE: scratch,
CODEX_HOME: scratch,
...(environmentEntry(env, "SystemRoot") && {
SystemRoot: environmentEntry(env, "SystemRoot")!,
}),
},
["-c", "analytics.enabled=false", "debug", "models", "--bundled"],
signal,
);
await writeFile(path, bundled, { mode: 0o600 });
const bootstrapEnv = {
HOME: scratch,
USERPROFILE: scratch,
CODEX_HOME: scratch,
SystemRoot: environmentEntry(env, "SystemRoot"),
};
await writeFile(path, await debugModels(bootstrapEnv, true), {
mode: 0o600,
});
bootstrap.push(`model_catalog_json=${inlineToml(path)}`);
}
return await probe(bootstrap, async (request) => {
const { config: settings, layers } = await request("config/read", {
cwd,
includeLayers: Boolean(apiKey || maskCatalog),
});
const { config: settings, layers: nativeLayers } = await request(
"config/read",
{
cwd,
includeLayers: Boolean(apiKey || maskCatalog),
},
);
if (
!isRecord(settings) ||
settings["daybreak"] != null ||
@@ -356,12 +339,9 @@ export async function resolveScanCyberAccessProgram({
const { requirements } = await request("configRequirements/read", {});
const policy = isRecord(requirements) ? requirements : {};
if ((policy["modelProvider"] ?? "openai") !== "openai") return undefined;
const requiredFeatures = isRecord(policy["featureRequirements"])
? policy["featureRequirements"]
: {};
const scopedFeatures = isRecord(settings["features"])
? settings["features"]
: {};
const layers: unknown[] = Array.isArray(nativeLayers) ? nativeLayers : [];
const requiredFeatures = asRecord(policy["featureRequirements"]) ?? {};
const scopedFeatures = asRecord(settings["features"]) ?? {};
if (
(requiredFeatures["cli_daybreak"] ?? scopedFeatures["cli_daybreak"]) ===
false
@@ -371,13 +351,9 @@ export async function resolveScanCyberAccessProgram({
const enabled = (name: string) =>
requiredFeatures[name] ?? scopedFeatures[name] ?? flags.get(name);
if (enabled("cli_daybreak") !== true) return undefined;
let accountType: unknown = "apiKey";
if (!apiKey) {
const { account } = await request("account/read", {
refreshToken: false,
});
accountType = isRecord(account) ? account["type"] : undefined;
}
const accountType = apiKey
? "apiKey"
: await daybreakAccountType(request);
if (accountType === "apiKey") {
if (
enabled("api_key_cyber_access_programs") !== true ||
@@ -410,69 +386,38 @@ export async function resolveScanCyberAccessProgram({
const requiredProvider = openAiProvider(policy["modelProviders"]);
const nativeUrl = (requiredProvider ??
openAiProvider(settings["model_providers"]))?.["model_catalog_url"];
const catalogUrl = requiredProvider
? nativeUrl
: pinned
? url
: (url ?? nativeUrl);
const catalogUrl = requiredProvider || !route ? nativeUrl : route.url;
if (!apiKey)
return nativeUrl === catalogUrl
? probe(policyOverrides, select)
: "standard";
// The isolated key cannot reload a saved workspace's managed network controls.
const application = policy["application"];
if (
enabled("api_key_model_discovery") === false ||
policy["chatgptBaseUrl"] != null ||
policy["enforceResidency"] != null ||
["respect_system_proxy", "system_proxy_fallback", "psp"].some(
(name) => requiredFeatures[name] != null,
) ||
(isRecord(application) &&
isRecord(application["network"]) &&
application["network"]["enabled"] === true) ||
(Array.isArray(layers) && layers.some(hasManagedCatalogSettings))
hasManagedRoute(policy, layers)
)
return "standard";
// Native debug models uses CODEX_API_KEY. Its credential home contains only this call's private configuration.
const keyConfig = catalogConfig(settings);
keyConfig["model_provider"] = "openai";
// Replay the effective native policy exactly once, in a private home without the saved login
// or a second set of project layers. Keep the scan key in the environment and its route in the file.
const keyConfig: JsonObject = {
...catalogConfig(settings),
...pickSettings(settings, ["analytics", "responses_api_metadata"]),
...pickSettings(projected, endpoints),
features: {
...pickSettings(scopedFeatures as JsonObject, catalogFeatures),
...pickSettings(requiredFeatures as JsonObject, catalogFeatures),
},
model_provider: "openai",
...(typeof catalogUrl === "string" && {
model_providers: { openai: { model_catalog_url: catalogUrl } },
}),
project_root_markers: [],
};
delete keyConfig["model_catalog_json"];
for (const key of ["analytics", "responses_api_metadata"]) {
const value = settings[key] ?? resolved[key];
if (value != null) keyConfig[key] = value;
}
for (const key of ["openai_base_url", "chatgpt_base_url"]) {
if (projected[key] != null) keyConfig[key] = projected[key]!;
}
if (typeof catalogUrl === "string")
keyConfig["model_providers"] = {
openai: { model_catalog_url: catalogUrl },
};
await writeCodexConfig(join(scratch, "config.toml"), keyConfig);
const keyEnv = Object.fromEntries(
Object.entries(env).filter(
([name]) =>
!["CODEX_ACCESS_TOKEN", "CODEX_HOME"].includes(name.toUpperCase()),
),
);
const overrides = policyOverrides.filter(
(flag) => flag.startsWith("features.") || flag.startsWith("features="),
);
overrides.push('model_provider="openai"');
for (const name of catalogFeatures) {
if (typeof requiredFeatures[name] === "boolean")
overrides.push(`features.${name}=${requiredFeatures[name]}`);
}
const raw = await nativeModels(
catalogCommand,
cwd,
{ ...keyEnv, CODEX_HOME: scratch, CODEX_API_KEY: apiKey },
[...overrides.flatMap((flag) => ["-c", flag]), "debug", "models"],
signal,
);
const raw = await debugModels({ ...isolated, CODEX_API_KEY: apiKey });
const catalog = JSON.parse(raw).models;
const row = Array.isArray(catalog)
? catalog.find(
@@ -243,113 +243,84 @@ test.each(cases)(
},
);
test.each([
{
programs: ["standard", "daybreak_red", "daybreak_blue"],
expected: "daybreak_blue",
},
{ programs: ["standard", "daybreak_red"], expected: "standard" },
])(
"fresh and resumed direct Deep Scan workers automatically request $expected",
async ({ programs, expected }) => {
const root = await temporaryDirectory();
const repository = join(root, "repository");
const home = join(root, "home");
const scanDir = join(root, "scan");
for (const path of [repository, home, scanDir])
await mkdir(path, { mode: 0o700 });
const catalog = JSON.parse(
await readFile(
new URL("./fixtures/native-skill-model-catalog.json", import.meta.url),
"utf8",
test("automatically selected Blue reaches fresh and resumed direct workers", async () => {
const repository = await temporaryDirectory();
const home = await temporaryDirectory();
const scanDir = await temporaryDirectory();
const environment = {
...Object.fromEntries(
Object.entries(process.env).filter(([name]) =>
/^(path|systemroot|comspec|temp|tmp|tmpdir)$/iu.test(name),
),
);
catalog.models[0].available_access_programs.cyber = programs;
const catalogPath = join(root, "catalog.json");
await writeFile(catalogPath, JSON.stringify(catalog));
const environment = {
...Object.fromEntries(
Object.entries(process.env).filter(([name]) =>
/^(path|systemroot|comspec|temp|tmp|tmpdir)$/iu.test(name),
),
CODEX_API_KEY: "synthetic-worker-key",
CODEX_SECURITY_STATE_DIR: join(home, "state"),
};
const prompt = join(repository, "prompt.md");
await writeFile(prompt, "Test scan.");
const fixture = (relative: string) =>
fileURLToPath(new URL(relative, import.meta.url));
await using client = new TestClient(
{
codexOverrides: {
model: "gpt-test",
model_catalog_json: fixture(
"./fixtures/native-skill-model-catalog.json",
),
),
CODEX_HOME: home,
CODEX_API_KEY: "synthetic-worker-key",
CODEX_SECURITY_STATE_DIR: join(root, "state"),
};
const runtime = {
...preparedRuntime(home),
},
},
{
...scanRuntimeDependencies(home, scanDir),
environment,
configPath: join(home, "scan.toml"),
};
const prompt = join(root, "prompt.md");
await writeFile(prompt, "Test scan.");
await using client = new TestClient(
{
codexOverrides: {
model: "gpt-test",
model_catalog_json: catalogPath,
},
},
{
...scanRuntimeDependencies(home, scanDir),
prepareRuntime: async () => ({
...preparedRuntime(home),
environment,
prepareRuntime: async () => runtime,
canRunDirectDeepScan: () => true,
resolveScanCyberAccessProgram,
createCodex: codexFactory(rejecting("unexpected parent turn")),
runDeepScan: async function* ({ codexOptions, preflightCommand }) {
const output = execFileSync(
process.execPath,
[
fileURLToPath(
new URL(
"./fixtures/stored-daybreak-workers.mjs",
import.meta.url,
),
),
fileURLToPath(
new URL(
"../../../plugins/codex-security/mcp-app/src/deep-scan/executor.ts",
import.meta.url,
),
),
prompt,
"--local-provider",
],
{
cwd: repository,
env: {
...codexOptions.env,
CODEX_CLI_PATH: preflightCommand.command,
CODEX_API_KEY: codexOptions.apiKey,
},
input:
'{"kind":"discovery"}\n{"kind":"discovery","resumePrevious":true}\n',
encoding: "utf8",
configPath: join(home, "scan.toml"),
}),
canRunDirectDeepScan: () => true,
resolveScanCyberAccessProgram,
createCodex: codexFactory(rejecting("unexpected parent turn")),
runDeepScan: async function* ({ codexOptions, preflightCommand }) {
const output = execFileSync(
process.execPath,
[
fixture("./fixtures/stored-daybreak-workers.mjs"),
fixture(
"../../../plugins/codex-security/mcp-app/src/deep-scan/executor.ts",
),
prompt,
"--local-provider",
],
{
cwd: repository,
env: {
...codexOptions.env,
CODEX_CLI_PATH: preflightCommand.command,
CODEX_API_KEY: codexOptions.apiKey,
},
);
const [, fresh, resumed] = output
.trimEnd()
.split("\n")
.map((line) => JSON.parse(line));
expect(fresh).toMatchObject({
requestedProgram: expected,
program: expected,
resumed: false,
});
expect(resumed).toMatchObject({
requestedProgram: expected,
program: expected,
resumed: true,
threadId: fresh.threadId,
});
throw new Error("worker launches verified");
},
input:
'{"kind":"discovery"}\n{"kind":"discovery","resumePrevious":true}\n',
encoding: "utf8",
},
);
const [, fresh, resumed] = output
.trimEnd()
.split("\n")
.map((line) => JSON.parse(line));
expect(fresh).toMatchObject({
program: "daybreak_blue",
resumed: false,
});
expect(resumed).toMatchObject({
program: "daybreak_blue",
resumed: true,
threadId: fresh.threadId,
});
throw new Error("worker launches verified");
},
);
await expect(client.run(repository, { mode: "deep" })).rejects.toThrow(
"worker launches verified",
);
},
);
},
);
await expect(client.run(repository, { mode: "deep" })).rejects.toThrow(
"worker launches verified",
);
});
+70 -205
View File
@@ -2045,159 +2045,6 @@ describe("CodexSecurity orchestration", () => {
await client.close();
});
test.each([
["api-key", "daybreak_blue", false],
["chatgpt", "standard", false],
["api-key", "daybreak_blue", true],
] as const)(
"selects the scan program with %s credentials (expected %s, replacing output %p)",
async (auth, program, archiveExisting) => {
const { root, repository, codexHome, scanDir } = await scanDirectories();
if (archiveExisting) {
await mkdir(join(scanDir, ".codex"));
await writeFile(
join(scanDir, ".codex", "config.toml"),
"daybreak = false\n",
);
}
const repositoryBin = join(repository, "node_modules", ".bin");
const trustedBin = join(root, "bin");
await mkdir(repositoryBin, { recursive: true });
await mkdir(trustedBin);
const environment = {
OPENAI_API_KEY: "synthetic-project-key",
CODEX_SQLITE_HOME: join(root, "stale-sqlite"),
PATH: [repositoryBin, trustedBin].join(delimiter),
};
const sqliteSetting =
auth === "api-key" ? "scan-db" : join(root, "selected-sqlite");
const scanDb = resolve(scanDir, sqliteSetting);
let probeDir: string | undefined;
let catalogMetadata: unknown;
const registered = mock();
const turn = mock(rejecting("synthetic scan turn"));
await using client = new TestClient(
{
codexOverrides: {
model: "synthetic-model",
model_catalog_json: "catalog.json",
responses_api_metadata: { "test.tag": "scan-attribution" },
sqlite_home: sqliteSetting,
},
},
{
...scanRuntimeDependencies(codexHome, scanDir),
environment,
createOperationTelemetry: (options) =>
new OperationTelemetry({
...options,
directory: join(root, "journal"),
}),
prepareRuntime: async () => ({
...preparedRuntime(codexHome),
environment,
}),
resolveScanCyberAccessProgram: async (query) => {
expect(query.model).toBe("synthetic-model");
catalogMetadata = query.config["responses_api_metadata"];
expect(catalogMetadata).toMatchObject({
"test.tag": "scan-attribution",
codex_security_command: "scan",
codex_security_surface: "sdk",
codex_security_operation_id: expect.any(String),
codex_security_attempt_id: expect.any(String),
});
expect(query.config["model_catalog_json"]).toBe(
join(scanDir, "catalog.json"),
);
probeDir = query.cwd;
if (archiveExisting) {
expect(dirname(probeDir)).toBe(dirname(scanDir));
expect(probeDir).not.toBe(scanDir);
expect(await readdir(probeDir)).toEqual([]);
} else expect(probeDir).toBe(scanDir);
expect(query.environment["PATH"]).toBe(await realpath(trustedBin));
expect(query.environment["CODEX_HOME"]).toBe(
await realpath(codexHome),
);
expect(query.environment["OPENAI_API_KEY"]).toBeUndefined();
expect(query.environment["CODEX_API_KEY"]).toBe(
auth === "api-key" ? environment.OPENAI_API_KEY : undefined,
);
return program;
},
runWorkbench: async (options, args, input) => {
if (args[0] === "register-cli-scan") {
expect(options.environment?.["CODEX_SQLITE_HOME"]).toBe(scanDb);
if (archiveExisting) expect(existsSync(probeDir!)).toBe(false);
const recipe = JSON.parse(input!).recipe;
expect(recipe.cyberAccessProgram).toBeUndefined();
expect(recipe.requestedCyberAccessProgram).toBe(program);
}
return mockWorkbench(args, input);
},
createCodex: (options) => {
const metadataOverride = options.configOverrides!.find((value) =>
value.startsWith("responses_api_metadata="),
);
expect(catalogMetadata).toEqual(
parseToml(metadataOverride!)["responses_api_metadata"],
);
expect(options.env?.["CODEX_SQLITE_HOME"]).toBe(scanDb);
expect(options.env?.["PATH"]?.split(delimiter)).toContain(
trustedBin,
);
expect(options.env?.["PATH"]?.split(delimiter)).not.toContain(
repositoryBin,
);
return codexFactory(turn)();
},
},
);
await expect(
client.run(repository, {
auth,
archiveExisting,
outputDir: scanDir,
onScanRegistered: registered,
}),
).rejects.toThrow("synthetic scan turn");
expect(turn).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({ cyberAccessProgram: program }),
);
expect(registered).toHaveBeenCalledWith(
expect.objectContaining({ cyberAccessProgram: program }),
);
},
);
test("keeps existing output and removes the temporary catalog workspace when selection fails", async () => {
const { repository, codexHome, scanDir } = await scanDirectories();
const previous = join(scanDir, "previous.txt");
await writeFile(previous, "previous scan");
let probed: string | undefined;
const registration = mock();
await using client = TestClient.withDependencies({
...scanRuntimeDependencies(codexHome, scanDir),
resolveScanCyberAccessProgram: async ({ cwd }) => {
probed = cwd;
throw new Error("Synthetic Red-only model");
},
});
await expect(
client.run(repository, {
outputDir: scanDir,
archiveExisting: true,
onScanRegistered: registration,
}),
).rejects.toThrow("Synthetic Red-only model");
expect(registration).not.toHaveBeenCalled();
expect(probed).toBeDefined();
expect(existsSync(probed!)).toBe(false);
expect(await readFile(previous, "utf8")).toBe("previous scan");
});
test("retains the registered scan ID when continuation storage becomes unavailable", async () => {
const { root, repository, codexHome, scanDir } = await scanDirectories();
const document = join(root, "architecture.md");
@@ -2348,11 +2195,18 @@ describe("CodexSecurity orchestration", () => {
await client.close();
});
test.each(["revision", "registration", "cancellation", "mock"] as const)(
test.each([
"revision",
"catalog",
"registration",
"cancellation",
"mock",
] as const)(
"keeps existing output when %s prevents scan registration",
async (failurePoint) => {
const { root, repository, codexHome, scanDir } = await scanDirectories();
await writeFile(join(scanDir, "previous.txt"), "previous scan\n");
let catalogDirectory: string | undefined;
const cancellation = new AbortController();
const client = new TestClient(
{ pluginPath: PLUGIN_ROOT },
@@ -2365,6 +2219,13 @@ describe("CodexSecurity orchestration", () => {
if (failurePoint === "cancellation") cancellation.abort();
return null;
},
resolveScanCyberAccessProgram: async ({ cwd }) => {
catalogDirectory = cwd;
expect(dirname(cwd)).toBe(dirname(scanDir));
expect(await readdir(cwd)).toEqual([]);
if (failurePoint === "catalog") throw new Error("Red-only model");
return "daybreak_blue";
},
runWorkbench: async () => {
throw new Error("fixture registration rejected");
},
@@ -2379,7 +2240,10 @@ describe("CodexSecurity orchestration", () => {
signal: cancellation.signal,
mock: failurePoint === "mock",
}),
).rejects.toThrow();
).rejects.toThrow(
failurePoint === "catalog" ? "Red-only model" : undefined,
);
if (catalogDirectory) expect(existsSync(catalogDirectory)).toBe(false);
expect(await readFile(join(scanDir, "previous.txt"), "utf8")).toBe(
"previous scan\n",
);
@@ -2411,12 +2275,18 @@ describe("CodexSecurity orchestration", () => {
prepareRuntime: async () => preparedRuntime(codexHome),
resolvePluginPython: async () => "/managed/python",
repositoryRevision: async () => null,
resolveScanCyberAccessProgram: async () => "daybreak_blue",
runWorkbench: async (
_options: Parameters<typeof runWorkbench>[0],
args: readonly string[],
input?: string,
): Promise<JsonObject> => {
if (args[0] === "register-cli-scan") registration = args;
if (args[0] === "register-cli-scan") {
registration = args;
const recipe = JSON.parse(input!).recipe;
expect(recipe.cyberAccessProgram).toBeUndefined();
expect(recipe.requestedCyberAccessProgram).toBe("daybreak_blue");
}
const result = await runWorkbench(
{
..._options,
@@ -2432,7 +2302,12 @@ describe("CodexSecurity orchestration", () => {
}
return result;
},
createCodex: codexFactory(scanDidNotStart),
createCodex: codexFactory(
async (_prompt: string, turn: { cyberAccessProgram?: string }) => {
expect(turn.cyberAccessProgram).toBe("daybreak_blue");
return scanDidNotStart();
},
),
},
);
@@ -15148,73 +15023,63 @@ if __name__ == "__main__":
);
test.each([
["requestedCyberAccessProgram", "daybreak_blue"],
["requestedCyberAccessProgram", "standard"],
["cyberAccessProgram", "daybreak_red"],
[undefined, undefined],
[{ requestedCyberAccessProgram: "daybreak_blue" }, "daybreak_blue"],
[{ cyberAccessProgram: "daybreak_red" }, "daybreak_red"],
[{}, undefined],
] as const)(
"preserves saved %p=%p across repeated Deep Scan resumes",
async (savedKey, savedProgram) => {
"restores the saved Cyber access program %p",
async (saved, expected) => {
const { repository, codexHome, scanDir } = await scanDirectories();
const scanId = "scan_example_001";
const threadId = "thread-1";
const configPath = join(codexHome, "worker-config.toml");
const configPath = join(codexHome, "worker.toml");
await writeUsageSession(codexHome, threadId, {}, { cwd: scanDir });
const discover = mock<() => Promise<"daybreak_blue" | "standard">>();
const runStreamed = mock(rejecting("resumed turn reached"));
const recipe = {
repository,
target: { kind: "repository", paths: [] },
...saved,
};
const runStreamed = mock(rejecting("resumed turn"));
await using client = TestClient.withDependencies({
...scanRuntimeDependencies(codexHome, scanDir),
prepareRuntime: async () => ({
...preparedRuntime(codexHome),
configPath,
}),
resolveScanCyberAccessProgram: discover,
resolveScanCyberAccessProgram: rejecting("unexpected rediscovery"),
readDeepScanParentConfig: async () => undefined,
createCodex: () => ({
startThread: throwing("Expected the original scan thread"),
resumeThread: () => ({ id: threadId, runStreamed }),
}),
runWorkbench: async (_options, args, input): Promise<JsonObject> =>
args[0] === "get-cli-scan-resume"
? {
scanId,
scanDir,
...mockScanRegistration(
["--registration-json-stdin", "--scan-dir", scanDir],
JSON.stringify({ recipe }),
),
recipe,
threadId,
targetId: "target_sha256_example",
targetRevision: "deadbeef",
contract: { target: { allowedKinds: ["git_revision"] } },
recipe: {
repository,
target: { kind: "repository", paths: [] },
...(savedKey === undefined
? {}
: { [savedKey]: savedProgram }),
},
}
: mockWorkbench(args, input),
createCodex: () => ({
startThread: throwing("expected resume"),
resumeThread: () => ({ id: threadId, runStreamed }),
}),
});
for (const available of ["daybreak_blue", "standard"] as const) {
discover.mockResolvedValue(available);
await expect(
client.run(repository, {
mode: "deep",
resumeScanId: scanId,
outputDir: scanDir,
}),
).rejects.toThrow("resumed turn reached");
expect(runStreamed).toHaveBeenLastCalledWith(
expect.any(String),
expect.objectContaining({ cyberAccessProgram: savedProgram }),
);
expect(
parseToml(await readFile(configPath, "utf8"))["codex_security"],
).toEqual(
savedProgram === undefined
? undefined
: { cyber_access_program: savedProgram },
);
}
expect(discover).not.toHaveBeenCalled();
await expect(
client.run(repository, {
mode: "deep",
resumeScanId: scanId,
outputDir: scanDir,
}),
).rejects.toThrow("resumed turn");
expect(runStreamed).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({ cyberAccessProgram: expected }),
);
expect(
parseToml(await readFile(configPath, "utf8"))["codex_security"],
).toEqual(
expected === undefined ? undefined : { cyber_access_program: expected },
);
},
);
@@ -85,11 +85,8 @@ async function patchSettings(
homeConfig?: string;
standalone?: boolean;
programs?: string[];
cachedScanProgram?: ScanResult["requestedCyberAccessProgram"];
scan?: Pick<
NonNullable<Parameters<typeof dependencies>[0]>,
"onTurn" | "onValidate"
>;
scanProgram?: ScanResult["requestedCyberAccessProgram"];
onValidate?: NonNullable<Parameters<typeof dependencies>[0]>["onValidate"];
} = {},
): Promise<ChildReceipt> {
const root = await temporaryDirectory("inline-patch-settings-");
@@ -103,7 +100,7 @@ async function patchSettings(
const result = new ScanResult({
...fakeResult(["high"]),
scanDir: root,
requestedCyberAccessProgram: options.cachedScanProgram,
requestedCyberAccessProgram: options.scanProgram,
});
Object.assign(result.findings.findings[0]!, {
occurrenceId: "occ_1",
@@ -152,7 +149,7 @@ async function patchSettings(
"--json",
],
dependencies({
...options.scan,
onValidate: options.onValidate,
currentDirectory: repository,
environment,
result,
@@ -428,36 +425,23 @@ describe("inline patch service tier", () => {
});
describe("patch Daybreak configuration", () => {
test.each([false, true])(
"validation and patching inherit automatically selected Blue (cached scan: %p)",
async (cached) => {
const validationPrograms: Array<string | undefined> = [];
const child = await patchSettings(["--validate"], {
cachedScanProgram: cached ? "daybreak_blue" : undefined,
scan: {
onTurn: (_, scan) => {
if (cached) return;
scan.onScanRegistered?.({
scanId: "scan",
scanDir: "/synthetic/scan",
cyberAccessProgram: "daybreak_blue",
});
},
onValidate: async (validation) => {
validationPrograms.push(validation.cyberAccessProgram);
return {
disposition: "deferred",
report: "Additional evidence needed.",
threadId: "validation-thread",
outputDir: "evidence",
};
},
},
});
expect(validationPrograms).toEqual(["daybreak_blue"]);
expect(child.cyberAccessProgram).toBe("daybreakBlue");
},
);
test("validation and patching reuse the scan’s selected program", async () => {
const validationPrograms: Array<string | undefined> = [];
const child = await patchSettings(["--validate"], {
scanProgram: "daybreak_blue",
onValidate: async (validation) => {
validationPrograms.push(validation.cyberAccessProgram);
return {
disposition: "deferred",
report: "Additional evidence needed.",
threadId: "validation-thread",
outputDir: "evidence",
};
},
});
expect(validationPrograms).toEqual(["daybreak_blue"]);
expect(child.cyberAccessProgram).toBe("daybreakBlue");
});
test.each([true, false, undefined])(
"preserves standalone native configuration (override: %p)",
+22 -27
View File
@@ -976,41 +976,36 @@ test("CLI restores the dashboard and reports saved partial results on cancellati
test("component matching requests Blue with the bundled model catalog", async () => {
const paths = await fixture();
const home = await temporaryDirectory();
const catalog = fileURLToPath(
new URL("./fixtures/native-skill-model-catalog.json", import.meta.url),
);
const turn = spyOn(Thread.prototype, "run").mockResolvedValue({
using turn = spyOn(Thread.prototype, "run").mockResolvedValue({
finalResponse: JSON.stringify(noMatches),
items: [],
usage: null,
});
try {
const result = await scan(paths, {
components: components.slice(0, 2),
matchFindings: undefined,
environment: {
PATH: process.env["PATH"],
SystemRoot: process.env["SystemRoot"],
CODEX_HOME: home,
OPENAI_API_KEY: "synthetic-key",
const result = await scan(paths, {
components: components.slice(0, 2),
matchFindings: undefined,
environment: {
PATH: process.env["PATH"],
SystemRoot: process.env["SystemRoot"],
CODEX_HOME: await temporaryDirectory(),
OPENAI_API_KEY: "synthetic-key",
},
config: {
codexOverrides: {
model: "gpt-test",
model_catalog_json: catalog,
chatgpt_base_url: "http://127.0.0.1:1",
openai_base_url: "http://127.0.0.1:1/v1",
},
config: {
codexOverrides: {
model: "gpt-test",
model_catalog_json: catalog,
chatgpt_base_url: "http://127.0.0.1:1",
openai_base_url: "http://127.0.0.1:1/v1",
},
},
});
expect(result.deduplication?.error).toBeUndefined();
expect(
turn.mock.calls.map(([, options]) => options?.cyberAccessProgram),
).toEqual(["daybreak_blue"]);
} finally {
turn.mockRestore();
}
},
});
expect(result.deduplication?.error).toBeUndefined();
expect(
turn.mock.calls.map(([, options]) => options?.cyberAccessProgram),
).toEqual(["daybreak_blue"]);
});
test("merges confirmed root causes with complete evidence and the highest severity", async () => {
@@ -112,9 +112,6 @@ try {
tools: requests.at(-1)?.tools ?? [],
}),
program: requests.at(-1)?.access_programs?.cyber,
requestedProgram: workerArgs.includes("--cyber-access-program")
? workerArgs[workerArgs.indexOf("--cyber-access-program") + 1]
: null,
daybreak: config.daybreak ?? null,
telemetry: {
analyticsEnabled: config.analytics?.enabled ?? null,
@@ -177,7 +177,7 @@ describe("semantic scan comparison", () => {
] as const)(
"preserves request metadata and attributes %s %s at the model boundary",
async (surface, helper) => {
const root = await temporaryDirectory();
const root = await realpath(await temporaryDirectory());
const home = join(root, "home");
const checkout = join(root, "checkout");
const repository = join(checkout, "repository");
@@ -211,9 +211,7 @@ describe("semantic scan comparison", () => {
},
},
environment: {
PATH: [await realpath(repositoryBin), process.env["PATH"]].join(
delimiter,
),
PATH: [repositoryBin, process.env["PATH"]].join(delimiter),
SystemRoot: process.env["SystemRoot"],
CODEX_HOME: home,
CODEX_SECURITY_STATE_DIR: state,
@@ -226,11 +224,11 @@ describe("semantic scan comparison", () => {
? { components: [{ name: "Source", paths: ["source.ts"] }] }
: { matches: [], uncertain: [] },
);
const login = spyOn(auth, "accountStatus").mockResolvedValue({
using _login = spyOn(auth, "accountStatus").mockResolvedValue({
authenticated: true,
details: "Logged in using ChatGPT",
});
const discovery = spyOn(
using discovery = spyOn(
cyberAccess,
"resolveScanCyberAccessProgram",
).mockResolvedValue("daybreak_blue");
@@ -260,13 +258,13 @@ describe("semantic scan comparison", () => {
expect(probe.environment["CODEX_API_KEY"]).toBe(
surface === "sdk" ? "synthetic-key" : undefined,
);
expect(await realpath(probe.environment["CODEX_HOME"]!)).toBe(
await realpath(surface === "sdk" ? home : privateHome),
expect(probe.environment["CODEX_HOME"]).toBe(
surface === "sdk" ? home : privateHome,
);
expect(probe.config).not.toHaveProperty("openai_base_url");
expect(probe.config).not.toHaveProperty("chatgpt_base_url");
expect(probe.environment["PATH"]?.split(delimiter)).not.toContain(
await realpath(repositoryBin),
repositoryBin,
);
expect(probe.environment["PATH"]).toBe(captured?.env?.["PATH"]);
expect(probe.config).toHaveProperty(
@@ -288,8 +286,6 @@ describe("semantic scan comparison", () => {
codex_security_package_version: VERSION,
});
} finally {
login.mockRestore();
discovery.mockRestore();
startThread.mockRestore();
}
},
+96 -182
View File
@@ -1,68 +1,49 @@
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, beforeEach, expect, spyOn, test } from "bun:test";
import { resolveBundledCodexExecutable } from "../src/codex-sdk-environment.js";
import type { JsonObject } from "../src/config.js";
import { resolveScanCyberAccessProgram } from "../src/scan-cyber-access.js";
import * as runtime from "../src/runtime.js";
import catalogFixture from "./fixtures/native-skill-model-catalog.json" with { type: "json" };
import { writeJson } from "./support/json.js";
import { chatGptTokens } from "./support/chatgpt-credentials.js";
import { createApiTestFixtures } from "./support/temporary-directories.js";
const loopback = "http://127.0.0.1:1";
const savedLogin = JSON.stringify({
auth_mode: "chatgpt",
tokens: chatGptTokens,
});
const privateUrl = "http://127.0.0.1:1/private-catalog";
const privateRoute = {
model_providers: { openai: { model_catalog_url: privateUrl } },
};
const { temporaryDirectory, cleanup } = createApiTestFixtures("scan-cyber-");
const endpoint = "http://127.0.0.1:1";
const homeSettings = `chatgpt_base_url="${endpoint}"\nopenai_base_url="${endpoint}/v1"\n`;
const savedLogin = { auth_mode: "chatgpt", tokens: chatGptTokens };
const stored = { environment: { CODEX_API_KEY: "" } };
let home: string;
let catalog: string;
beforeEach(async () => {
home = await mkdtemp(join(tmpdir(), "scan-cyber-access-"));
home = await temporaryDirectory();
catalog = join(home, "catalog.json");
const fixture = JSON.parse(
await readFile(
new URL("./fixtures/native-skill-model-catalog.json", import.meta.url),
"utf8",
),
).models[0];
const base = catalogFixture.models[0]!;
const model = (slug: string, cyber?: string[]) => ({
...fixture,
...base,
slug,
available_access_programs: cyber && { cyber },
});
await Promise.all([
writeFile(join(home, "auth.json"), savedLogin, { mode: 0o600 }),
writeFile(
join(home, "config.toml"),
`chatgpt_base_url="${loopback}"\nopenai_base_url="${loopback}/v1"\n`,
),
writeFile(
catalog,
JSON.stringify({
models: [
model("blue-and-red", ["standard", "daybreak_red", "daybreak_blue"]),
model("standard-and-red", ["daybreak_red", "standard"]),
model("red-only", ["daybreak_red"]),
model("missing-metadata"),
],
}),
),
]);
});
afterEach(async () => {
await rm(home, { recursive: true, force: true });
await writeJson(join(home, "auth.json"), savedLogin);
await writeFile(join(home, "config.toml"), homeSettings);
await writeJson(catalog, {
models: [
base,
model("standard", ["daybreak_red", "standard"]),
model("red", ["daybreak_red"]),
model("no-metadata"),
],
});
});
afterEach(cleanup);
type SelectorOptions = Pick<
Parameters<typeof resolveScanCyberAccessProgram>[0],
"command" | "program" | "environment"
"command" | "environment"
>;
function select(
model: string,
config: JsonObject = {},
@@ -86,117 +67,71 @@ function select(
config: {
model_catalog_json: catalog,
cli_auth_credentials_store: "file",
openai_base_url: loopback + "/v1",
chatgpt_base_url: loopback,
openai_base_url: endpoint + "/v1",
chatgpt_base_url: endpoint,
analytics: { enabled: false },
...config,
},
signal: new AbortController().signal,
program: options.program,
});
}
test("bundled scans select from the requested model's advertised programs", async () => {
expect(
await select("blue-and-red", { model_catalog_json: "catalog.json" }),
).toBe("daybreak_blue");
expect(await select("standard-and-red")).toBe("standard");
await expect(select("red-only")).rejects.toThrow(
test("bundled scans use available model programs even with remote discovery disabled", async () => {
const offline = {
features: { api_key_model_discovery: false },
model_catalog_json: "catalog.json",
};
expect(await select("gpt-test", offline)).toBe("daybreak_blue");
expect(await select("standard", offline)).toBe("standard");
await expect(select("red", offline)).rejects.toThrow(
"--cyber-access-program daybreak_red",
);
expect(await select("missing-metadata")).toBe("standard");
expect(await select("absent-model")).toBe("standard");
for (const model of ["no-metadata", "absent"])
expect(await select(model, offline)).toBe("standard");
expect(
await select("gpt-test", { ...offline, model_catalog_json: null }),
).toBe("standard");
await expect(
select("blue-and-red", { model_catalog_json: "missing.json" }),
select("gpt-test", { model_catalog_json: "missing.json" }),
).rejects.toThrow(/os error 2|ENOENT/i);
});
test("model discovery and access-program forwarding follow their own native gates", async () => {
const offline = { features: { api_key_model_discovery: false } };
expect(await select("blue-and-red", offline)).toBe("daybreak_blue");
await expect(select("red-only", offline)).rejects.toThrow(
"requires Daybreak Red",
);
test("the API-key forwarding gate is scoped to the selected credentials", async () => {
const disabled = { "features.api_key_cyber_access_programs": false };
expect(await select("gpt-test", disabled)).toBeUndefined();
expect(await select("gpt-test", disabled, stored)).toBe("daybreak_blue");
expect(
await select("blue-and-red", { ...offline, model_catalog_json: null }),
).toBe("standard");
expect(
await select("blue-and-red", { features: { cli_daybreak: false } }),
).toBeUndefined();
const disabled = { features: { api_key_cyber_access_programs: false } };
expect(await select("blue-and-red", disabled)).toBeUndefined();
expect(
await select("blue-and-red", {
"features.api_key_cyber_access_programs": false,
}),
).toBeUndefined();
expect(
await select("blue-and-red", {
await select("gpt-test", {
features: { api_key_cyber_access_programs: true },
"features.api_key_cyber_access_programs": false,
}),
).toBe("daybreak_blue");
expect(
await select("blue-and-red", disabled, {
environment: { CODEX_API_KEY: "" },
...disabled,
}),
).toBe("daybreak_blue");
});
test("project keys and stored logins follow their own catalog routes", async () => {
for (const route of [
privateRoute,
{ "model_providers.openai.model_catalog_url": privateUrl },
]) {
await expect(
select("blue-and-red", { ...route, model_catalog_json: null }),
).rejects.toThrow("must use an allowed ChatGPT host");
}
const stored = { environment: { CODEX_API_KEY: "" } };
expect(
await select(
"blue-and-red",
{ ...privateRoute, model_catalog_json: null },
stored,
),
).toBe("standard");
test("native catalog routing follows the scan's selected identity", async () => {
const route = {
model_catalog_json: null,
"model_providers.openai.model_catalog_url": endpoint + "/private-catalog",
};
await expect(select("gpt-test", route)).rejects.toThrow(
"must use an allowed ChatGPT host",
);
expect(await select("gpt-test", route, stored)).toBe("standard");
const configuredUrl = "https://chatgpt.com/backend-api/codex/models";
await writeFile(
join(home, "config.toml"),
`chatgpt_base_url="${loopback}"\nmodel_catalog_json=${JSON.stringify(catalog)}\n[model_providers.openai]\nmodel_catalog_url=${JSON.stringify(configuredUrl)}\n`,
homeSettings + `model_catalog_json=${JSON.stringify(catalog)}\n`,
);
expect(
await select(
"blue-and-red",
{
model_catalog_json: null,
model_providers: { openai: { model_catalog_url: configuredUrl } },
},
stored,
),
).toBe("daybreak_blue");
expect(await select("blue-and-red", { model_catalog_json: null })).toBe(
"daybreak_blue",
);
expect(await readFile(join(home, "auth.json"), "utf8")).toBe(savedLogin);
const storedKey = JSON.stringify({
for (const credentials of [stored, {}])
expect(await select("gpt-test", route, credentials)).toBe("daybreak_blue");
expect(await Bun.file(join(home, "auth.json")).json()).toEqual(savedLogin);
await writeJson(join(home, "auth.json"), {
auth_mode: "apikey",
OPENAI_API_KEY: "synthetic-stored-key",
});
await writeFile(join(home, "auth.json"), storedKey, { mode: 0o600 });
const offline = {
...privateRoute,
model_catalog_json: null,
features: { api_key_model_discovery: false },
};
expect(await select("blue-and-red", offline, stored)).toBe("daybreak_blue");
await expect(select("red-only", offline, stored)).rejects.toThrow(
await expect(select("red", route, stored)).rejects.toThrow(
"requires Daybreak Red",
);
expect(await readFile(join(home, "auth.json"), "utf8")).toBe(storedKey);
});
test("the remote catalog subprocess uses only the project key and its private route", async () => {
@@ -205,16 +140,14 @@ test("the remote catalog subprocess uses only the project key and its private ro
using probe = spyOn(runtime, "runCodexCommand").mockImplementation(
async (...inputs) => {
const [command, args, env] = inputs;
if (args.at(-1) !== "models") return run(...inputs);
if (!env["CODEX_API_KEY"]) return run(...inputs);
expect(env["CODEX_API_KEY"]).toBe("synthetic-scan-key");
expect(env["OPENAI_API_KEY"]).toBeUndefined();
const keyHome = env["CODEX_HOME"]!;
expect(keyHome).not.toBe(home);
await expect(readFile(join(keyHome, "auth.json"))).rejects.toMatchObject({
code: "ENOENT",
});
expect(await Bun.file(join(keyHome, "auth.json")).exists()).toBe(false);
const config = Bun.TOML.parse(
await readFile(join(keyHome, "config.toml"), "utf8"),
await Bun.file(join(keyHome, "config.toml")).text(),
);
expect(config).toMatchObject({
model_providers: { openai: { model_catalog_url: route } },
@@ -224,13 +157,13 @@ test("the remote catalog subprocess uses only the project key and its private ro
success: true,
exitCode: 0,
stderr: "",
stdout: await readFile(catalog, "utf8"),
stdout: JSON.stringify(catalogFixture),
};
},
);
expect(
await select(
"blue-and-red",
"gpt-test",
{
model_catalog_json: null,
model_providers: { openai: { model_catalog_url: route } },
@@ -262,16 +195,21 @@ test("managed policy uses the saved login on its own endpoint and disables Blue
id_token: `eyJhbGciOiJub25lIn0.${claims}.c2ln`,
},
});
const paths: string[] = [];
let servedPolicy = false;
const policyPath = "/backend-api/wham/config/bundle";
const endpoint = Bun.serve({
const paths: string[] = [];
const policy = {
id: "managed",
name: "Disabled Daybreak",
contents: "[features]\ncli_daybreak=false\n",
};
using server = Bun.serve({
hostname: "127.0.0.1",
port: 0,
fetch(request) {
const path = new URL(request.url).pathname;
paths.push(path);
if (path !== policyPath) return new Response(null, { status: 404 });
if (path !== "/backend-api/wham/config/bundle")
return new Response(null, { status: 404 });
if (
request.headers.get("authorization") !==
`Bearer ${chatGptTokens.access_token}` ||
@@ -280,37 +218,25 @@ test("managed policy uses the saved login on its own endpoint and disables Blue
return new Response(null, { status: 403 });
servedPolicy = true;
return Response.json({
requirements_toml: {
enterprise_managed: [
{
id: "managed-feature",
name: "Disabled Daybreak",
contents: "[features]\ncli_daybreak=false\n",
},
],
},
requirements_toml: { enterprise_managed: [policy] },
});
},
});
try {
const origin = endpoint.url.origin;
await writeFile(join(home, "auth.json"), login, { mode: 0o600 });
await writeFile(
join(home, "config.toml"),
`chatgpt_base_url="${origin}/backend-api"\n`,
);
expect(
await select("blue-and-red", {
chatgpt_base_url: origin + "/project",
openai_base_url: origin + "/project/v1",
}),
).toBeUndefined();
expect(servedPolicy).toBe(true);
expect(paths.some((path) => path.startsWith("/project"))).toBe(false);
expect(await readFile(join(home, "auth.json"), "utf8")).toBe(login);
} finally {
await endpoint.stop(true);
}
const origin = server.url.origin;
await writeFile(join(home, "auth.json"), login, { mode: 0o600 });
await writeFile(
join(home, "config.toml"),
`chatgpt_base_url="${origin}/backend-api"\n`,
);
expect(
await select("gpt-test", {
chatgpt_base_url: origin + "/project",
openai_base_url: origin + "/project/v1",
}),
).toBeUndefined();
expect(servedPolicy).toBe(true);
expect(paths.some((path) => path.startsWith("/project"))).toBe(false);
expect(await readFile(join(home, "auth.json"), "utf8")).toBe(login);
});
test("native preferences and non-OpenAI authentication bypass automatic selection", async () => {
@@ -318,27 +244,18 @@ test("native preferences and non-OpenAI authentication bypass automatic selectio
{ daybreak: false },
{ daybreak: true },
{ model_provider: "custom" },
{ "features.cli_daybreak": false },
];
for (const config of nativePreferences) {
expect(await select("red-only", config)).toBeUndefined();
}
for (const config of nativePreferences)
expect(await select("red", config)).toBeUndefined();
for (const name of [
"OPENAI_FEDERATION_RULE_ID",
"OPENAI_IDENTITY_TOKEN_FILE",
]) {
expect(
await select("red-only", {}, { environment: { [name]: "workload" } }),
await select("red", {}, { environment: { [name]: "workload" } }),
).toBeUndefined();
}
for (const program of [
"standard",
"daybreak_blue",
"daybreak_red",
] as const) {
expect(await select("red-only", { daybreak: false }, { program })).toBe(
program,
);
}
});
test("custom executables and launch arguments skip discovery", async () => {
@@ -346,9 +263,6 @@ test("custom executables and launch arguments skip discovery", async () => {
{ command: "nonexistent-catalog-launcher" },
{ command: resolveBundledCodexExecutable(), args: ["--invalid-for-codex"] },
]) {
expect(await select("red-only", {}, { command })).toBeUndefined();
expect(
await select("red-only", {}, { command, program: "daybreak_red" }),
).toBe("daybreak_red");
expect(await select("red", {}, { command })).toBeUndefined();
}
});