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(plugin): preserve Windows scope and patch behavior (#594)
ianw-oaib68575b608ea
diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py b/sdk/typescript/_bundled_plugin/scripts/workbench_db.pyindex 5584d3a13..dbf1320e1 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_db.py@@ -110,6 +110,7 @@ from workbench_target import (git_submodule_paths,git_target_metadata,git_worktree_context,+ remediation_checkout_snapshot,require_git_worktree_head,require_remediation_target,require_scan_target_identity,@@ -602,17 +603,15 @@ def verify_manifest_binding(scan: sqlite3.Row, manifest: dict[str, Any]) -> Nonedef require_scope(scope: str, mode: str, target: Path) -> str:value = scope.strip() or "."- if "\\" in value:+ requested_scope = Path(value)+ if "\\" in value and (os.name != "nt" or not requested_scope.is_absolute()):raise SystemExit("Scan scope must use repository-relative POSIX paths.")- parsed = PurePosixPath(value)- if ".." in parsed.parts:+ if ".." in requested_scope.parts:raise SystemExit("Scan scope must stay inside the scanned target.")try:resolved_scope = (- Path(parsed.as_posix()).resolve()- if parsed.is_absolute()- else (target / parsed.as_posix()).resolve()- )+ requested_scope if requested_scope.is_absolute() else target / requested_scope+ ).resolve()relative_scope = resolved_scope.relative_to(target)except (RuntimeError, ValueError) as exc:raise SystemExit("Scan scope must stay inside the scanned target.") from exc@@ -2842,24 +2841,6 @@ def require_pending_remediation_action(current: sqlite3.Row, requested: str) ->)-def remediation_checkout_snapshot(- scan: sqlite3.Row, *, expected_revision: str | None = None-) -> tuple[str, str | None]:- target = require_scan_target_identity(scan)- revision = git_revision(target)- required_revision = expected_revision or scan["target_revision"]- if revision != required_revision:- raise SystemExit(- "Repository HEAD changed. Regenerate the remediation patch against the current checkout."- )- content_digest = (- worktree_content_digest(target)- if revision != "unversioned"- else directory_content_digest(target, excluded=(Path(scan["scan_dir"]),))- )- return revision, content_digest--def require_reviewed_patch_applied(scan: sqlite3.Row, remediation: sqlite3.Row, patch_path: str) -> str | None:@@ -2924,6 +2905,14 @@ def require_reviewed_patch_applied(work_tree=checkout_root,))+ if reverted_digest != remediation["base_content_digest"] and unversioned:+ checkout = Path(temporary) / "checkout-lf"+ copy_directory_excluding(target, checkout, excluded)+ applied_without_conversion = git_command(+ checkout, "-c", "core.autocrlf=input", *arguments, text=True+ )+ if applied_without_conversion.returncode == 0:+ reverted_digest = directory_content_digest(checkout)if reverted_digest != remediation["base_content_digest"]:raise SystemExit("The selected checkout contains changes outside the reviewed patch. Remove them before recording the patch as applied."diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_target.py b/sdk/typescript/_bundled_plugin/scripts/workbench_target.pyindex fdbce930d..01ccb4e6d 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_target.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_target.py@@ -176,6 +176,24 @@ def worktree_content_digest(target: Path) -> str:return worktree_content_digest_for_context(repository, pathspec)+def remediation_checkout_snapshot(+ scan: sqlite3.Row, *, expected_revision: str | None = None+) -> tuple[str, str | None]:+ target = require_scan_target_identity(scan)+ revision = git_revision(target)+ required_revision = expected_revision or scan["target_revision"]+ if revision != required_revision:+ raise SystemExit(+ "Repository HEAD changed. Regenerate the remediation patch against the current checkout."+ )+ content_digest = (+ worktree_content_digest(target)+ if revision != "unversioned"+ else directory_content_digest(target, excluded=(Path(scan["scan_dir"]),))+ )+ return revision, content_digest++def worktree_content_digest_for_context(repository: Path,pathspec: str,diff --git a/sdk/typescript/tests-ts/workbench-windows-compatibility.test.ts b/sdk/typescript/tests-ts/workbench-windows-compatibility.test.tsnew file mode 100644index 000000000..d731259da--- /dev/null+++ b/sdk/typescript/tests-ts/workbench-windows-compatibility.test.ts@@ -0,0 +1,89 @@+import { mkdtemp, realpath, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, expect, test } from "bun:test";+import { PLUGIN_ROOT } from "./plugin-root.js";++const directories: string[] = [];++afterEach(async () => {+ await Promise.all(+ directories+ .splice(0)+ .map((path) => rm(path, { recursive: true, force: true })),+ );+});++function probe(program: string, ...args: string[]): void {+ const python = Bun.which("python3") ?? Bun.which("python");+ if (python === null)+ throw new Error("Python is required for workbench tests.");+ const result = Bun.spawnSync(+ [python, "-I", "-B", "-c", program, join(PLUGIN_ROOT, "scripts"), ...args],+ { stdout: "pipe", stderr: "pipe" },+ );+ expect(result.exitCode, result.stderr.toString()).toBe(0);+}++test("normalizes absolute Windows scopes without accepting escapes", () => {+ probe(+ [+ "import sys",+ "from pathlib import PureWindowsPath",+ "from types import SimpleNamespace",+ "sys.path.insert(0, sys.argv[1])",+ "import workbench_db as workbench",+ "class WindowsPath(PureWindowsPath):",+ " def resolve(self): return self",+ " def is_dir(self): return True",+ "workbench.Path = WindowsPath",+ "workbench.os = SimpleNamespace(name='nt')",+ "target = WindowsPath('C:/repository')",+ "assert workbench.require_scope(r'C:\\repository\\src', 'standard', target) == 'src'",+ "assert workbench.require_scope('src/nested', 'standard', target) == 'src/nested'",+ "assert workbench.require_scope(r'C:\\repository', 'deep', target) == '.'",+ "for scope, mode in [(r'src\\nested', 'standard'), (r'C:\\other', 'standard'), (r'C:\\repository\\..\\other', 'standard'), ('src', 'deep')]:",+ " try: workbench.require_scope(scope, mode, target)",+ " except SystemExit: pass",+ " else: raise AssertionError((scope, mode))",+ ].join("\n"),+ );+});++test("verifies LF and CRLF patches with Git line-ending conversion enabled", async () => {+ const root = await realpath(+ await mkdtemp(join(tmpdir(), "codex-security-line-endings-")),+ );+ directories.push(root);+ probe(+ [+ "import hashlib, os, sys",+ "from pathlib import Path",+ "sys.path.insert(0, sys.argv[1])",+ "import workbench_db as workbench",+ "os.environ.update(GIT_CONFIG_COUNT='1', GIT_CONFIG_KEY_0='core.autocrlf', GIT_CONFIG_VALUE_0='true')",+ "root = Path(sys.argv[2])",+ "for index, ending in enumerate((b'\\n', b'\\r\\n')):",+ " target, scan_dir = root / f'target-{index}', root / f'scan-{index}'",+ " target.mkdir(); scan_dir.mkdir(mode=0o700)",+ " source = target / 'source.txt'",+ " source.write_bytes(b'vulnerable' + ending)",+ " base = workbench.directory_content_digest(target)",+ " patch = b'diff --git a/source.txt b/source.txt\\n--- a/source.txt\\n+++ b/source.txt\\n@@ -1 +1 @@\\n-vulnerable\\n+fixed\\n'",+ " patch_path = scan_dir / 'remediation.patch'",+ " patch_path.write_bytes(patch)",+ " applied = workbench.git_command(target, 'apply', '--no-index', str(patch_path), text=True)",+ " assert applied.returncode == 0, applied.stderr",+ " scan = {'target_path': str(target), 'target_inode': target.stat().st_ino, 'target_revision': 'unversioned', 'scan_dir': str(scan_dir)}",+ " remediation = {'base_revision': 'unversioned', 'base_content_digest': base, 'patch_digest': 'sha256:' + hashlib.sha256(patch).hexdigest()}",+ " current = workbench.directory_content_digest(target)",+ " assert workbench.require_reviewed_patch_applied(scan, remediation, patch_path.name) == current",+ " assert workbench.directory_content_digest(target) == current",+ " (target / 'unrelated.txt').write_bytes(b'unrelated\\n')",+ " try: workbench.require_reviewed_patch_applied(scan, remediation, patch_path.name)",+ " except SystemExit as error: assert 'changes outside the reviewed patch' in str(error)",+ " else: raise AssertionError('unrelated changes were accepted')",+ ].join("\n"),+ root,+ );+});