OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
fix(publish): select scans and reuse credentials (#640)
Kyle Brown37889531cc94
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex a2509e6f4..271ee9b3d 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -739,7 +739,9 @@ npx @openai/codex-security publish scan --to cloud --dry-run --json```The picker shows each scan's repository, finding count, age, and scan ID.-Choose scans, then select **Done**. No scans are selected automatically.+Press <kbd>Space</kbd> to select or deselect scans, then press+<kbd>Enter</kbd> to submit. At least one scan is required, and no scans are+selected automatically.For scripts, repeat `--scan` with saved scan IDs or unique ID prefixes (atleast eight characters):@@ -753,7 +755,8 @@ npx @openai/codex-security publish scan \Use `scans list --json` to find IDs for the current repository. `--scan latest`selects its latest completed scan. The CLI resolves IDs through saved history,processes each selected scan once, and checks that its sealed artifacts match-the selected ID. The artifacts must still be available locally.+the selected ID. Picker selections use the order shown; repeated `--scan`+selections use argument order. The artifacts must still be available locally.`--dry-run` validates the scans and prints their findings without uploading orrequiring a login. Remove `--dry-run` to upload. Live uploads require ChatGPTdiff --git a/sdk/typescript/src/bulk-scan-discovery.ts b/sdk/typescript/src/bulk-scan-discovery.tsindex 23a7b8722..cd86a2e34 100644--- a/sdk/typescript/src/bulk-scan-discovery.ts+++ b/sdk/typescript/src/bulk-scan-discovery.ts@@ -5,7 +5,7 @@ import { join, resolve } from "node:path";import { stdin } from "node:process";import { Writable } from "node:stream";import { promisify } from "node:util";-import { confirm, input, search } from "@inquirer/prompts";+import { checkbox, confirm, input, search, Separator } from "@inquirer/prompts";import { Octokit } from "@octokit/core";import Papa from "papaparse";import { expandHome } from "./runtime.js";@@ -71,6 +71,12 @@ export interface BulkScanPrompt {presentation?: { header?: string },signal?: AbortSignal,): Promise<Value>;+ checkbox<Value extends string>(+ question: string,+ options: readonly { label: string; value: Value; short?: string }[],+ presentation?: { header?: string; required?: boolean },+ signal?: AbortSignal,+ ): Promise<Value[]>;}export interface BulkScanDiscoveryDependencies {@@ -361,6 +367,24 @@ function createTerminalPrompt(output: PromptOutput): BulkScanPrompt {confirm({ message, default: defaultValue }, context(signal)),input: (message, defaultValue, signal) =>input({ message, default: defaultValue }, context(signal)),+ checkbox: (message, options, presentation, signal) =>+ checkbox(+ {+ message,+ choices: [+ ...(presentation?.header === undefined+ ? []+ : [new Separator(presentation.header)]),+ ...options.map(({ label, value, short }) => ({+ name: label,+ value,+ ...(short === undefined ? {} : { short }),+ })),+ ],+ required: presentation?.required,+ },+ context(signal),+ ),select: (message, options, presentation, signal) =>search({diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex f5c614e99..4d9cce33b 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -1057,7 +1057,8 @@ interface CliDependencies {) => Promise<string>;hasStoredChatGPTSignIn?: (signal?: AbortSignal) => Promise<boolean>;scanAuthenticationPrompt?: Pick<BulkScanPrompt, "isInteractive" | "select">;- publishPrompt?: Pick<BulkScanPrompt, "isInteractive" | "select">;+ publishPrompt?: Pick<BulkScanPrompt, "isInteractive" | "select"> &+ Partial<Pick<BulkScanPrompt, "checkbox">>;checkScanPublication?: typeof checkScanPublication;publishScan?: typeof publishScan;publishScanToCloud?: typeof publishScanToCloud;@@ -2321,28 +2322,22 @@ export async function main(};});if (options.to === "cloud") {- let remaining = choices;- while (true) {- controller.signal.throwIfAborted();- const selected = await prompt.select(- "Which completed scans would you like to publish?",- selectedScans.length === 0- ? remaining- : [- {- label: `Done (${selectedScans.length} selected)`,- value: "",- },- ...remaining,- ],- { header },- controller.signal,+ if (prompt.checkbox === undefined) {+ throw new CodexSecurityError(+ "Interactive scan selection is unavailable.",);- controller.signal.throwIfAborted();- if (selected === "") break;- selectedScans.push(scansById.get(selected)!);- remaining = remaining.filter(({ value }) => value !== selected);}+ controller.signal.throwIfAborted();+ const selected = await prompt.checkbox(+ "Which completed scans would you like to publish?",+ choices,+ { header, required: true },+ controller.signal,+ );+ controller.signal.throwIfAborted();+ selectedScans.push(+ ...selected.map((scanId) => scansById.get(scanId)!),+ );scanDir = selectedScans[0]!.scanDir;} else {scanDir = await prompt.select(diff --git a/sdk/typescript/src/cloud-publish.ts b/sdk/typescript/src/cloud-publish.tsindex 8e3e22a88..eddc7eb99 100644--- a/sdk/typescript/src/cloud-publish.ts+++ b/sdk/typescript/src/cloud-publish.ts@@ -17,7 +17,7 @@ import {const CLOUD_PUBLISH_URL ="https://chatgpt.com/backend-api/aardvark/cli/findings";const CHATGPT_LOGIN_REQUIRED =- 'Cloud publication requires ChatGPT credentials stored with cli_auth_credentials_store = "file". Automatic and keyring storage are not read because a stale auth.json may belong to another account. Configure file storage, sign in with ChatGPT again, then retry.';+ "Cloud publication requires a ChatGPT login already available to Codex Security. Run a scan or sign in with ChatGPT using Codex file credential storage, then retry.";const credentialsSchema = z.object({auth_mode: z.literal("chatgpt").optional(),@@ -149,6 +149,7 @@ async function readCloudCredentials(environment: NodeJS.ProcessEnv) {environment["CODEX_HOME"]?.trim() || "~/.codex",environment,);+ let requireFileStorage = true;const dedicatedHome = codexSecurityCredentialHome(environment);if (existsSync(dedicatedHome)) {if (!(await codexSecurityCredentialAllowsAmbientImport(dedicatedHome))) {@@ -156,23 +157,26 @@ async function readCloudCredentials(environment: NodeJS.ProcessEnv) {}if (await codexSecurityHasStoredFileCredentials(dedicatedHome)) {home = dedicatedHome;+ requireFileStorage = false;} else if (existsSync(join(dedicatedHome, "config.toml"))) {// Do not silently switch accounts when the dedicated login may be in a keyring.throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);}}- let credentialStorage: unknown;- try {- credentialStorage = parseToml(- await readFile(join(home, "config.toml"), "utf8"),- )["cli_auth_credentials_store"];- } catch {- throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);- }- // File presence is not proof that it is the active login: automatic or- // keyring storage can leave an auth.json from a different account.- if (credentialStorage !== "file") {- throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);+ if (requireFileStorage) {+ let credentialStorage: unknown;+ try {+ credentialStorage = parseToml(+ await readFile(join(home, "config.toml"), "utf8"),+ )["cli_auth_credentials_store"];+ } catch {+ throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);+ }+ // File presence is not proof that it is the active ambient login:+ // automatic or keyring storage can leave auth.json for another account.+ if (credentialStorage !== "file") {+ throw new AuthenticationRequiredError(CHATGPT_LOGIN_REQUIRED);+ }}try {const credentials = credentialsSchema.safeParse(diff --git a/sdk/typescript/tests-ts/bulk-scan-discovery.test.ts b/sdk/typescript/tests-ts/bulk-scan-discovery.test.tsindex 5aae6f7f6..cf4e1b26a 100644--- a/sdk/typescript/tests-ts/bulk-scan-discovery.test.ts+++ b/sdk/typescript/tests-ts/bulk-scan-discovery.test.ts@@ -71,6 +71,10 @@ class FakePrompt implements BulkScanPrompt {return (options.find((option) => option.value === value) ?? options[0]!).value;}++ public async checkbox<Value extends string>(): Promise<Value[]> {+ throw new Error("unexpected checkbox prompt");+ }}interface Repository {diff --git a/sdk/typescript/tests-ts/cli-cloud-publish.test.ts b/sdk/typescript/tests-ts/cli-cloud-publish.test.tsindex aac3928dd..be01e8732 100644--- a/sdk/typescript/tests-ts/cli-cloud-publish.test.ts+++ b/sdk/typescript/tests-ts/cli-cloud-publish.test.ts@@ -173,26 +173,38 @@ describe("publish scan to Cloud", () => {expect(stderr.text()).toContain("Use --scan or scan directory inputs");});- test("selects several saved scans by ID and stops at Done without selecting the rest", async () => {+ test("publishes checked scans in display order from one multi-select prompt", async () => {const { scans, deps } = await savedScansFixture();- const picks = [scans[1]!.scanId, scans[0]!.scanId, ""];+ const picks = scans.slice(0, 2).map(({ scanId }) => scanId);let selections = 0;deps.publishPrompt = {isInteractive: () => true,- select: async (_question, choices, presentation, signal) => {+ select: async () => {+ throw new Error("unexpected single-select prompt");+ },+ checkbox: async <Value extends string>(+ _question: string,+ choices: readonly { label: string; value: Value }[],+ presentation?: { header?: string; required?: boolean },+ signal?: AbortSignal,+ ): Promise<Value[]> => {+ selections++;expect(signal).toBeInstanceOf(AbortSignal);expect(presentation?.header).toContain("SCAN ID");- expect(choices.some(({ value }) => value === "")).toBe(selections > 0);+ expect(presentation?.required).toBe(true);+ expect(choices.some(({ value }) => value === "")).toBe(false);expect(choices.some(({ label }) => label.includes(scans[0]!.scanDir)),).toBe(false);- const pick = picks[selections++]!;- return choices.find(({ value }) => value === pick)!.value;+ expect(choices.map(({ value }) => String(value))).toEqual(+ scans.map(({ scanId }) => scanId),+ );+ return choices.slice(0, 2).map(({ value }) => value);},};const calls: string[] = [];deps.publishScanToCloud = async (_directory, options) => {- expect(selections).toBe(3);+ expect(selections).toBe(1);calls.push(options!.expectedScanId!);return { ...receipt, scanId: options!.expectedScanId! };};@@ -205,7 +217,7 @@ describe("publish scan to Cloud", () => {deps,),).toBe(0);- expect(calls).toEqual(picks.slice(0, 2));+ expect(calls).toEqual(picks);expect(JSON.parse(stdout.text()).results.map((result: { scanId: string }) => result.scanId,@@ -220,15 +232,15 @@ describe("publish scan to Cloud", () => {signals.add(signal, listener);deps.removeSignalListener = (signal, listener) =>signals.remove(signal, listener);- let selections = 0;deps.publishPrompt = {isInteractive: () => true,- select: async (_question, choices, _presentation, signal) => {- if (selections++ > 0) {- signals.emit("SIGINT");- signal!.throwIfAborted();- }- return choices[0]!.value;+ select: async () => {+ throw new Error("unexpected single-select prompt");+ },+ checkbox: async (_question, _choices, _presentation, signal) => {+ signals.emit("SIGINT");+ signal!.throwIfAborted();+ return [];},};let uploads = 0;@@ -770,16 +782,15 @@ describe("publish scan to Cloud", () => {let selections = 0;deps.publishPrompt = {isInteractive: () => true,- select: async (_question, choices) => {+ select: async () => {+ throw new Error("unexpected single-select prompt");+ },+ checkbox: async (_question, choices, presentation) => {selections++;const directories: string[] = choices.map(({ value }) => value);- if (selections === 1) {- expect(directories).toEqual(["scan-1"]);- return choices[0]!.value;- }- expect(directories).toEqual([""]);- expect(choices[0]!.label).toBe("Done (1 selected)");- return choices[0]!.value;+ expect(directories).toEqual(["scan-1"]);+ expect(presentation?.required).toBe(true);+ return [choices[0]!.value];},};deps.publishScanToCloud = async (directory, options) => {@@ -796,7 +807,7 @@ describe("publish scan to Cloud", () => {deps,),).toBe(0);- expect(selections).toBe(2);+ expect(selections).toBe(1);expect(JSON.parse(stdout.text())).toEqual(receipt);} finally {await rm(root, { recursive: true, force: true });diff --git a/sdk/typescript/tests-ts/cloud-publish.test.ts b/sdk/typescript/tests-ts/cloud-publish.test.tsindex e81bfb6f4..35290fd84 100644--- a/sdk/typescript/tests-ts/cloud-publish.test.ts+++ b/sdk/typescript/tests-ts/cloud-publish.test.ts@@ -265,7 +265,7 @@ describe("Cloud publication", () => {expect(requestedUrl).toBe(publishUrl);});- test("prefers the dedicated file login and honors an explicit logout", async () => {+ test("reuses the dedicated Codex Security login and honors an explicit logout", async () => {const { scan, environment } = await fixture();const home = codexSecurityCredentialHome(environment);await mkdir(home, { recursive: true, mode: 0o700 });@@ -277,6 +277,10 @@ describe("Cloud publication", () => {}),{ mode: 0o600 },);+ await writeFile(+ join(home, "config.toml"),+ 'cli_auth_credentials_store = "auto"\n',+ );let requests = 0;const send = async (_url: string, options: RequestInit) => {requests++;@@ -285,19 +289,11 @@ describe("Cloud publication", () => {);return Response.json(receipt);};- await expect(- publishScanToCloud(scan, { environment, fetch: send }),- ).rejects.toThrow('cli_auth_credentials_store = "file"');- expect(requests).toBe(0);- await writeFile(- join(home, "config.toml"),- 'cli_auth_credentials_store = "file"\n',- );await publishScanToCloud(scan, { environment, fetch: send });await setCodexSecurityCredentialLogout(home, true);await expect(publishScanToCloud(scan, { environment, fetch: send }),- ).rejects.toThrow('cli_auth_credentials_store = "file"');+ ).rejects.toThrow("ChatGPT login already available to Codex Security");expect(requests).toBe(1);});@@ -340,7 +336,7 @@ describe("Cloud publication", () => {}await expect(publishScanToCloud(scan, { environment, fetch: send }),- ).rejects.toThrow('cli_auth_credentials_store = "file"');+ ).rejects.toThrow("ChatGPT login already available to Codex Security");}expect(requests).toBe(0);});@@ -363,16 +359,16 @@ describe("Cloud publication", () => {});await expect(publishScanToCloud(scan, { environment, fetch: send }),- ).rejects.toThrow('cli_auth_credentials_store = "file"');+ ).rejects.toThrow("ChatGPT login already available to Codex Security");}await writeFile(join(home, "auth.json"), "malformed-synthetic-secret");await expect(publishScanToCloud(scan, { environment, fetch: send }),- ).rejects.toThrow('cli_auth_credentials_store = "file"');+ ).rejects.toThrow("ChatGPT login already available to Codex Security");await rm(join(home, "auth.json"));await expect(publishScanToCloud(scan, { environment, fetch: send }),- ).rejects.toThrow('cli_auth_credentials_store = "file"');+ ).rejects.toThrow("ChatGPT login already available to Codex Security");expect(requests).toBe(0);});@@ -394,9 +390,8 @@ describe("Cloud publication", () => {() => undefined,(failure: unknown) => failure,);- expect(String(error)).toContain('cli_auth_credentials_store = "file"');expect(String(error)).toContain(- "a stale auth.json may belong to another account",+ "ChatGPT login already available to Codex Security",);}expect(requests).toBe(0);