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
refactor(github): share connection and error handling for finding imports (#2204)
Michael D'Angelo7d2f3b7aebb8
diff --git a/sdk/typescript/src/github-advisories.ts b/sdk/typescript/src/github-advisories.tsindex d7456e6e5..f2fbc5d6d 100644--- a/sdk/typescript/src/github-advisories.ts+++ b/sdk/typescript/src/github-advisories.ts@@ -3,9 +3,15 @@ import {CANONICAL_GHSA_ID,githubRepositoryParts,} from "./github-identifiers.js";-import { CodexSecurityError, errorMessage } from "./errors.js";+import { CodexSecurityError } from "./errors.js";import { requireExternalImports } from "./external-imports-feature.js";-import { createAuthenticatedGitHub } from "./github.js";+import {+ githubImportHost,+ githubImportClient,+ githubImportError,+ type GitHubImportConnectionOptions,+ type GitHubImportDependencies,+} from "./github.js";export const GITHUB_ADVISORY_STATES = ["published",@@ -14,7 +20,7 @@ export const GITHUB_ADVISORY_STATES = ["closed",] as const;-export interface GitHubAdvisoryImportOptions {+export interface GitHubAdvisoryImportOptions extends GitHubImportConnectionOptions {/** Source repository, or the selected target for explicit global advisory IDs. */repository: string;/** Exact GHSA IDs. Required for the global advisory API. */@@ -23,11 +29,6 @@ export interface GitHubAdvisoryImportOptions {source?: "repository" | "global";/** Repository list state (default: published). Exact IDs ignore state. */state?: (typeof GITHUB_ADVISORY_STATES)[number];- /** Defaults to GH_HOST or github.com. */- githubHost?: string;- /** Omit to use the authenticated GitHub CLI. */- githubToken?: string;- signal?: AbortSignal;}type RepositoryAdvisory = Awaited<ReturnType<typeof fetchRepositoryAdvisory>>;@@ -44,16 +45,10 @@ export interface ImportedGitHubAdvisory {advisory: RepositoryAdvisory | GlobalAdvisory;}-interface GitHubAdvisoryImportDependencies {- environment?: NodeJS.ProcessEnv;- currentDirectory?: string;- createGitHub?: (host: string, signal?: AbortSignal) => Promise<Octokit>;-}-/** Read repository disclosures or explicitly selected public GHSA records. */export async function importGitHubAdvisories(options: GitHubAdvisoryImportOptions,- dependencies: GitHubAdvisoryImportDependencies = {},+ dependencies: GitHubImportDependencies = {},): Promise<ImportedGitHubAdvisory[]> {options.signal?.throwIfAborted();const environment = dependencies.environment ?? process.env;@@ -93,20 +88,15 @@ export async function importGitHubAdvisories(throw new CodexSecurityError("--github-state only filters repository lists; omit it when selecting exact GHSA IDs.",);- const host =- options.githubHost?.trim() ??- (environment["GH_HOST"]?.trim() || "github.com");- if (!host) throw new CodexSecurityError("GitHub host must not be empty.");+ const host = githubImportHost(options.githubHost, environment);try {- const github = dependencies.createGitHub- ? await dependencies.createGitHub(host, options.signal)- : await createAuthenticatedGitHub(host, {- token: options.githubToken,- environment,- currentDirectory: dependencies.currentDirectory,- signal: options.signal,- });+ const github = await githubImportClient(+ host,+ options,+ dependencies,+ environment,+ );const advisories: (RepositoryAdvisory | GlobalAdvisory)[] = [];if (ids.length > 0) {for (const id of ids) {@@ -165,29 +155,13 @@ export async function importGitHubAdvisories(advisory,}));} catch (error) {- options.signal?.throwIfAborted();- if (error instanceof CodexSecurityError) throw error;- const status =- typeof error === "object" && error !== null && "status" in error- ? error.status- : undefined;- if (status === 401)- throw new CodexSecurityError("GitHub authentication failed.");- if (status === 403)- throw new CodexSecurityError(+ throw githubImportError(error, options.signal, {+ operation: "security advisory",+ denied:"GitHub denied security advisory access. Check repository advisory permissions and API rate limits.",- );- if (status === 404)- throw new CodexSecurityError(+ notFound:"GitHub repository or security advisory was not found or is not accessible.",- );- if (status === 429)- throw new CodexSecurityError(- "GitHub request was rate limited. Wait and retry.",- );- throw new CodexSecurityError(- `GitHub security advisory request failed${typeof status === "number" ? ` (HTTP ${status})` : ""}: ${errorMessage(error)}`,- );+ });}}diff --git a/sdk/typescript/src/github.ts b/sdk/typescript/src/github.tsindex 957e4ab16..53a5630d6 100644--- a/sdk/typescript/src/github.ts+++ b/sdk/typescript/src/github.ts@@ -17,7 +17,15 @@ export const GITHUB_ALERT_STATES = ["all",] as const;-export interface GitHubCodeScanningImportOptions {+export interface GitHubImportConnectionOptions {+ /** Defaults to GH_HOST or github.com. */+ githubHost?: string;+ /** Omit to use the authenticated GitHub CLI, including its token environment. */+ githubToken?: string;+ signal?: AbortSignal;+}++export interface GitHubCodeScanningImportOptions extends GitHubImportConnectionOptions {/** GitHub repository in OWNER/REPO form. */repository: string;/** Exact alert numbers, regardless of state. Omit to list matching alerts. */@@ -26,11 +34,6 @@ export interface GitHubCodeScanningImportOptions {state?: (typeof GITHUB_ALERT_STATES)[number];/** Git reference to inspect; omitted lists the default branch. */ref?: string;- /** Defaults to GH_HOST or github.com. */- githubHost?: string;- /** Omit to use the authenticated GitHub CLI, including its token environment. */- githubToken?: string;- signal?: AbortSignal;}export interface ImportedGitHubCodeScanningAlert {@@ -42,7 +45,7 @@ export interface ImportedGitHubCodeScanningAlert {alert: GitHubAlert;}-interface GitHubImportDependencies {+export interface GitHubImportDependencies {environment?: NodeJS.ProcessEnv;currentDirectory?: string;createGitHub?: (host: string, signal?: AbortSignal) => Promise<Octokit>;@@ -96,6 +99,61 @@ export async function createAuthenticatedGitHub(});}+export function githubImportHost(+ githubHost: string | undefined,+ environment: NodeJS.ProcessEnv,+): string {+ const host =+ githubHost?.trim() ?? (environment["GH_HOST"]?.trim() || "github.com");+ if (!host) throw new CodexSecurityError("GitHub host must not be empty.");+ return host;+}++export function githubImportClient(+ host: string,+ options: GitHubImportConnectionOptions,+ dependencies: GitHubImportDependencies,+ environment: NodeJS.ProcessEnv,+): Promise<Octokit> {+ return dependencies.createGitHub+ ? dependencies.createGitHub(host, options.signal)+ : createAuthenticatedGitHub(host, {+ token: options.githubToken,+ environment,+ currentDirectory: dependencies.currentDirectory,+ signal: options.signal,+ });+}++export function githubImportError(+ error: unknown,+ signal: AbortSignal | undefined,+ messages: { operation: string; denied: string; notFound: string },+): CodexSecurityError {+ signal?.throwIfAborted();+ if (error instanceof CodexSecurityError) return error;+ const status =+ typeof error === "object" && error !== null && "status" in error+ ? error.status+ : undefined;+ switch (status) {+ case 401:+ return new CodexSecurityError("GitHub authentication failed.");+ case 403:+ return new CodexSecurityError(messages.denied);+ case 404:+ return new CodexSecurityError(messages.notFound);+ case 429:+ return new CodexSecurityError(+ "GitHub request was rate limited. Wait and retry.",+ );+ default:+ return new CodexSecurityError(+ `GitHub ${messages.operation} request failed${typeof status === "number" ? ` (HTTP ${status})` : ""}: ${errorMessage(error)}`,+ );+ }+}+export async function importGitHubCodeScanningAlerts(options: GitHubCodeScanningImportOptions,dependencies: GitHubImportDependencies = {},@@ -126,22 +184,15 @@ export async function importGitHubCodeScanningAlerts(throw new CodexSecurityError("GitHub reference must not be empty.");}const environment = dependencies.environment ?? process.env;- const host =- options.githubHost?.trim() ??- (environment["GH_HOST"]?.trim() || "github.com");- if (host.length === 0) {- throw new CodexSecurityError("GitHub host must not be empty.");- }+ const host = githubImportHost(options.githubHost, environment);try {- const github = dependencies.createGitHub- ? await dependencies.createGitHub(host, options.signal)- : await createAuthenticatedGitHub(host, {- token: options.githubToken,- environment,- currentDirectory: dependencies.currentDirectory,- signal: options.signal,- });+ const github = await githubImportClient(+ host,+ options,+ dependencies,+ environment,+ );const selected = new Map<number, GitHubAlert["most_recent_instance"]>();if (numbers.length === 0 || ref !== undefined) {let page = 1;@@ -204,31 +255,13 @@ export async function importGitHubCodeScanningAlerts(}return alerts;} catch (error) {- options.signal?.throwIfAborted();- if (error instanceof CodexSecurityError) throw error;- const status =- typeof error === "object" && error !== null && "status" in error- ? error.status- : undefined;- if (status === 401)- throw new CodexSecurityError("GitHub authentication failed.");- if (status === 403) {- throw new CodexSecurityError(+ throw githubImportError(error, options.signal, {+ operation: "code scanning",+ denied:"GitHub denied code scanning access. Check repository permissions, code scanning availability, and API rate limits.",- );- }- if (status === 404) {- throw new CodexSecurityError(+ notFound:"GitHub repository or code scanning alert was not found or is not accessible.",- );- }- if (status === 429)- throw new CodexSecurityError(- "GitHub request was rate limited. Wait and retry.",- );- throw new CodexSecurityError(- `GitHub code scanning request failed${typeof status === "number" ? ` (HTTP ${status})` : ""}: ${errorMessage(error)}`,- );+ });}}diff --git a/sdk/typescript/tests-ts/github-advisories.test.ts b/sdk/typescript/tests-ts/github-advisories.test.tsindex 1fb8894c8..938330fa7 100644--- a/sdk/typescript/tests-ts/github-advisories.test.ts+++ b/sdk/typescript/tests-ts/github-advisories.test.ts@@ -47,6 +47,24 @@ test.each(["repository", "global"] as const)(},);+test.each([+ [403, "GitHub denied security advisory access"],+ [404, "GitHub repository or security advisory was not found"],+] as const)(+ "reports advisory-specific guidance for HTTP %i",+ async (status, guidance) => {+ await expect(+ importGitHubAdvisories(+ { repository: "example/project" },+ {+ environment: enabledEnvironment,+ createGitHub: async () => client(() => Response.json({}, { status })),+ },+ ),+ ).rejects.toThrow(guidance);+ },+);+test("concurrent advisory imports keep opt-in scoped to each call", async () => {const advisory = importedAdvisory();const createGitHub = mock(async () =>