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
feat(cli): create GitLab merge requests for verified patches (#814)
Kyle Brown746fb84a15c9
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 6cbee5318..f532d650c 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -1128,8 +1128,8 @@ assessment skill once on the completed patch. The assessment is advisory anddoes not change the patch or its merge state. Human-readable commands print thereport after the patch results; saved-finding JSON output returns it as`patchRisk.report` in the same result object. When combined with `--create-pr`,-the draft pull request body includes only the concise Markdown summary from the-assessment; the validated JSON remains in the command result.+the draft pull request or merge request body includes only the concise Markdown+summary from the assessment; the validated JSON remains in the command result.```bashnpx @openai/codex-security validate "Possible SQL injection" --effort high@@ -1151,11 +1151,25 @@ to select findings and add patch instructions. Results include a `patches`entry per finding with status `verified`, `no_change`, `blocked`, or `failed`.Verified and already-fixed findings no longer fail `--fail-on-severity`.-`--create-pr` commits generated patch files and opens a draft PR with `gh`.-Supplied-issue pull requests require a clean working tree before patching so+`--create-pr` commits generated patch files and opens a draft GitHub pull request+with `gh` or a draft GitLab merge request with `glab`. Install and authenticate+the appropriate CLI first (`gh auth login` or `glab auth login`). GitLab.com is+selected from the `origin` push URL, including SSH URLs and subgroup projects.+For self-hosted GitLab, set `GITLAB_HOST` to the host in that URL and authenticate+with `glab auth login --hostname HOST`. The existing `GITLAB_URI` and `GL_HOST`+aliases are also accepted, in that order after `GITLAB_HOST`. Other hosts retain+the GitHub workflow.++```bash+GITLAB_HOST=gitlab.example.com npx @openai/codex-security patch --scan SCAN_ID --create-pr+```++Both providers use the existing `pullRequest: { branch, url }` JSON result.+Supplied-issue requests require a clean working tree before patching soexisting work is never included. If publication fails, run the printed`patch --resume-pr BRANCH` command in the same repository. It reuses the savedcommit without rerunning Codex, but refuses to publish if the branch changed.+Use the same GitLab host setting when resuming a self-hosted merge request.To patch Linear issues, repeat `--linear-issue ISSUE` (ID or URL), or use`--linear-project "PROJECT"` with an optional native JSON `--linear-filter`.diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 2bd94e487..d73570ec4 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -323,7 +323,9 @@ const PROVIDER_OPTION = zconst CREATE_PR_OPTION = z.boolean().default(false)- .describe("Create a draft GitHub pull request after verified patches.");+ .describe(+ "Create a draft GitHub pull request or GitLab merge request after verified patches.",+ );const ASSESS_PATCH_RISK_OPTION = z.boolean().default(false)@@ -1174,7 +1176,7 @@ interface CliDependencies {input?: string,): Promise<number>;runRepositoryCommand(- command: "git" | "gh",+ command: "git" | "gh" | "glab",args: readonly string[],repository: string,options?: { trim?: boolean; environment?: NodeJS.ProcessEnv },@@ -5367,36 +5369,90 @@ async function publishPatchBranch(stderr: Writable,dependencies: CliDependencies,): Promise<{ branch: string; url: string }> {- const run = (command: "git" | "gh", args: string[]) =>+ const run = (command: "git" | "gh" | "glab", args: string[]) =>dependencies.runRepositoryCommand(command, args, repository);try {- let url = await run("gh", [- "pr",- "list",- "--head",- branch,- "--state",- "all",- "--json",- "url",- "--jq",- ".[0].url // empty",- ]);+ const remote = await run("git", ["remote", "get-url", "--push", "origin"]);+ const host = patchRemoteHost(remote);+ const gitlabHost =+ dependencies.environment["GITLAB_HOST"] ||+ dependencies.environment["GITLAB_URI"] ||+ dependencies.environment["GL_HOST"];+ const gitlab =+ host === "gitlab.com" ||+ (host !== undefined &&+ gitlabHost !== undefined &&+ host ===+ patchRemoteHost(+ gitlabHost.includes("://") ? gitlabHost : `https://${gitlabHost}`,+ ));+ const command = gitlab ? "glab" : "gh";+ let url = await run(+ command,+ gitlab+ ? [+ "mr",+ "list",+ "--all",+ "--source-branch",+ branch,+ "--output",+ "json",+ "--jq",+ ".[0].web_url // empty",+ "--repo",+ remote,+ ]+ : [+ "pr",+ "list",+ "--head",+ branch,+ "--state",+ "all",+ "--json",+ "url",+ "--jq",+ ".[0].url // empty",+ ],+ );if (!url) {await run("git", ["push", "--set-upstream", "origin", branch]);- url = await run("gh", [- "pr",- "create",- "--draft",- "--head",- branch,- "--title",- PATCH_PR_TITLE,- "--body",- body,- ]);+ url = await run(+ command,+ gitlab+ ? [+ "mr",+ "create",+ "--draft",+ "--head",+ remote,+ "--source-branch",+ branch,+ "--title",+ PATCH_PR_TITLE,+ "--description",+ body,+ "--yes",+ "--repo",+ remote,+ ]+ : [+ "pr",+ "create",+ "--draft",+ "--head",+ branch,+ "--title",+ PATCH_PR_TITLE,+ "--body",+ body,+ ],+ );}- stderr.write(`Pull request: ${safePatchText(url)}\n`);+ stderr.write(+ `${gitlab ? "Merge" : "Pull"} request: ${safePatchText(url)}\n`,+ );return { branch, url };} catch (error) {stderr.write(@@ -5406,6 +5462,11 @@ async function publishPatchBranch(}}+function patchRemoteHost(remote: string): string | undefined {+ if (remote.includes("://")) return new URL(remote).hostname.toLowerCase();+ return /^(?:[^@/]+@)?([^:/]+):[^/]/u.exec(remote)?.[1]?.toLowerCase();+}+async function resumePatchPullRequest(repository: string,branch: string,@@ -5484,14 +5545,14 @@ async function createPatchPullRequest(const branch = `codex-security/patch-${patchId.replaceAll(/[^a-z\d._-]/giu, "-")}`;const body = patchPullRequestBody(patchRiskSummary, introduction);- const run = (command: "git" | "gh", args: string[]) =>- dependencies.runRepositoryCommand(command, args, repository);+ const run = (args: string[]) =>+ dependencies.runRepositoryCommand("git", args, repository);stderr.write(- "Creating a draft GitHub pull request for verified patches...\n",+ "Creating a draft pull request or merge request for verified patches...\n",);- await run("git", ["switch", "-c", branch]);- await run("git", ["--literal-pathspecs", "add", "--", ...files]);- await run("git", [+ await run(["switch", "-c", branch]);+ await run(["--literal-pathspecs", "add", "--", ...files]);+ await run(["--literal-pathspecs","commit","--only",@@ -5500,14 +5561,9 @@ async function createPatchPullRequest("--",...files,]);- const commit = await run("git", ["rev-parse", "HEAD"]);- await run("git", ["config", "--local", patchCommitKey(branch), commit]);- await run("git", [- "config",- "--local",- patchPullRequestBodyKey(branch),- body,- ]);+ const commit = await run(["rev-parse", "HEAD"]);+ await run(["config", "--local", patchCommitKey(branch), commit]);+ await run(["config", "--local", patchPullRequestBodyKey(branch), body]);return publishPatchBranch(repository, branch, body, stderr, dependencies);}diff --git a/sdk/typescript/src/patch-tui.tsx b/sdk/typescript/src/patch-tui.tsxindex ee285d348..8b6a33590 100644--- a/sdk/typescript/src/patch-tui.tsx+++ b/sdk/typescript/src/patch-tui.tsx@@ -652,7 +652,7 @@ export function PatchTui({<Text color={createPullRequest ? success : muted}>{createPullRequest ? "[✓]" : "[ ]"}</Text>- {" Create draft GitHub pull request after patching "}+ {" Create draft pull request or merge request after patching "}<Text dimColor>(r toggle)</Text></Text>diff --git a/sdk/typescript/tests-ts/cli-patch.test.ts b/sdk/typescript/tests-ts/cli-patch.test.tsindex ef22a1d7f..7493298ba 100644--- a/sdk/typescript/tests-ts/cli-patch.test.ts+++ b/sdk/typescript/tests-ts/cli-patch.test.ts@@ -826,16 +826,26 @@ describe("scan and patch workflow", () => {}});- test.each(["push", "create"])(- "resumes publication after %s fails without patching again",- async (failure) => {+ test.each([+ ["github", "push"],+ ["github", "create"],+ ["gitlab", "push"],+ ["gitlab", "create"],+ ["gitlab", "missing client"],+ ])(+ "resumes %s publication after %s fails without patching again",+ async (provider, failure) => {const directory = await mkdtemp(join(tmpdir(), "codex-security-pr-retry-"),);const repository = join(directory, "repository");const remote = join(directory, "remote.git");const branch = "codex-security/patch-scan-1";- const url = "https://github.example.test/example/repository/pull/16";+ const gitlab = provider === "gitlab";+ const origin = "https://gitlab.com/example/subgroup/repository.git";+ const url = gitlab+ ? "https://gitlab.com/example/subgroup/repository/-/merge_requests/16"+ : "https://github.example.test/example/repository/pull/16";const result = resultWithFindings(["high"]);let modelCalls = 0;let pushCalls = 0;@@ -880,6 +890,10 @@ describe("scan and patch workflow", () => {},onRepositoryCommand: (command, args) => {if (command === "git") {+ if (gitlab && args[0] === "remote") {+ expect(args).toEqual(["remote", "get-url", "--push", "origin"]);+ return origin;+ }if (args[0] === "push") {pushCalls += 1;if (failure === "push" && failOnce) {@@ -889,6 +903,11 @@ describe("scan and patch workflow", () => {}return git(...args);}+ expect(command).toBe(gitlab ? "glab" : "gh");+ if (failure === "missing client" && failOnce) {+ failOnce = false;+ throw new Error("spawn glab ENOENT");+ }if (args[1] === "list") return publishedUrl;expect(args[1]).toBe("create");if (failure === "create" && failOnce) {@@ -907,6 +926,10 @@ describe("scan and patch workflow", () => {);expect(first.exitCode).toBe(2);expect(first.stderr).toContain(`patch --resume-pr ${branch}`);+ if (failure === "missing client") {+ expect(first.stderr).toContain("spawn glab ENOENT");+ expect(pushCalls).toBe(0);+ }const commit = git("rev-parse", "HEAD");expect(git("config", "--get", `branch.${branch}.codexSecurityPatchCommit`),@@ -1382,28 +1405,127 @@ describe("scan and patch workflow", () => {});});- test("creates a draft pull request for verified saved-finding patches", async () => {- const result = resultWithFindings(["high"]);- const url = "https://github.example.test/example/repository/pull/14";- let repository = "";- const outcome = await runWorkflow(- ["patch", "--scan", "scan-1", "--create-pr", "--json"],- {- onWorkbench: () => savedScan(result),- onRepositoryCommand: (command, args, target) => {- repository = target;- return command === "gh" && args[1] === "create" ? url : "";+ test.each([+ [+ "https://github.example.test/example/repository.git",+ { GITLAB_HOST: "gitlab.com" },+ "gh",+ ],+ ["https://gitlab.com/example/subgroup/repository.git", {}, "glab"],+ ["[email protected]:example/subgroup/repository.git", {}, "glab"],+ ["ssh://[email protected]:2222/example/subgroup/repository.git", {}, "glab"],+ [+ "[email protected]:example/subgroup/repository.git",+ { GITLAB_HOST: "gitlab.example.test" },+ "glab",+ ],+ [+ "https://gitlab.example.test/example/repository.git",+ { GITLAB_HOST: "https://gitlab.example.test" },+ "glab",+ ],+ [+ "https://gitlab.example.test/example/repository.git",+ { GITLAB_URI: "https://gitlab.example.test" },+ "glab",+ ],+ [+ "https://gitlab.example.test/example/repository.git",+ { GL_HOST: "gitlab.example.test" },+ "glab",+ ],+ ["https://gitlab.example.test/example/repository.git", {}, "gh"],+ ] as const)(+ "publishes saved-finding patches for origin %s with environment %j using %s",+ async (origin, environment, client) => {+ const result = resultWithFindings(["high"]);+ const url =+ client === "glab"+ ? "https://gitlab.example.test/example/repository/-/merge_requests/14"+ : "https://github.example.test/example/repository/pull/14";+ const publicationCommands: Array<readonly string[]> = [];+ const outcome = await runWorkflow(+ [+ "patch",+ "--scan",+ "scan-1",+ "--assess-patch-risk",+ "--create-pr",+ "--json",+ ],+ {+ environment,+ onWorkbench: () => savedScan(result),+ onRepositoryCommand: (command, args, target) => {+ expect(target).toBe(SAVED_REPOSITORY);+ if (command === "git") {+ if (args[0] === "remote") {+ expect(args).toEqual(["remote", "get-url", "--push", "origin"]);+ return origin;+ }+ return "";+ }+ expect(command).toBe(client);+ publicationCommands.push(args);+ return args[1] === "create" ? url : "";+ },},- },- );+ {+ configure: (current) => {+ Object.assign(current, {+ assessPatchRisk: async () => patchRiskAssessment(),+ });+ },+ },+ );- expect(outcome.exitCode).toBe(0);- expect(repository).toBe(SAVED_REPOSITORY);- expect(JSON.parse(outcome.stdout)).toMatchObject({- scanId: "scan-1",- pullRequest: { branch: "codex-security/patch-scan-1", url },- });- });+ expect(outcome.exitCode).toBe(0);+ expect(publicationCommands.map((args) => args[1])).toEqual([+ "list",+ "create",+ ]);+ if (client === "glab") {+ expect(publicationCommands).toEqual([+ [+ "mr",+ "list",+ "--all",+ "--source-branch",+ "codex-security/patch-scan-1",+ "--output",+ "json",+ "--jq",+ ".[0].web_url // empty",+ "--repo",+ origin,+ ],+ [+ "mr",+ "create",+ "--draft",+ "--head",+ origin,+ "--source-branch",+ "codex-security/patch-scan-1",+ "--title",+ "fix: patch verified security findings",+ "--description",+ expect.stringContaining(patchRiskSummary()),+ "--yes",+ "--repo",+ origin,+ ],+ ]);+ }+ expect(outcome.stderr).toContain(+ `${client === "glab" ? "Merge" : "Pull"} request: ${url}`,+ );+ expect(JSON.parse(outcome.stdout)).toMatchObject({+ scanId: "scan-1",+ pullRequest: { branch: "codex-security/patch-scan-1", url },+ });+ },+ );test("redacts credentials when saved-finding pull request creation fails", async () => {const result = resultWithFindings(["high"]);diff --git a/sdk/typescript/tests-ts/patch-tui.test.ts b/sdk/typescript/tests-ts/patch-tui.test.tsindex 58dd67f79..59772c311 100644--- a/sdk/typescript/tests-ts/patch-tui.test.ts+++ b/sdk/typescript/tests-ts/patch-tui.test.ts@@ -101,7 +101,7 @@ describe("interactive patch finding browser", () => {expect(app.lastFrame()).toContain("PATCH INSTRUCTIONS");expect(app.lastFrame()).toContain("Add instructions for this finding.");expect(app.lastFrame()).toContain(- "[ ] Create draft GitHub pull request after patching",+ "[ ] Create draft pull request or merge request after patching",);expect(app.lastFrame()).toContain("3/3 selected");expect(app.lastFrame()).toContain("SUMMARY");@@ -316,12 +316,12 @@ describe("interactive patch finding browser", () => {);expect(app.lastFrame()).toContain(- "[ ] Create draft GitHub pull request after patching",+ "[ ] Create draft pull request or merge request after patching",);app.stdin.write("r");await settle();expect(app.lastFrame()).toContain(- "[✓] Create draft GitHub pull request after patching",+ "[✓] Create draft pull request or merge request after patching",);app.stdin.write("\r");await settle();