Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

fix(windows): preserve platform-safe canonical scan paths (#85)

mldangelo-oai3384dcc21d35
diff --git a/sdk/typescript/_bundled_plugin/scripts/deep_scan_workbench.py b/sdk/typescript/_bundled_plugin/scripts/deep_scan_workbench.py
index 8e56da531..e9b9d849a 100644
--- a/sdk/typescript/_bundled_plugin/scripts/deep_scan_workbench.py
+++ b/sdk/typescript/_bundled_plugin/scripts/deep_scan_workbench.py
@@ -239,7 +239,7 @@ def deep_scan_path(
resolved.relative_to(scan_dir)
except (OSError, RuntimeError, ValueError) as exc:
raise SystemExit(f"{label} must be an existing path inside the scan directory.") from exc
- if resolved.as_posix().lower() != supplied.absolute().as_posix().lower():
+ if os.path.normcase(resolved) != os.path.normcase(supplied.absolute()):
raise SystemExit(f"{label} must be a canonical non-symlink path.")
if kind == "file" and not resolved.is_file():
raise SystemExit(f"{label} must be a regular file.")
diff --git a/sdk/typescript/_bundled_plugin/scripts/finalize_scan_contract.py b/sdk/typescript/_bundled_plugin/scripts/finalize_scan_contract.py
index d52d52dde..c5d473d1d 100644
--- a/sdk/typescript/_bundled_plugin/scripts/finalize_scan_contract.py
+++ b/sdk/typescript/_bundled_plugin/scripts/finalize_scan_contract.py
@@ -316,7 +316,7 @@ def _require_scan_directory(scan_dir: Path) -> Path:
resolved = scan_dir.resolve(strict=True)
except OSError as exc:
raise ContractError("scan directory: expected an existing non-symlink directory") from exc
- if resolved.as_posix().lower() != scan_dir.as_posix().lower():
+ if os.path.normcase(resolved) != os.path.normcase(scan_dir):
raise ContractError("scan directory: expected a canonical non-symlink directory")
return resolved
@@ -327,7 +327,10 @@ def _validate_scan_local_output_path(scan_dir: Path, path: Path, relative_path:
resolved_parent.relative_to(scan_dir)
except (OSError, RuntimeError, ValueError) as exc:
raise ContractError(f"{relative_path}: expected a path inside the scan directory") from exc
- if resolved_parent.as_posix().lower() != path.parent.as_posix().lower() or path.is_symlink():
+ if (
+ os.path.normcase(resolved_parent) != os.path.normcase(path.parent)
+ or path.is_symlink()
+ ):
raise ContractError(
f"{relative_path}: expected a non-symlink path inside the scan directory"
)
diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py b/sdk/typescript/_bundled_plugin/scripts/workbench_db.py
index 8faa6d9d4..59b841464 100644
--- a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py
+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_db.py
@@ -3436,7 +3436,7 @@ def artifact_path(scan_dir: Path, file_name: str, *, required: bool) -> Path | N
raise SystemExit(
f"{file_name}: expected a regular file inside the scan directory."
) from exc
- if resolved.as_posix().lower() != candidate.as_posix().lower() or not candidate.is_file():
+ if os.path.normcase(resolved) != os.path.normcase(candidate) or not candidate.is_file():
raise SystemExit(f"{file_name}: expected a regular non-symlink file.")
return resolved
@@ -3450,7 +3450,9 @@ def require_canonical_scan_directory(scan_dir: Path) -> Path:
raise SystemExit(
"Scan directory must be an existing canonical non-symlink directory."
) from exc
- if not stat.S_ISDIR(metadata.st_mode) or resolved.as_posix().lower() != scan_dir.as_posix().lower():
+ if not stat.S_ISDIR(metadata.st_mode) or os.path.normcase(resolved) != os.path.normcase(
+ scan_dir
+ ):
raise SystemExit("Scan directory must be an existing canonical non-symlink directory.")
return scan_dir
diff --git a/sdk/typescript/tests-ts/workbench-canonical-paths.test.ts b/sdk/typescript/tests-ts/workbench-canonical-paths.test.ts
new file mode 100644
index 000000000..356215b15
--- /dev/null
+++ b/sdk/typescript/tests-ts/workbench-canonical-paths.test.ts
@@ -0,0 +1,194 @@
+import {
+ mkdir,
+ mkdtemp,
+ realpath,
+ rm,
+ symlink,
+ writeFile,
+} from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, test } from "bun:test";
+import { PLUGIN_ROOT } from "./plugin-root.js";
+
+const temporaryDirectories: string[] = [];
+const testCaseSensitive = process.platform === "linux" ? test : test.skip;
+const testWindows = process.platform === "win32" ? test : test.skip;
+
+const simulatedPathProbe = [
+ "import json, ntpath, os, posixpath, sys",
+ "from pathlib import PurePosixPath, PureWindowsPath",
+ "from types import SimpleNamespace",
+ "sys.path.insert(0, sys.argv[1])",
+ "import deep_scan_workbench as deep_scan",
+ "mode = sys.argv[2]",
+ "if mode == 'windows':",
+ " path_type, path_module = PureWindowsPath, ntpath",
+ " root, supplied, resolved = 'D:/Scan', 'd:/sCaN/pRoMpT', 'D:/Scan/Prompt'",
+ "else:",
+ " path_type, path_module = PurePosixPath, posixpath",
+ " root, supplied, resolved = '/scan', '/scan/prompt', '/scan/Prompt'",
+ "class SimulatedPath(path_type):",
+ " def expanduser(self):",
+ " return self",
+ " def absolute(self):",
+ " return self",
+ " def resolve(self, strict=False):",
+ " return type(self)(resolved)",
+ " def is_file(self):",
+ " return True",
+ "deep_scan.Path = SimulatedPath",
+ "deep_scan.os = SimpleNamespace(path=path_module)",
+ "deep_scan.require_canonical_scan_directory = lambda path: path",
+ "try:",
+ " result = deep_scan.deep_scan_path({'scan_dir': root}, supplied, 'Worker prompt path', kind='file')",
+ "except SystemExit:",
+ " accepted = False",
+ " result = None",
+ "else:",
+ " accepted = True",
+ "print(json.dumps({'accepted': accepted, 'nativePathEquality': path_type(supplied) == path_type(resolved), 'resolvedPath': result}))",
+].join("\n");
+
+const realFilesystemProbe = [
+ "import json, sys",
+ "from pathlib import Path",
+ "sys.path.insert(0, sys.argv[1])",
+ "import deep_scan_workbench as deep_scan",
+ "import finalize_scan_contract as finalizer",
+ "import workbench_db as workbench",
+ "mode = sys.argv[2]",
+ "scan_dir = Path(sys.argv[3])",
+ "if mode == 'windows':",
+ " alias_scan_dir = Path(str(scan_dir).swapcase())",
+ " alias_directory = alias_scan_dir / 'pRoMpTs'",
+ " artifact_name = 'pRoMpTs/PrOmPt.TxT'",
+ " candidate_name = 'PrOmPt.TxT'",
+ "else:",
+ " alias_scan_dir = Path(sys.argv[4])",
+ " alias_directory = scan_dir / 'prompts'",
+ " artifact_name = 'prompts/prompt.txt'",
+ " candidate_name = 'prompt.txt'",
+ "deep_scan.require_canonical_scan_directory = workbench.require_canonical_scan_directory",
+ "def accepted(action):",
+ " try:",
+ " action()",
+ " except (SystemExit, finalizer.ContractError):",
+ " return False",
+ " return True",
+ "checks = {",
+ " 'deepScanPath': accepted(lambda: deep_scan.deep_scan_path({'scan_dir': str(scan_dir)}, str(alias_directory / candidate_name), 'Worker prompt path', kind='file')),",
+ " 'finalizerScanDirectory': accepted(lambda: finalizer._require_scan_directory(alias_scan_dir)),",
+ " 'finalizerOutputParent': accepted(lambda: finalizer._validate_scan_local_output_path(scan_dir, alias_directory / 'output.json', f'{alias_directory.name}/output.json')),",
+ " 'workbenchArtifact': accepted(lambda: workbench.artifact_path(scan_dir, artifact_name, required=True)),",
+ " 'workbenchScanDirectory': accepted(lambda: workbench.require_canonical_scan_directory(alias_scan_dir)),",
+ "}",
+ "print(json.dumps(checks))",
+].join("\n");
+
+afterEach(async () => {
+ await Promise.all(
+ temporaryDirectories
+ .splice(0)
+ .map((directory) => rm(directory, { recursive: true, force: true })),
+ );
+});
+
+async function temporaryDirectory(): Promise<string> {
+ const directory = await realpath(
+ await mkdtemp(join(tmpdir(), "codex-security-canonical-paths-")),
+ );
+ temporaryDirectories.push(directory);
+ return directory;
+}
+
+function runPythonProbe(
+ program: string,
+ ...args: string[]
+): Record<string, unknown> {
+ const python = Bun.which("python3") ?? Bun.which("python") ?? Bun.which("py");
+ expect(python).not.toBeNull();
+ if (python === null) {
+ throw new Error(
+ "A Python interpreter is required for workbench path tests.",
+ );
+ }
+
+ const result = Bun.spawnSync(
+ [python, "-I", "-B", "-c", program, join(PLUGIN_ROOT, "scripts"), ...args],
+ { stdout: "pipe", stderr: "pipe" },
+ );
+ expect(new TextDecoder().decode(result.stderr)).toBe("");
+ expect(result.exitCode).toBe(0);
+ return JSON.parse(new TextDecoder().decode(result.stdout)) as Record<
+ string,
+ unknown
+ >;
+}
+
+describe("bundled workbench canonical paths", () => {
+ test("preserves native Windows case-insensitive path comparison", () => {
+ expect(runPythonProbe(simulatedPathProbe, "windows")).toMatchObject({
+ accepted: true,
+ nativePathEquality: true,
+ });
+ });
+
+ test("rejects case-differing POSIX symlink resolution", () => {
+ expect(runPythonProbe(simulatedPathProbe, "posix")).toMatchObject({
+ accepted: false,
+ nativePathEquality: false,
+ });
+ });
+
+ testCaseSensitive(
+ "rejects case-differing symlinks at every workbench and finalizer boundary",
+ async () => {
+ const root = await temporaryDirectory();
+ const parent = join(root, "Scans");
+ const aliasParent = join(root, "scans");
+ const scanDirectory = join(parent, "Scan");
+ const promptDirectory = join(scanDirectory, "Prompts");
+ await mkdir(promptDirectory, { recursive: true });
+ await writeFile(join(promptDirectory, "prompt.txt"), "worker prompt\n");
+ await symlink(parent, aliasParent, "dir");
+ await symlink(promptDirectory, join(scanDirectory, "prompts"), "dir");
+
+ expect(
+ runPythonProbe(
+ realFilesystemProbe,
+ "posix",
+ scanDirectory,
+ join(aliasParent, "Scan"),
+ ),
+ ).toEqual({
+ deepScanPath: false,
+ finalizerScanDirectory: false,
+ finalizerOutputParent: false,
+ workbenchArtifact: false,
+ workbenchScanDirectory: false,
+ });
+ },
+ );
+
+ testWindows(
+ "accepts mixed-case Windows paths at every workbench and finalizer boundary",
+ async () => {
+ const root = await temporaryDirectory();
+ const scanDirectory = join(root, "ScanRoot");
+ const promptDirectory = join(scanDirectory, "Prompts");
+ await mkdir(promptDirectory, { recursive: true });
+ await writeFile(join(promptDirectory, "prompt.txt"), "worker prompt\n");
+
+ expect(
+ runPythonProbe(realFilesystemProbe, "windows", scanDirectory),
+ ).toEqual({
+ deepScanPath: true,
+ finalizerScanDirectory: true,
+ finalizerOutputParent: true,
+ workbenchArtifact: true,
+ workbenchScanDirectory: true,
+ });
+ },
+ );
+});