mirror of
https://github.com/openai/codex-security.git
synced 2026-11-21 02:12:29 +08:00
feat(cli): make project setup and authentication easier to inspect (#2581)
* feat(cli): expose identifiers for saved scan follow-up * test(sdk): exercise dedupe representatives in publication * feat(cli): make project setup and authentication easier to inspect * docs(cli): distinguish sign-in flows and credential sources * feat(cli): link interrupted scans and imported evidence to their next commands * fix(cli): make command help and discovery reflect runnable workflows * build(sdk): include the command argument helper in package checks * refactor(cli): reuse shell path quoting for project previews * docs(cli): identify the shell used for Windows preview commands * test(cli): account for the internal publication CSV in help coverage * fix(cli): scope recovery hints to supported sessions and shells * fix(cli): declare exclusive scan import sources in the schema * refactor(cli): share credential locking and project preview preparation * fix(cli): resolve repository arguments consistently during scan discovery * refactor(cli): simplify the result handoffs and verify PowerShell recovery * fix(cli): check sign-in from the same directory in every format * fix(cli): preserve diagnostics when project initialization fails --------- Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
co-authored by
Codex
parent
507e10af4f
commit
594604ffb5
@@ -36,6 +36,8 @@ codex-security info -c codex-security.yaml --json
|
||||
codex-security scan . -c codex-security.yaml --dry-run --json
|
||||
```
|
||||
|
||||
The init command prints a preview command using the file it created. On Windows the displayed command uses PowerShell syntax. It includes an editor schema hint when the package is installed in the project. With a global installation the starter contains an empty mapping, which you can replace with your settings. The CLI always validates the file with its bundled schema.
|
||||
|
||||
Check that the preview shows your intended repository and scope. To start the
|
||||
scan with those settings, keep the same file selection:
|
||||
|
||||
|
||||
@@ -12,6 +12,24 @@ pnpm --dir ../../plugins/codex-security/mcp-app install --frozen-lockfile
|
||||
|
||||
The commands below run from `sdk/typescript` unless a different directory is named. For a test that builds or loads the bundled plugin, first [download the universal native payload](../../plugins/codex-security/native/README.md#package-inputs). The SDK’s `test`, `test:ci`, `test:mcp` and `prepack` scripts all build that bundle.
|
||||
|
||||
## Run the CLI from your checkout
|
||||
|
||||
From the repository root, use the source entry point to iterate on commands and help:
|
||||
|
||||
```sh
|
||||
bun sdk/typescript/src/cli.ts scan --help
|
||||
```
|
||||
|
||||
For the Node launcher that npm installs as `cs`, build the SDK first:
|
||||
|
||||
```sh
|
||||
pnpm --dir sdk/typescript run build
|
||||
node sdk/typescript/bin/codex-security.mjs scan --help
|
||||
node sdk/typescript/bin/codex-security.mjs scan . --dry-run --json
|
||||
```
|
||||
|
||||
Saved history, exports, and commands that run the bundled plugin also need the native payload described above and `pnpm --dir sdk/typescript run build:plugin`. The `build:ci` script compiles the repository’s CI helpers.
|
||||
|
||||
## Run a focused test
|
||||
|
||||
Run the file for the behavior you changed. This example exercises progress parsing:
|
||||
|
||||
@@ -156,6 +156,8 @@ If Codex Security reports that the refresh token was already used, run
|
||||
`codex-security logout`, then `codex-security login`. If your Codex CLI or app
|
||||
reports that error, sign out and sign back in there.
|
||||
|
||||
Use `codex-security login status --json` in automation. Its stdout reports `authenticated`, the effective authentication `method`, and the environment variable name when an API key takes precedence. Native diagnostics go to stderr. The command keeps the exit status of the human-readable status check.
|
||||
|
||||
For other refresh errors, check `codex-security login status`. Retry if the
|
||||
sign-in recently changed. Otherwise run `codex-security logout`, then
|
||||
`codex-security login`.
|
||||
|
||||
+216
-110
@@ -302,6 +302,7 @@ import type { ScanResult } from "./result.js";
|
||||
import { importScan, type ImportScanOptions } from "./import-scan.js";
|
||||
import {
|
||||
bundledPluginRoot,
|
||||
runCodexCommand,
|
||||
cleanupSdkDirectory,
|
||||
createIsolatedHome,
|
||||
resolvePluginPath,
|
||||
@@ -1715,6 +1716,9 @@ function signalHandlers(
|
||||
dependencies[`${operation}SignalListener`]("SIGTERM", terminate);
|
||||
}
|
||||
|
||||
// Login and status must not load configuration from the caller's checkout.
|
||||
const NEUTRAL_CODEX_CWD = parse(process.execPath).root;
|
||||
|
||||
export async function runCodexSkillCommand(
|
||||
args: readonly string[],
|
||||
output?: SkillCommandOutput,
|
||||
@@ -1990,7 +1994,7 @@ async function runCodexSkillProcess(
|
||||
[...args],
|
||||
{
|
||||
env: environment,
|
||||
cwd: output?.appServer?.directory ?? parse(process.execPath).root,
|
||||
cwd: output?.appServer?.directory ?? NEUTRAL_CODEX_CWD,
|
||||
stdio:
|
||||
output === undefined
|
||||
? [input === undefined ? "inherit" : "pipe", "inherit", "pipe"]
|
||||
@@ -5069,9 +5073,23 @@ export async function main(
|
||||
});
|
||||
},
|
||||
});
|
||||
const withLoginEnvironment = async (
|
||||
run: (
|
||||
environment: NodeJS.ProcessEnv & { CODEX_HOME: string },
|
||||
) => Promise<number>,
|
||||
) => {
|
||||
const home = await prepareCodexSecurityCredentialHome(
|
||||
dependencies.environment,
|
||||
);
|
||||
return withCredentialHomeLock(home, () =>
|
||||
run({ ...dependencies.environment, CODEX_HOME: home }),
|
||||
);
|
||||
};
|
||||
|
||||
const infoOutput = z.object({
|
||||
sdkVersion: z.string(),
|
||||
bundledPluginVersion: z.string(),
|
||||
bundledPluginAvailable: z.boolean(),
|
||||
scanMcp: z.literal(false),
|
||||
cancellationNote: z.string(),
|
||||
cliVersion: z.string(),
|
||||
@@ -7556,103 +7574,76 @@ export async function main(
|
||||
}
|
||||
},
|
||||
})
|
||||
.command("login", {
|
||||
description: "Sign in with ChatGPT or store credentials.",
|
||||
hint:
|
||||
"For remote login, use --device-auth if your workspace allows it.\n" +
|
||||
"If device auth is disabled, sign in over SSH:\n" +
|
||||
" On your local machine (replace user@remote):\n" +
|
||||
" ssh -L 1455:localhost:1455 user@remote\n" +
|
||||
" In that SSH session:\n" +
|
||||
" codex-security login\n" +
|
||||
" Open the sign-in URL in your local browser.\n" +
|
||||
" Keep SSH connected until login finishes.\n" +
|
||||
"Docs: https://learn.chatgpt.com/docs/auth?surface=cli#cli-fallback-forward-the-localhost-callback-over-ssh",
|
||||
destructive: true,
|
||||
args: z.object({
|
||||
action: z
|
||||
.enum(["status"])
|
||||
.optional()
|
||||
.describe("Use status to inspect credentials; omit to sign in."),
|
||||
}),
|
||||
options: z.object({
|
||||
deviceAuth: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe("Use device auth if your workspace allows it."),
|
||||
withApiKey: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe("Read an API key from stdin."),
|
||||
withAccessToken: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe("Read an access token from stdin."),
|
||||
}),
|
||||
examples: [
|
||||
{ args: {}, description: "Sign in with ChatGPT." },
|
||||
{ args: { action: "status" }, description: "Check authentication." },
|
||||
],
|
||||
async run({ args, options }) {
|
||||
const credentialHome = await prepareCodexSecurityCredentialHome(
|
||||
dependencies.environment,
|
||||
);
|
||||
const authentication = scanAuthentication(dependencies.environment);
|
||||
exitCode = await withCredentialHomeLock(credentialHome, async () => {
|
||||
if (args.action === undefined) {
|
||||
.command(
|
||||
Cli.create("login", {
|
||||
description: "Sign in with ChatGPT or store credentials.",
|
||||
hint: "Check the effective sign-in with codex-security login status. For a remote machine use --device-auth if your workspace permits it. For SSH, on your local machine run:\n ssh -L 1455:localhost:1455 user@remote\nThen, in that SSH session:\n codex-security login\nOpen the sign-in URL locally and keep SSH connected until login finishes.\nhttps://learn.chatgpt.com/docs/auth?surface=cli#cli-fallback-forward-the-localhost-callback-over-ssh",
|
||||
destructive: true,
|
||||
options: z.object({
|
||||
deviceAuth: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe("Use device auth if your workspace allows it."),
|
||||
withApiKey: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe("Read an API key from stdin."),
|
||||
withAccessToken: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe("Read an access token from stdin."),
|
||||
}),
|
||||
examples: [
|
||||
{ options: {}, description: "Sign in using the browser." },
|
||||
{
|
||||
options: { deviceAuth: true },
|
||||
description: "Sign in from a headless machine with device auth.",
|
||||
},
|
||||
{
|
||||
options: { withApiKey: true },
|
||||
description:
|
||||
"Pipe an API key on stdin from your credential source.",
|
||||
},
|
||||
],
|
||||
async run({ options }) {
|
||||
const authentication = scanAuthentication(dependencies.environment);
|
||||
exitCode = await withLoginEnvironment(async (environment) => {
|
||||
await prepareLoginConfig(
|
||||
credentialHome,
|
||||
environment.CODEX_HOME,
|
||||
await readCodexAuthConfig(
|
||||
scanCodexHome(dependencies.environment),
|
||||
true,
|
||||
),
|
||||
);
|
||||
} else if (authentication.method !== "api_key") {
|
||||
await initialCredentialsAvailable(
|
||||
dependencies.environment,
|
||||
scanCodexHome(dependencies.environment),
|
||||
credentialHome,
|
||||
const status = await dependencies.runCodex(
|
||||
[
|
||||
"login",
|
||||
...(options.deviceAuth ? ["--device-auth"] : []),
|
||||
...(options.withApiKey ? ["--with-api-key"] : []),
|
||||
...(options.withAccessToken ? ["--with-access-token"] : []),
|
||||
],
|
||||
undefined,
|
||||
environment,
|
||||
);
|
||||
}
|
||||
const status = await dependencies.runCodex(
|
||||
[
|
||||
"login",
|
||||
...(args.action === undefined ? [] : [args.action]),
|
||||
...(options.deviceAuth ? ["--device-auth"] : []),
|
||||
...(options.withApiKey ? ["--with-api-key"] : []),
|
||||
...(options.withAccessToken ? ["--with-access-token"] : []),
|
||||
],
|
||||
undefined,
|
||||
{ ...dependencies.environment, CODEX_HOME: credentialHome },
|
||||
);
|
||||
if (args.action === undefined && status === 0) {
|
||||
await setCodexSecurityCredentialLogout(credentialHome, false);
|
||||
}
|
||||
return status;
|
||||
});
|
||||
if (args.action === "status") {
|
||||
if (status === 0)
|
||||
await setCodexSecurityCredentialLogout(
|
||||
environment.CODEX_HOME,
|
||||
false,
|
||||
);
|
||||
return status;
|
||||
});
|
||||
if (
|
||||
authentication.method === "api_key" &&
|
||||
(exitCode === 0 || exitCode === 1)
|
||||
exitCode === 0 &&
|
||||
!options.withApiKey &&
|
||||
authentication.method === "api_key"
|
||||
) {
|
||||
exitCode = 0;
|
||||
errorOutput.write(
|
||||
`Effective scan authentication: API key from ${authentication.source}.\n`,
|
||||
);
|
||||
errorOutput.write(
|
||||
`To use a ChatGPT sign-in, ${formatEnvironmentVariableRemovalGuidance(["OPENAI_API_KEY", "CODEX_API_KEY"])}.\n`,
|
||||
);
|
||||
}
|
||||
} else if (exitCode === 0 && !options.withApiKey) {
|
||||
if (authentication.method === "api_key") {
|
||||
const configuredApiKeyVariables = Object.entries(
|
||||
const configuredApiKeyVariables = Object.keys(
|
||||
dependencies.environment,
|
||||
).flatMap(([name, value]) =>
|
||||
value?.trim() &&
|
||||
(name.toUpperCase() === "OPENAI_API_KEY" ||
|
||||
name.toUpperCase() === "CODEX_API_KEY")
|
||||
? name
|
||||
: [],
|
||||
).filter(
|
||||
(name) =>
|
||||
["OPENAI_API_KEY", "CODEX_API_KEY"].includes(
|
||||
name.toUpperCase(),
|
||||
) && dependencies.environment[name]?.trim(),
|
||||
);
|
||||
const loginWarning = options.withAccessToken
|
||||
? `Access-token login succeeded, but noninteractive scans will use ${authentication.source}.\n`
|
||||
@@ -7667,23 +7658,80 @@ export async function main(
|
||||
`${formatEnvironmentVariableRemovalGuidance(configuredApiKeyVariables)}.\n`,
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
},
|
||||
}).command("status", {
|
||||
description: "Check effective scan authentication.",
|
||||
hint: "Use codex-security login status --json for automation. With stored credentials, the first check can import an existing Codex sign-in.",
|
||||
output: z
|
||||
.object({
|
||||
authenticated: z.boolean(),
|
||||
method: z.enum(["api_key", "stored_credentials"]),
|
||||
source: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
async run({ format }) {
|
||||
const structured = !useDefaultOutput(format);
|
||||
const authentication = scanAuthentication(dependencies.environment);
|
||||
exitCode = await withLoginEnvironment(async (environment) => {
|
||||
if (authentication.method !== "api_key")
|
||||
await initialCredentialsAvailable(
|
||||
dependencies.environment,
|
||||
scanCodexHome(dependencies.environment),
|
||||
environment.CODEX_HOME,
|
||||
);
|
||||
if (!structured)
|
||||
return await dependencies.runCodex(
|
||||
["login", "status"],
|
||||
undefined,
|
||||
environment,
|
||||
);
|
||||
const native = await runCodexCommand(
|
||||
resolveCodexCommand(environment),
|
||||
["login", "status"],
|
||||
environment,
|
||||
undefined,
|
||||
undefined,
|
||||
{ cwd: NEUTRAL_CODEX_CWD },
|
||||
);
|
||||
for (const diagnostic of [native.stdout, native.stderr]) {
|
||||
if (diagnostic.trim())
|
||||
errorOutput.write(`${diagnosticLines(diagnostic.trimEnd())}\n`);
|
||||
}
|
||||
return native.exitCode ?? 2;
|
||||
});
|
||||
if (
|
||||
authentication.method === "api_key" &&
|
||||
(exitCode === 0 || exitCode === 1)
|
||||
) {
|
||||
exitCode = 0;
|
||||
errorOutput.write(
|
||||
`Effective scan authentication: API key from ${authentication.source}.\n`,
|
||||
);
|
||||
errorOutput.write(
|
||||
`To use a ChatGPT sign-in, ${formatEnvironmentVariableRemovalGuidance(["OPENAI_API_KEY", "CODEX_API_KEY"])}.\n`,
|
||||
);
|
||||
}
|
||||
if (structured)
|
||||
return {
|
||||
authenticated: exitCode === 0,
|
||||
...(authentication.method === "api_key"
|
||||
? {
|
||||
method: authentication.method,
|
||||
source: authentication.source,
|
||||
}
|
||||
: { method: "stored_credentials" as const }),
|
||||
};
|
||||
},
|
||||
}),
|
||||
)
|
||||
.command("logout", {
|
||||
description: "Remove the stored sign-in.",
|
||||
description: "Remove the stored Codex Security sign-in.",
|
||||
hint: "Check the effective account with codex-security login status. Scans can still use an API key configured in your environment.",
|
||||
destructive: true,
|
||||
async run() {
|
||||
const credentialHome = await prepareCodexSecurityCredentialHome(
|
||||
dependencies.environment,
|
||||
);
|
||||
const environment = {
|
||||
...dependencies.environment,
|
||||
CODEX_HOME: credentialHome,
|
||||
};
|
||||
exitCode = await withCredentialHomeLock(credentialHome, () =>
|
||||
exitCode = await withLoginEnvironment((environment) =>
|
||||
logoutCredentialHome(
|
||||
credentialHome,
|
||||
environment.CODEX_HOME,
|
||||
scanCodexHome(dependencies.environment),
|
||||
(store) =>
|
||||
dependencies.runCodex(
|
||||
@@ -7697,7 +7745,7 @@ export async function main(
|
||||
})
|
||||
.command("init", {
|
||||
description: "Create a starter project configuration.",
|
||||
hint: "Existing files are never overwritten.",
|
||||
hint: "Use the generated file with scan . -c FILE --dry-run. Existing files are never overwritten.",
|
||||
destructive: true,
|
||||
args: z.object({
|
||||
file: z
|
||||
@@ -7707,21 +7755,30 @@ export async function main(
|
||||
.describe("YAML or JSON destination (default: codex-security.yaml)."),
|
||||
}),
|
||||
output: z.object({ path: z.string() }).optional(),
|
||||
async run({ args }) {
|
||||
async run({ args, format }) {
|
||||
let preview: string | undefined;
|
||||
try {
|
||||
const directory = dependencies.currentDirectory();
|
||||
const path = resolveCliPath(
|
||||
directory,
|
||||
args.file ?? "codex-security.yaml",
|
||||
);
|
||||
preview = `${PREVIEW_LABEL}: ${projectPreviewCommand(directory, path)}`;
|
||||
await writeFile(path, projectConfigStarter(path, directory), {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
if (useDefaultOutput(format)) {
|
||||
if (output.isTTY)
|
||||
renderedOutput = `Created ${escapeTerminalText(path)}\n${preview}\n`;
|
||||
else errorOutput.write(`${preview}\n`);
|
||||
}
|
||||
return { path };
|
||||
} catch (error) {
|
||||
exitCode = 2;
|
||||
errorOutput.write(`codex-security: ${diagnosticLines(error)}\n`);
|
||||
if ((error as NodeJS.ErrnoException).code === "EEXIST" && preview)
|
||||
errorOutput.write(`${preview}\n`);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
@@ -7817,7 +7874,7 @@ export async function main(
|
||||
},
|
||||
},
|
||||
output: infoOutput,
|
||||
async run({ options }) {
|
||||
async run({ options, format }) {
|
||||
const directory = dependencies.currentDirectory();
|
||||
const project = await selectedProjectConfig(
|
||||
options.config,
|
||||
@@ -7840,23 +7897,50 @@ export async function main(
|
||||
),
|
||||
)
|
||||
: undefined;
|
||||
const model = scanModelConfiguration(codex);
|
||||
const sources = configurationSources(resolved.sources, deep?.sources);
|
||||
const nextStep = projectPreviewCommand(directory, project?.path);
|
||||
const bundledPluginAvailable = Boolean(
|
||||
await bundledPluginRoot().catch(() => undefined),
|
||||
);
|
||||
if (output.isTTY && useDefaultOutput(format)) {
|
||||
const overrides = Object.entries(sources)
|
||||
.filter(([, source]) => source !== "default")
|
||||
.map(([key, source]) => `${key} (${source})`);
|
||||
const { mode, auth, target, maxCostUsd } = resolved.options;
|
||||
renderedOutput =
|
||||
[
|
||||
`${PREVIEW_LABEL}: ${nextStep}`,
|
||||
`Configuration: ${project?.path ?? "defaults"}`,
|
||||
`Scope: ${typeof target === "string" ? target : JSON.stringify(target)}`,
|
||||
`Scan: ${mode} · ${model.model} (${model.reasoningEffort}) · auth ${auth}`,
|
||||
...(maxCostUsd === undefined
|
||||
? []
|
||||
: [`Cost limit: $${maxCostUsd}`]),
|
||||
`Bundled plugin: ${BUNDLED_PLUGIN_VERSION} (${bundledPluginAvailable ? "available" : "missing"})`,
|
||||
...(overrides.length
|
||||
? [`Overrides: ${overrides.join(", ")}`]
|
||||
: []),
|
||||
]
|
||||
.map((line) => escapeTerminalText(line))
|
||||
.join("\n") + "\n";
|
||||
}
|
||||
return {
|
||||
sdkVersion: VERSION,
|
||||
bundledPluginVersion: BUNDLED_PLUGIN_VERSION,
|
||||
bundledPluginAvailable,
|
||||
scanMcp: false as const,
|
||||
cancellationNote:
|
||||
"Scans are CLI-only because the MCP transport cannot cancel active commands.",
|
||||
cliVersion: VERSION,
|
||||
codexVersion: CODEX_EXECUTABLE_VERSION,
|
||||
codexSdkVersion: CODEX_SDK_VERSION,
|
||||
...scanModelConfiguration(codex),
|
||||
nextStep: project
|
||||
? "Run codex-security scan . -c FILE --dry-run, replacing FILE with the project configuration you selected."
|
||||
: "codex-security scan . --dry-run",
|
||||
...model,
|
||||
nextStep,
|
||||
configuration: {
|
||||
...(project?.path === undefined ? {} : { path: project.path }),
|
||||
settings: { ...resolved.options, ...deep?.settings },
|
||||
sources: configurationSources(resolved.sources, deep?.sources),
|
||||
sources,
|
||||
},
|
||||
};
|
||||
},
|
||||
@@ -7910,7 +7994,8 @@ export async function main(
|
||||
const structuredOutput = frameworkFlags.formats.some(isJsonFormat);
|
||||
if (
|
||||
structuredOutput &&
|
||||
["validate", "login", "logout"].includes(command) &&
|
||||
(["validate", "logout"].includes(command) ||
|
||||
(command === "login" && following !== "status")) &&
|
||||
!argv.includes("--schema")
|
||||
) {
|
||||
return `${command} does not support noninteractive JSON output; run it without --json, --format json, or --format jsonl.`;
|
||||
@@ -8028,6 +8113,13 @@ export async function main(
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
if (
|
||||
command === "login" &&
|
||||
positionals.length > 0 &&
|
||||
(following !== "status" || positionals.length !== 1)
|
||||
) {
|
||||
return "Use login to sign in or login status to inspect authentication.";
|
||||
}
|
||||
if (
|
||||
subcommand === "match" &&
|
||||
!argv.some((value) =>
|
||||
@@ -10814,6 +10906,20 @@ function diagnosticLines(value: unknown): string {
|
||||
return errorMessage(value).split("\n").map(diagnosticValue).join("\n");
|
||||
}
|
||||
|
||||
const PREVIEW_LABEL =
|
||||
process.platform === "win32" ? "Next (PowerShell)" : "Next";
|
||||
|
||||
function projectPreviewCommand(directory: string, path?: string): string {
|
||||
if (path === undefined) return "codex-security scan . --dry-run";
|
||||
const local = relative(directory, path);
|
||||
let file = local.split(/[\\/]/u)[0] === ".." ? path : local;
|
||||
if (file.startsWith("-") || file.startsWith("~")) file = `./${file}`;
|
||||
// Keep terminal controls out of suggested commands and quote shell syntax.
|
||||
if (escapeTerminalText(file) !== file)
|
||||
return "codex-security scan . -c FILE --dry-run (replace FILE with the selected path)";
|
||||
return `codex-security scan . -c ${quoteCliPath(file)} --dry-run`;
|
||||
}
|
||||
|
||||
function diagnosticValue(value: unknown): string {
|
||||
return errorMessage(value).replaceAll(
|
||||
/[\u0000-\u001F\u007F-\u009F\u2028\u2029]/gu,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { isUtf8 } from "node:buffer";
|
||||
import { existsSync } from "node:fs";
|
||||
import { readFile, realpath } from "node:fs/promises";
|
||||
import {
|
||||
basename,
|
||||
@@ -207,11 +208,14 @@ export function projectConfigStarter(
|
||||
: `${relativeSchema.startsWith(".") ? "" : "./"}${encodeURI(
|
||||
relativeSchema.split(sep).join("/"),
|
||||
).replace(/[#?]/gu, encodeURIComponent)}`;
|
||||
const hasSchema = existsSync(schemaPath);
|
||||
if (projectConfigExtension(path) === ".json")
|
||||
return `${JSON.stringify({ $schema: schema }, null, 2)}\n`;
|
||||
return `${JSON.stringify(hasSchema ? { $schema: schema } : {}, null, 2)}\n`;
|
||||
return [
|
||||
"# This file is trusted like CLI options. Keep it outside untrusted inputs.",
|
||||
`$schema: ${schema}`,
|
||||
...(hasSchema
|
||||
? [`$schema: ${schema}`]
|
||||
: ["# Replace the empty mapping below when enabling settings.", "{}"]),
|
||||
"",
|
||||
"# Uncomment the settings you want to override. Defaults remain unpinned.",
|
||||
`# auth: ${DEFAULT_SCAN_AUTH}`,
|
||||
|
||||
@@ -100,6 +100,76 @@ async function createCredentialHome() {
|
||||
}
|
||||
|
||||
describe("CLI authentication", () => {
|
||||
test("login status JSON uses an isolated home and returns the effective authentication source", async () => {
|
||||
const { stdout, runCli } = createCliTest(main, { stderr: true });
|
||||
const environment = {
|
||||
HOME: stateDirectory,
|
||||
USERPROFILE: stateDirectory,
|
||||
CODEX_API_KEY: "synthetic-fixture-key",
|
||||
};
|
||||
expect(
|
||||
await runCli(
|
||||
["login", "status", "--json"],
|
||||
dependencies({ environment }),
|
||||
),
|
||||
).toBe(0);
|
||||
expect(JSON.parse(stdout.text())).toEqual({
|
||||
authenticated: true,
|
||||
method: "api_key",
|
||||
source: "CODEX_API_KEY",
|
||||
});
|
||||
});
|
||||
|
||||
test("structured login status ignores checkout-specific native configuration", async () => {
|
||||
const home = await createCredentialHome();
|
||||
expect(spawnSync("git", ["init", "--quiet", skillDirectory]).status).toBe(
|
||||
0,
|
||||
);
|
||||
await mkdir(join(skillDirectory, ".codex"));
|
||||
await writeFile(
|
||||
join(skillDirectory, ".codex", "config.toml"),
|
||||
"broken = [",
|
||||
);
|
||||
await writeFile(
|
||||
join(home, "config.toml"),
|
||||
`cli_auth_credentials_store = "file"\n[projects.${JSON.stringify(skillDirectory)}]\ntrust_level = "trusted"\n`,
|
||||
{ mode: 0o600 },
|
||||
);
|
||||
await writeFile(
|
||||
join(home, "auth.json"),
|
||||
JSON.stringify({ OPENAI_API_KEY: "synthetic-key" }),
|
||||
{ mode: 0o600 },
|
||||
);
|
||||
|
||||
const status = spawnSync(
|
||||
process.execPath,
|
||||
[join(import.meta.dir, "../src/cli.ts"), "login", "status", "--json"],
|
||||
{
|
||||
cwd: skillDirectory,
|
||||
encoding: "utf8",
|
||||
env: {
|
||||
PATH: process.env["PATH"],
|
||||
HOME: stateDirectory,
|
||||
USERPROFILE: stateDirectory,
|
||||
CODEX_SECURITY_STATE_DIR: stateDirectory,
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(status.status, status.stderr).toBe(0);
|
||||
expect(JSON.parse(status.stdout)).toEqual({
|
||||
authenticated: true,
|
||||
method: "stored_credentials",
|
||||
});
|
||||
});
|
||||
|
||||
test("an unknown login action does not start a sign-in", async () => {
|
||||
const { stderr, runCli } = createCliTest(main, { stderr: true });
|
||||
const deps = dependencies();
|
||||
deps.runCodex = throwing("must not start a sign-in");
|
||||
expect(await runCli(["login", "stats"], deps)).toBe(2);
|
||||
expect(stderr.text()).toContain("login status");
|
||||
});
|
||||
|
||||
test("delegates login and logout without overriding managed credential storage", async () => {
|
||||
const cases = [
|
||||
["login"],
|
||||
|
||||
@@ -88,13 +88,13 @@ async function bulkInventory(
|
||||
}
|
||||
|
||||
test.each([
|
||||
[undefined, "./node_modules"],
|
||||
["starter.json", "./node_modules"],
|
||||
["settings/starter.yaml", "../node_modules"],
|
||||
["settings/starter.json", "../node_modules"],
|
||||
undefined,
|
||||
"starter.json",
|
||||
"settings/starter.yaml",
|
||||
"settings/starter.json",
|
||||
])(
|
||||
"init writes a valid unpinned starter and refuses overwrites: %s",
|
||||
async (file, modules) => {
|
||||
async (file) => {
|
||||
const input = await fixture({});
|
||||
const args = ["init", ...(file === undefined ? [] : [file]), "--json"];
|
||||
const output = captureCli(main, "stdout");
|
||||
@@ -106,15 +106,28 @@ test.each([
|
||||
const path = join(input.root, file ?? "codex-security.yaml");
|
||||
expect(JSON.parse(output.text())).toEqual({ path });
|
||||
const selected = await readProjectConfig(path);
|
||||
expect(selected.input).toEqual({
|
||||
$schema: `${modules}/@openai/codex-security/schemas/project-config.schema.json`,
|
||||
});
|
||||
expect(selected.input).toEqual({});
|
||||
const contents = await readFile(path, "utf8");
|
||||
expect(await runCapturedCli(main, args, deps)).toBe(2);
|
||||
expect(await readFile(path, "utf8")).toBe(contents);
|
||||
},
|
||||
);
|
||||
|
||||
test("init shows how to select a custom config and info reports the same preview", async () => {
|
||||
const input = await fixture({});
|
||||
const file = "config for review.yaml";
|
||||
const deps = dependencies({ currentDirectory: input.root });
|
||||
const init = captureCli(main, "stdout", true);
|
||||
expect(await init.run(["init", file], deps)).toBe(0);
|
||||
const preview = "codex-security scan . -c 'config for review.yaml' --dry-run";
|
||||
expect(init.text()).toContain(preview);
|
||||
const info = captureCli(main, "stdout", true);
|
||||
expect(await info.run(["info", "-c", file], deps)).toBe(0);
|
||||
expect(info.text()).toContain(preview);
|
||||
expect(info.text()).toContain("Scope: repository");
|
||||
expect(info.text()).not.toContain("codex.reasoning");
|
||||
});
|
||||
|
||||
test.each(["yaml", "json"])(
|
||||
"init preserves URI-sensitive directory names in the %s schema reference",
|
||||
async (extension) => {
|
||||
@@ -187,7 +200,7 @@ test("info resolves a config and its sources without a target, prompt reads, or
|
||||
expect(stdout.text()).not.toContain("synthetic-private-value");
|
||||
expect(JSON.parse(stdout.text())).toMatchObject({
|
||||
model: "gpt-5.6-terra",
|
||||
nextStep: expect.stringContaining("scan . -c FILE --dry-run"),
|
||||
nextStep: "codex-security scan . -c scan.json --dry-run",
|
||||
configuration: {
|
||||
path: input.config,
|
||||
settings: {
|
||||
|
||||
@@ -3208,7 +3208,6 @@ describe("CLI", () => {
|
||||
for (const [command, ...args] of [
|
||||
["validate", "finding", "--json"],
|
||||
["login", "--format", "json"],
|
||||
["login", "status", "--format=jsonl"],
|
||||
["logout", "--format", "jsonl"],
|
||||
["logout", "--format=json"],
|
||||
] as const) {
|
||||
|
||||
Reference in New Issue
Block a user