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): create private scan output directories (#987)
Adam Hupp2aab4e90ab98
diff --git a/plugins/codex-security/scripts/deep_scan_workbench.py b/plugins/codex-security/scripts/deep_scan_workbench.pyindex 853094a0a..e82ebf2b6 100644--- a/plugins/codex-security/scripts/deep_scan_workbench.py+++ b/plugins/codex-security/scripts/deep_scan_workbench.py@@ -21,6 +21,7 @@ from deep_scan_config import resolve_deep_scan_configfrom filesystem_identity import serialize_filesystem_identityfrom finalize_scan_contract import _read_scan_local_jsonfrom workbench.handoff import require_current_continuation+from workbench.storage import create_private_directoryfrom workbench_target import (directory_content_digest,directory_snapshot_regular_file_count,@@ -838,7 +839,7 @@ def begin_deep_scan_for_target(target_root = (root / safe_segment(target.name)).resolve()if target_root == target or target in target_root.parents:raise SystemExit("The scan artifact directory must be outside the selected target.")- target_root.mkdir(parents=True, exist_ok=True)+ create_private_directory(target_root)user_context = user_context_argument(args)model = optional_text(args.model, maximum=200)reasoning_effort = optional_text(args.reasoning_effort, maximum=32)diff --git a/plugins/codex-security/scripts/workbench/storage.py b/plugins/codex-security/scripts/workbench/storage.pyindex cf3770577..bc5a02aa8 100644--- a/plugins/codex-security/scripts/workbench/storage.py+++ b/plugins/codex-security/scripts/workbench/storage.py@@ -16,3 +16,14 @@ def state_dir() -> Path:def resolve_scan_root(scan_root: str | None) -> Path:return Path(scan_root).expanduser().resolve() if scan_root else state_dir() / "scans"+++def create_private_directory(path: Path) -> None:+ """Create missing directories privately without changing existing permissions."""+ try:+ path.mkdir(mode=0o700, exist_ok=True)+ except FileNotFoundError:+ if path.parent == path:+ raise+ create_private_directory(path.parent)+ path.mkdir(mode=0o700, exist_ok=True)diff --git a/plugins/codex-security/scripts/workbench_db.py b/plugins/codex-security/scripts/workbench_db.pyindex 994df97fc..19059cd2c 100644--- a/plugins/codex-security/scripts/workbench_db.py+++ b/plugins/codex-security/scripts/workbench_db.py@@ -60,7 +60,7 @@ from finalize_scan_contract import ()from finding_preview import bounded_finding_detailsfrom workbench import handoff-from workbench.storage import resolve_scan_root, state_dir+from workbench.storage import create_private_directory, resolve_scan_root, state_dirfrom workbench_cli import parse_argsfrom workbench_constants import (ARTIFACTS,@@ -170,7 +170,7 @@ def database_path() -> Path:@contextmanagerdef scan_completion_lock(scan_id: str) -> Any:lock_dir = state_dir() / "completion-locks"- lock_dir.mkdir(parents=True, exist_ok=True)+ create_private_directory(lock_dir)lock_path = lock_dir / f"{require_uuid(scan_id, 'scan-id')}.lock"descriptor = os.open(lock_path,@@ -233,7 +233,7 @@ def release_completion_file_lock(descriptor: int) -> None:def connect() -> sqlite3.Connection:path = database_path()- path.parent.mkdir(parents=True, exist_ok=True)+ create_private_directory(path.parent)for attempt in range(SQLITE_RETRY_ATTEMPTS):connection = sqlite3.connect(path, timeout=5)try:@@ -856,7 +856,7 @@ def start_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dictmetadata=target_metadata,)target_root = scan_target_root(args.scan_root, target)- target_root.mkdir(parents=True, exist_ok=True)+ create_private_directory(target_root)if manages_transaction:connection.execute("BEGIN IMMEDIATE")workspace = require_workspace(connection, workspace_id)@@ -1024,7 +1024,7 @@ def _start_prompt_driven_scan(**scan_context(connection, existing["id"]),"startDisposition": "joined",}- target_root.mkdir(parents=True, exist_ok=True)+ create_private_directory(target_root)workspace_id = str(uuid.uuid4())scan_id = str(uuid.uuid4())timestamp = now()diff --git a/plugins/codex-security/tests/test_workbench_output_permissions.py b/plugins/codex-security/tests/test_workbench_output_permissions.pynew file mode 100644index 000000000..08368e41b--- /dev/null+++ b/plugins/codex-security/tests/test_workbench_output_permissions.py@@ -0,0 +1,118 @@+from __future__ import annotations++import os+import stat+import uuid+from pathlib import Path++import pytest+from workbench_test_support import create_saved_workspace, run_workbench++pytestmark = pytest.mark.skipif(os.name == "nt", reason="POSIX directory permissions")+++def test_completion_lock_creates_private_directory(+ tmp_path: Path, monkeypatch, workbench_api+) -> None:+ state_dir = tmp_path / "state"+ state_dir.mkdir(mode=0o755)+ state_dir.chmod(0o755)+ monkeypatch.setenv("CODEX_SECURITY_STATE_DIR", str(state_dir))+ previous_umask = os.umask(0o002)+ try:+ with workbench_api["scan_completion_lock"](str(uuid.uuid4())):+ assert stat.S_IMODE((state_dir / "completion-locks").stat().st_mode) == 0o700+ finally:+ os.umask(previous_umask)+ assert stat.S_IMODE(state_dir.stat().st_mode) == 0o755+++ params=[+ ("start-scan", "results"),+ ("start-prompt-only-scan", "scan"),+ ("start-headless-standard-scan", "scan"),+ ("begin-deep-scan", "deepScan"),+ ],+ ids=lambda entry: entry[0],+)+def scan_entrypoint(request) -> tuple[str, str]:+ return request.param+++def start_scan_with_permissive_umask(+ tmp_path: Path, scan_root: Path | None, entrypoint: tuple[str, str]+) -> Path:+ command, result_key = entrypoint+ state_dir = tmp_path / "state"+ target = tmp_path / "target"+ target.mkdir()+ (target / "fixture.py").write_text("print('fixture')\n")+ if command == "start-scan":+ workspace = create_saved_workspace(state_dir, target)+ args = ["--workspace-id", str(workspace["id"])]+ else:+ args = ["--thread-id", "permissions-test", "--target-path", str(target), "--scope", "."]+ if command == "start-prompt-only-scan":+ args.extend(["--mode", "standard"])+ if scan_root is not None:+ args.extend(["--scan-root", str(scan_root)])+ started = run_workbench(+ state_dir,+ command,+ *args,+ environment={"CODEX_HOME": str(tmp_path / "codex-home")},+ umask=0o002,+ )+ return Path(str(started[result_key]["scanDir"]))+++def test_scan_start_creates_private_output_parents_under_permissive_umask(+ tmp_path: Path, scan_entrypoint: tuple[str, str], workbench_api+) -> None:+ existing_root = tmp_path / "output"+ existing_root.mkdir()+ existing_root.chmod(0o755)+ scan_root = existing_root / "nested" / "scans"++ scan_dir = start_scan_with_permissive_umask(tmp_path, scan_root, scan_entrypoint)++ assert stat.S_IMODE(existing_root.stat().st_mode) == 0o755+ for directory in (scan_root.parent, scan_root, scan_dir.parent, scan_dir):+ assert stat.S_IMODE(directory.stat().st_mode) == 0o700+ assert workbench_api["require_canonical_scan_directory"](scan_dir) == scan_dir+++def test_scan_start_creates_private_default_output_parents_under_permissive_umask(+ tmp_path: Path, scan_entrypoint: tuple[str, str], workbench_api+) -> None:+ scan_dir = start_scan_with_permissive_umask(tmp_path, None, scan_entrypoint)++ state_dir = tmp_path / "state"+ assert scan_dir.parent.parent == state_dir / "scans"+ for directory in (state_dir, state_dir / "scans", scan_dir.parent, scan_dir):+ assert stat.S_IMODE(directory.stat().st_mode) == 0o700+ assert workbench_api["require_canonical_scan_directory"](scan_dir) == scan_dir++[email protected]("existing_mode", [0o755, 0o775, 0o777, 0o1777])+def test_scan_start_preserves_existing_output_permissions_and_validation(+ tmp_path: Path, scan_entrypoint: tuple[str, str], existing_mode: int, workbench_api+) -> None:+ scan_root = tmp_path / "scans"+ target_root = scan_root / "target"+ target_root.mkdir(parents=True)+ scan_root.chmod(0o755)+ target_root.chmod(existing_mode)++ scan_dir = start_scan_with_permissive_umask(tmp_path, scan_root, scan_entrypoint)++ assert stat.S_IMODE(scan_root.stat().st_mode) == 0o755+ assert stat.S_IMODE(target_root.stat().st_mode) == existing_mode+ assert stat.S_IMODE(scan_dir.stat().st_mode) == 0o700+ validate_directory = workbench_api["require_canonical_scan_directory"]+ if existing_mode in (0o775, 0o777):+ with pytest.raises(SystemExit, match="group- or world-writable without the sticky bit"):+ validate_directory(scan_dir)+ else:+ assert validate_directory(scan_dir) == scan_dirdiff --git a/plugins/codex-security/tests/workbench_test_support.py b/plugins/codex-security/tests/workbench_test_support.pyindex dae12b77e..12db5cbf4 100644--- a/plugins/codex-security/tests/workbench_test_support.py+++ b/plugins/codex-security/tests/workbench_test_support.py@@ -86,6 +86,7 @@ def run_workbench(check: bool = True,environment: dict[str, str] | None = None,input_text: str | None = None,+ umask: int = -1,) -> dict[str, object]:completed = subprocess.run([sys.executable, str(SCRIPT), *args],@@ -98,6 +99,7 @@ def run_workbench(},input=input_text,text=True,+ umask=umask,)if not check:return {"returncode": completed.returncode, "stderr": completed.stderr}