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
Sync from Copyberry
Copyberrye22c417cd264
diff --git a/.gitattributes b/.gitattributesnew file mode 100644index 000000000..d1b802ec6--- /dev/null+++ b/.gitattributes@@ -0,0 +1 @@+sdk/python/src/openai_codex_security/_bundled_plugin/examples/completed-scan/*.json text eol=lfdiff --git a/sdk/python/src/openai_codex_security/_bundled_plugin/scripts/workbench/__init__.py b/sdk/python/src/openai_codex_security/_bundled_plugin/scripts/workbench/__init__.pynew file mode 100644index 000000000..660a264fe--- /dev/null+++ b/sdk/python/src/openai_codex_security/_bundled_plugin/scripts/workbench/__init__.py@@ -0,0 +1 @@+"""Focused Codex Security workbench operation modules."""diff --git a/sdk/python/src/openai_codex_security/_bundled_plugin/scripts/workbench/handoff.py b/sdk/python/src/openai_codex_security/_bundled_plugin/scripts/workbench/handoff.pynew file mode 100644index 000000000..ccf92ceee--- /dev/null+++ b/sdk/python/src/openai_codex_security/_bundled_plugin/scripts/workbench/handoff.py@@ -0,0 +1,238 @@+"""Scan handoff state transitions for the Codex Security workbench."""++from __future__ import annotations++import argparse+import sqlite3+from collections.abc import Callable+from typing import Any++from workbench_validation import optional_text, require_uuid++RECOVERY_HANDOFF_TOKEN_PREFIX = "recovery_"+++def require_handoff_claim_token(value: str) -> str:+ recovery_token = value.startswith(RECOVERY_HANDOFF_TOKEN_PREFIX)+ token = value.removeprefix(RECOVERY_HANDOFF_TOKEN_PREFIX) if recovery_token else value+ normalized = require_uuid(token, "claim-token")+ return f"{RECOVERY_HANDOFF_TOKEN_PREFIX}{normalized}" if recovery_token else normalized+++def require_current_continuation(+ scan: sqlite3.Row,+ claim_token: str | None,+ *,+ error_message: str,+) -> None:+ if (+ scan["handoff_status"] == "delivered"+ and scan["handoff_claim_token"] is None+ and claim_token is None+ ):+ return+ if claim_token is None:+ raise SystemExit(error_message)+ if scan["handoff_claim_token"] != require_handoff_claim_token(claim_token):+ raise SystemExit(error_message)+++def validate_handoff_delivery_thread(+ owning_thread_id: str | None,+ requesting_thread_id: str,+ claim_token: str,+) -> None:+ if owning_thread_id != requesting_thread_id and not claim_token.startswith(+ RECOVERY_HANDOFF_TOKEN_PREFIX+ ):+ raise SystemExit(+ "A scan handoff can only be marked delivered from its owning Codex thread."+ )+++def claim_handoff_delivery(+ connection: sqlite3.Connection,+ args: argparse.Namespace,+ *,+ now: Callable[[], str],+ require_scan: Callable[[sqlite3.Connection, str], sqlite3.Row],+ stale_claim_before: Callable[[], str],+ workspace_state: Callable[[sqlite3.Connection, str], dict[str, Any]],+) -> dict[str, Any]:+ scan_id = require_uuid(args.scan_id, "scan-id")+ claim_token = require_handoff_claim_token(args.claim_token)+ timestamp = now()+ with connection:+ scan = require_scan(connection, scan_id)+ if scan["handoff_status"] != "pending" or scan["handoff_claim_token"] == claim_token:+ return workspace_state(connection, scan["workspace_id"])+ updated = connection.execute(+ """+ UPDATE scans+ SET handoff_claimed_at = ?, handoff_claim_token = ?,+ continuation_thread_id = CASE+ WHEN handoff_claim_token IS NULL THEN continuation_thread_id+ ELSE NULL+ END,+ deep_scan_owner_thread_id = CASE+ WHEN handoff_claim_token IS NULL THEN deep_scan_owner_thread_id+ ELSE NULL+ END,+ updated_at = ?+ WHERE id = ? AND handoff_status = 'pending'+ AND (+ handoff_claim_token IS NULL+ OR (+ ? = 1+ AND (handoff_claimed_at IS NULL OR handoff_claimed_at <= ?)+ )+ )+ """,+ (+ timestamp,+ claim_token,+ timestamp,+ scan["id"],+ int(args.take_over_stale),+ stale_claim_before(),+ ),+ )+ if updated.rowcount != 1:+ return workspace_state(connection, scan["workspace_id"])+ return workspace_state(connection, scan["workspace_id"])+++def release_handoff_delivery(+ connection: sqlite3.Connection,+ args: argparse.Namespace,+ *,+ now: Callable[[], str],+ require_scan: Callable[[sqlite3.Connection, str], sqlite3.Row],+ workspace_state: Callable[[sqlite3.Connection, str], dict[str, Any]],+) -> dict[str, Any]:+ scan_id = require_uuid(args.scan_id, "scan-id")+ claim_token = require_handoff_claim_token(args.claim_token)+ timestamp = now()+ with connection:+ scan = require_scan(connection, scan_id)+ connection.execute(+ """+ UPDATE scans+ SET handoff_claimed_at = NULL, handoff_claim_token = NULL,+ continuation_thread_id = NULL, deep_scan_owner_thread_id = NULL,+ updated_at = ?+ WHERE id = ? AND handoff_status = 'pending'+ AND handoff_claim_token = ?+ """,+ (timestamp, scan["id"], claim_token),+ )+ return workspace_state(connection, scan["workspace_id"])+++def attach_scan_continuation_thread(+ connection: sqlite3.Connection,+ args: argparse.Namespace,+ *,+ now: Callable[[], str],+ require_scan: Callable[[sqlite3.Connection, str], sqlite3.Row],+ workspace_state: Callable[[sqlite3.Connection, str], dict[str, Any]],+) -> dict[str, Any]:+ scan_id = require_uuid(args.scan_id, "scan-id")+ claim_token = require_handoff_claim_token(args.claim_token)+ thread_id = optional_text(args.thread_id, maximum=512)+ if thread_id is None:+ raise SystemExit("Codex Security continuation thread ID is required.")+ connection.execute("BEGIN IMMEDIATE")+ try:+ timestamp = now()+ scan = require_scan(connection, scan_id)+ if scan["handoff_claim_token"] != claim_token:+ raise SystemExit("Codex Security continuation thread claim token does not match.")+ if scan["continuation_thread_id"] is not None:+ if scan["continuation_thread_id"] != thread_id:+ raise SystemExit(+ "Codex Security scan continuation is owned by another continuation."+ )+ connection.commit()+ return workspace_state(connection, scan["workspace_id"])+ updated = connection.execute(+ """+ UPDATE scans+ SET continuation_thread_id = ?,+ deep_scan_owner_thread_id = CASE+ WHEN mode = 'deep' THEN ? ELSE deep_scan_owner_thread_id+ END,+ updated_at = ?+ WHERE id = ? AND continuation_thread_id IS NULL+ AND handoff_claim_token = ?+ """,+ (thread_id, thread_id, timestamp, scan["id"], claim_token),+ )+ if updated.rowcount != 1:+ raise SystemExit("Codex Security continuation thread could not be attached.")+ connection.commit()+ except BaseException:+ connection.rollback()+ raise+ return workspace_state(connection, scan["workspace_id"])+++def mark_handoff_delivered(+ connection: sqlite3.Connection,+ args: argparse.Namespace,+ *,+ now: Callable[[], str],+ require_scan: Callable[[sqlite3.Connection, str], sqlite3.Row],+ require_workspace: Callable[[sqlite3.Connection, str], sqlite3.Row],+ workspace_state: Callable[[sqlite3.Connection, str], dict[str, Any]],+) -> dict[str, Any]:+ scan_id = require_uuid(args.scan_id, "scan-id")+ claim_token = require_handoff_claim_token(args.claim_token)+ thread_id = optional_text(args.thread_id, maximum=512)+ connection.execute("BEGIN IMMEDIATE")+ try:+ timestamp = now()+ scan = require_scan(connection, scan_id)+ if thread_id is not None:+ workspace = require_workspace(connection, scan["workspace_id"])+ validate_handoff_delivery_thread(+ scan["continuation_thread_id"] or workspace["thread_id"],+ thread_id,+ claim_token,+ )+ if scan["handoff_status"] == "delivered":+ if scan["handoff_claim_token"] != claim_token:+ raise SystemExit(+ "Codex Security handoff delivery is owned by another continuation."+ )+ connection.commit()+ return workspace_state(connection, scan["workspace_id"])+ updated = connection.execute(+ """+ UPDATE scans+ SET handoff_status = 'delivered', handoff_claimed_at = NULL,+ updated_at = ?+ WHERE id = ? AND handoff_status = 'pending'+ AND handoff_claim_token = ?+ """,+ (timestamp, scan["id"], claim_token),+ )+ if updated.rowcount != 1:+ raise SystemExit("Codex Security handoff delivery could not be recorded.")+ if scan["mode"] != "deep":+ connection.execute(+ """+ UPDATE scan_progress+ SET phase_items_total = 0, phase_items_completed = 0,+ phase_progress_unit = 'checks',+ preflight_checks_total = 0, preflight_checks_completed = 0,+ updated_at = ?+ WHERE scan_id = ?+ """,+ (timestamp, scan["id"]),+ )+ connection.commit()+ except BaseException:+ connection.rollback()+ raise+ return workspace_state(connection, scan["workspace_id"])diff --git a/sdk/python/src/openai_codex_security/_bundled_plugin/scripts/workbench_scan_start.py b/sdk/python/src/openai_codex_security/_bundled_plugin/scripts/workbench_scan_start.pynew file mode 100644index 000000000..f4b914505--- /dev/null+++ b/sdk/python/src/openai_codex_security/_bundled_plugin/scripts/workbench_scan_start.py@@ -0,0 +1,147 @@+"""Shared scan-start helpers for the Codex Security workbench."""++from __future__ import annotations++import argparse+import os+import sqlite3+import sys+import tempfile+from datetime import datetime, timezone+from pathlib import Path++# Some plugin hosts launch Python with safe-path isolation enabled.+sys.path.insert(0, str(Path(__file__).resolve().parent))+from filesystem_identity import serialize_filesystem_identity+from workbench_target import (+ directory_content_digest,+ git_revision,+ worktree_content_digest,+)+++def safe_segment(value: str) -> str:+ segment = "".join(+ character if character.isalnum() or character in "._-" else "-" for character in value+ )+ return segment.strip("-") or "scan"+++def compact_timestamp() -> str:+ return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")+++def scan_target_identity(+ target: Path,+ diff_target: dict[str, str] | None,+ *,+ metadata: os.stat_result | None = None,+) -> tuple[str, str | None, int | str, int | str]:+ if metadata is None:+ metadata = target.stat()+ revision = diff_target["headRevision"] if diff_target else git_revision(target)+ snapshot_digest = None+ if diff_target is None:+ snapshot_digest = (+ directory_content_digest(target)+ if revision == "unversioned"+ else worktree_content_digest(target)+ )+ return (+ revision,+ snapshot_digest,+ serialize_filesystem_identity(metadata.st_dev),+ serialize_filesystem_identity(metadata.st_ino),+ )+++def scan_diff_identity(+ diff_target: dict[str, str] | None,+) -> tuple[str | None, str | None, str | None, str | None]:+ if diff_target is None:+ return (None, None, None, None)+ return (+ diff_target["kind"],+ diff_target["baseRevision"],+ diff_target["headRevision"],+ diff_target.get("contentDigest"),+ )+++def insert_running_scan(+ connection: sqlite3.Connection,+ *,+ scan_id: str,+ workspace: sqlite3.Row,+ target: Path,+ scope: str,+ diff_target: dict[str, str] | None,+ target_identity: tuple[str, str | None, int | str, int | str],+ target_root: Path,+ target_summary: str | None,+ scope_file_count: int,+ timestamp: str,+ handoff_status: str = "pending",+) -> str:+ revision = target_identity[0]+ scan_dir = Path(+ tempfile.mkdtemp(+ prefix=f"{safe_segment(revision)}_{compact_timestamp()}_",+ dir=target_root,+ )+ ).resolve()+ connection.execute(+ """+ INSERT INTO scans (+ id, workspace_id, target_id, target_path, target_revision, target_snapshot_digest,+ target_device, target_inode, scope, mode, user_context,+ deep_scan_owner_thread_id, diff_target_kind, diff_base_revision,+ diff_head_revision, diff_content_digest, target_summary, scan_dir, status, phase,+ handoff_status, started_at, created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', 'preflight',+ ?, ?, ?, ?)+ """,+ (+ scan_id,+ workspace["id"],+ workspace["target_id"],+ str(target),+ *target_identity,+ scope,+ workspace["default_mode"],+ workspace["user_context"],+ workspace["thread_id"] if workspace["default_mode"] == "deep" else None,+ diff_target["kind"] if diff_target else None,+ diff_target["baseRevision"] if diff_target else None,+ diff_target["headRevision"] if diff_target else None,+ diff_target.get("contentDigest") if diff_target else None,+ target_summary,+ str(scan_dir),+ handoff_status,+ timestamp,+ timestamp,+ timestamp,+ ),+ )+ connection.execute(+ """+ INSERT INTO scan_progress (+ scan_id, scope_file_count, review_items_total, review_items_completed,+ reportable_findings_count, updated_at+ ) VALUES (?, ?, 0, 0, 0, ?)+ """,+ (scan_id, scope_file_count, timestamp),+ )+ connection.execute(+ "UPDATE workspaces SET active_scan_id = ?, updated_at = ? WHERE id = ?",+ (scan_id, timestamp, workspace["id"]),+ )+ return scan_id+++def main() -> None:+ argparse.ArgumentParser(description=__doc__).parse_args()+++if __name__ == "__main__":+ main()diff --git a/sdk/python/src/openai_codex_security/_bundled_plugin/scripts/workbench_target_state.py b/sdk/python/src/openai_codex_security/_bundled_plugin/scripts/workbench_target_state.pynew file mode 100644index 000000000..47d2ea6d3--- /dev/null+++ b/sdk/python/src/openai_codex_security/_bundled_plugin/scripts/workbench_target_state.py@@ -0,0 +1,63 @@+"""Persist stable Codex Security target identities."""++from __future__ import annotations++import argparse+import hashlib+import sqlite3+from datetime import datetime, timezone+from pathlib import Path+++def stable_target_id(target: Path) -> str:+ digest = hashlib.sha256(f"local-workspace\0{target}".encode()).hexdigest()+ return f"target_sha256_{digest}"+++def backfill_security_targets(connection: sqlite3.Connection) -> None:+ rows = connection.execute(+ """+ SELECT target_path FROM workspaces WHERE target_path IS NOT NULL+ UNION+ SELECT target_path FROM scans+ """+ ).fetchall()+ for row in rows:+ target_path = row["target_path"]+ target_id = ensure_security_target(connection, target_path)+ connection.execute(+ "UPDATE workspaces SET target_id = ? WHERE target_path = ? AND target_id IS NULL",+ (target_id, target_path),+ )+ connection.execute(+ "UPDATE scans SET target_id = ? WHERE target_path = ? AND target_id IS NULL",+ (target_id, target_path),+ )+++def ensure_security_target(connection: sqlite3.Connection, target_path: str) -> str:+ existing = connection.execute(+ "SELECT id FROM security_targets WHERE current_path = ?",+ (target_path,),+ ).fetchone()+ if existing is not None:+ return str(existing["id"])+ target_id = stable_target_id(Path(target_path))+ timestamp = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")+ connection.execute(+ """+ INSERT OR IGNORE INTO security_targets (+ id, current_path, display_name, created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?)+ """,+ (target_id, target_path, Path(target_path).name, timestamp, timestamp),+ )+ return target_id+++def main() -> None:+ argparse.ArgumentParser(description=__doc__).parse_args()+++if __name__ == "__main__":+ main()