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(hooks): use trusted Git when installing hooks (#92)
Gautam Sharmacbf9ec372bb3
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex 97c610d03..1aac4a88b 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -2360,8 +2360,9 @@ this repository and contains only the generated commands. Rerun `install-hook`with `--fail-on-severity` set to its original threshold. It recognizes the legacy`npx` hook and supported earlier templates with matching absolute Node and CLIpaths. If it refuses to overwrite the verified hook, back it up, remove it and-reinstall with the same threshold. Restore the backup if installation fails. The installer-respects `core.hooksPath`.+reinstall with the same threshold. Restore the backup if installation fails.+The installer uses host Git for the selected repository and respects+`core.hooksPath`.## Import SonarQube Cloud issuesdiff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex fb092a8fc..6519295a8 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -338,6 +338,7 @@ import {type PolicySecurity,} from "./security-policy-cli.js";import { formatSecurityPolicyText as escapeTerminalText } from "./security-policy.js";+import { commandGitProtectionRoots } from "./local-git-metadata.js";import type { PatchSelection } from "./patch-tui.js";import {scanPhaseLabel as scanPhase,@@ -351,6 +352,7 @@ import {enclosingGitWorktreeRoots,gitMarkerRoot,normalizeRepository,+ trustedGitCommand,UNSUPPORTED_GIT_ENVIRONMENT,type ScanTarget,relativePathIsOutside as isOutsidePath,@@ -5080,20 +5082,31 @@ export async function main(.optional(),async run({ args, options }) {try {+ const cwd = dependencies.currentDirectory();+ const repository = resolveCliPath(cwd, args.repository ?? ".");+ const environment = dependencies.environment;+ const git = await trustedGitCommand(+ repository,+ true,+ environment,+ await commandGitProtectionRoots(+ repository,+ environment,+ undefined,+ cwd,+ ),+ );const hook = execFileSync(- "git",+ git.executable,["-C",- resolveCliPath(- dependencies.currentDirectory(),- args.repository ?? ".",- ),+ repository,"rev-parse","--path-format=absolute","--git-path","hooks/pre-commit",],- { encoding: "utf8" },+ { encoding: "utf8", env: git.environment },).trim();const command = [realpathSync(process.execPath),diff --git a/sdk/typescript/src/external-findings-local.ts b/sdk/typescript/src/external-findings-local.tsindex b58c327f2..e7fe7ad12 100644--- a/sdk/typescript/src/external-findings-local.ts+++ b/sdk/typescript/src/external-findings-local.ts@@ -43,7 +43,7 @@ import { guardianSelectionFormat } from "./semgrep-guardian-findings.js";import {hasGitMetadata,localGitProtectionRoots,- importGitProtectionRoots,+ commandGitProtectionRoots,} from "./local-git-metadata.js";import {blackDuckReportRepositories,@@ -685,7 +685,7 @@ async function localContext(...new Set([repository,...(await abortable(- () => importGitProtectionRoots(path, environment, dependencies.signal),+ () => commandGitProtectionRoots(path, environment, dependencies.signal),dependencies.signal,)),]),diff --git a/sdk/typescript/src/local-git-metadata.ts b/sdk/typescript/src/local-git-metadata.tsindex 76a63d889..41b4b3889 100644--- a/sdk/typescript/src/local-git-metadata.ts+++ b/sdk/typescript/src/local-git-metadata.ts@@ -187,13 +187,13 @@ export async function localGitProtectionRoots(}/** Discover Git metadata for the selection, then for the current working directory. */-export async function importGitProtectionRoots(+export async function commandGitProtectionRoots(repository: string,environment: NodeJS.ProcessEnv,signal?: AbortSignal,+ cwd = process.cwd(),): Promise<string[]> {const roots = await localGitProtectionRoots(repository, environment, signal);- const cwd = process.cwd();if (signal?.aborted) throw abortReason(signal);if (cwd !== repository)roots.push(...(await localGitProtectionRoots(cwd, environment, signal)));diff --git a/sdk/typescript/src/sonar-import.ts b/sdk/typescript/src/sonar-import.tsindex 71ad71f96..2ef0a04cf 100644--- a/sdk/typescript/src/sonar-import.ts+++ b/sdk/typescript/src/sonar-import.ts@@ -10,7 +10,7 @@ import {type ConfiguredFetchRemote,prepareLocalImport,} from "./external-findings-local.js";-import { importGitProtectionRoots } from "./local-git-metadata.js";+import { commandGitProtectionRoots } from "./local-git-metadata.js";import {ExternalPublicationError,externalPublicationStateDirectory,@@ -177,7 +177,7 @@ export async function prepareSonarImport(const configuredState = codexSecurityStateDirectory(environment);const protectedRoots = [repository,- ...(await importGitProtectionRoots(options.cwd, environment, signal)),+ ...(await commandGitProtectionRoots(options.cwd, environment, signal)),];requireOutputOutsideRepositories(protectedRoots, configuredState, "runtime");const state = await canonicalConfigPath(configuredState);diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex af50ea1b0..1e4050ae6 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -12,7 +12,14 @@ import {writeFile,} from "node:fs/promises";import { homedir, tmpdir } from "node:os";-import { delimiter, join, normalize, relative, resolve } from "node:path";+import {+ delimiter,+ dirname,+ join,+ normalize,+ relative,+ resolve,+} from "node:path";import { PassThrough, Writable } from "node:stream";import { fileURLToPath } from "node:url";import { stripVTControlCharacters } from "node:util";@@ -1127,6 +1134,67 @@ describe("CLI", () => {expect(onRun).not.toHaveBeenCalled();});+ test("installs hooks with trusted Git in the selected checkout using the caller's configuration", async () => {+ await using temp = await scopedTemporaryDirectory("trusted-hook-git-");+ const root = await realpath(temp.path);+ const caller = join(root, "caller");+ const target = join(root, "target");+ const component = join(target, "component");+ const alias = join(caller, "target-link");+ const hooks = join(root, "owned hooks");+ const otherHooks = join(root, "other hooks");+ const config = join(root, "gitconfig");+ const git = Bun.which("git")!;+ for (const args of [+ ["init", "-q", caller],+ ["init", "-q", target],+ ["-C", caller, "config", "core.hooksPath", otherHooks],+ ["config", "--file", config, "core.hooksPath", hooks],+ ]) {+ const result = await runCommand(git, args);+ expect(result.status, result.stderr).toBe(0);+ }+ await mkdir(component);+ await symlink(+ target,+ alias,+ process.platform === "win32" ? "junction" : "dir",+ );+ for (const directory of [caller, target]) {+ await writeFile(+ join(directory, process.platform === "win32" ? "git.exe" : "git"),+ "",+ { mode: 0o700 },+ );+ }+ for (const selected of [component, join(alias, "component")]) {+ const { stdout, stderr, runCli } = createCliTest(main);+ const status = await runCli(+ ["install-hook", selected, "--json"],+ dependencies({+ currentDirectory: caller,+ environment: {+ PATH: [caller, target, dirname(git)].join(delimiter),+ SystemRoot: process.env["SystemRoot"],+ GIT_CONFIG_GLOBAL: config,+ GIT_CONFIG_NOSYSTEM: "1",+ GIT_DIR: join(caller, ".git"),+ },+ }),+ );+ expect(status, stderr.text()).toBe(0);+ expect(normalize(JSON.parse(stdout.text()).hook)).toBe(+ join(hooks, "pre-commit"),+ );+ }+ expect(await readFile(join(hooks, "pre-commit"), "utf8")).toContain(+ "--working-tree",+ );+ await expect(stat(join(otherHooks, "pre-commit"))).rejects.toMatchObject({+ code: "ENOENT",+ });+ });+test("installs a pre-commit hook that blocks failed diff scans", async () => {const root = await realpath(await temporaryDirectory("codex-security-cli-pre-commit-"),@@ -1143,6 +1211,7 @@ describe("CLI", () => {const hook = join(root, ".custom hooks", "pre-commit");const deps = dependencies({currentDirectory: root,+ environment: { ...process.env },onRun: () => (started = true),});for (let attempt = 0; attempt < 2; attempt += 1) {@@ -1339,7 +1408,10 @@ describe("CLI", () => {expect(await captureCli(main, "stdout").run(["install-hook", "."],- dependencies({ currentDirectory: repository }),+ dependencies({+ currentDirectory: repository,+ environment: { PATH: dirname(Bun.which("git")!) },+ }),),).toBe(0);} finally {