{"task_id": "pg-train-sqli-0000", "category": "sqli", "source": "openrouter:openai/gpt-4.1-mini", "messages": [{"role": "system", "content": "You are PatchGuard, a security-focused Python engineer. Fix the security vulnerabilities in the provided Python module without breaking any existing functionality or public API signatures. Use proper structural defenses (parameterized SQL, canonical Path confinement, shell=False argument vectors, IP/scheme SSRF checks, server-side authorization checks, safe JSON/literal parsing, context-aware HTML escaping, salted slow password hashing, CSPRNG tokens, and secret redaction). Do not swallow exceptions silently, hardcode test outputs, or use brittle string blacklists. Return a single complete ```python``` code block."}, {"role": "user", "content": "Service module `payroll_portal` has a SQL Injection (Parameterized Queries & Identifier Allow-List) (CWE-89) security issue.\nPatch the module below so all legitimate behavior and exact function names/signatures remain intact, while eliminating the security vulnerability structurally.\n\n```python\nimport sqlite3\n\n\ndef query_shipments(db_path: str, query: str, sort_by: str = \"unit_count\", limit: int = 10) -> list[dict]:\n \"\"\"Search shipments matching query on visit_reason and return sorted rows.\"\"\"\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, visit_reason, category_tag, unit_count \"\n f\"FROM shipments \"\n f\"WHERE visit_reason LIKE '%{query}%' \"\n f\"ORDER BY {sort_by} DESC \"\n f\"LIMIT {int(limit)}\"\n )\n rows = conn.execute(sql).fetchall()\n return [dict(r) for r in rows]\n finally:\n conn.close()\n```\n"}, {"role": "assistant", "content": "```python\nimport sqlite3\n\n\ndef query_shipments(db_path: str, query: str, sort_by: str = \"unit_count\", limit: int = 10) -> list[dict]:\n \"\"\"Search shipments matching query on visit_reason and return sorted rows.\"\"\"\n allowed_sort_columns = {\"id\", \"visit_reason\", \"category_tag\", \"unit_count\"}\n if sort_by not in allowed_sort_columns:\n raise ValueError(f\"Invalid sort_by column: {sort_by!r}\")\n\n if not isinstance(limit, int) or limit <= 0:\n raise ValueError(\"limit must be a positive integer\")\n\n # Use parameterized queries for user inputs\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, visit_reason, category_tag, unit_count \"\n f\"FROM shipments \"\n f\"WHERE visit_reason LIKE ? \"\n f\"ORDER BY {sort_by} DESC \"\n f\"LIMIT ?\"\n )\n # Parameterize query and limit; sort_by is validated and safe to interpolate\n rows = conn.execute(sql, (f\"%{query}%\", limit)).fetchall()\n return [dict(r) for r in rows]\n finally:\n conn.close()\n```"}]} {"task_id": "pg-train-path_traversal-0001", "category": "path_traversal", "source": "openrouter:openai/gpt-4.1-mini", "messages": [{"role": "system", "content": "You are PatchGuard, a security-focused Python engineer. Fix the security vulnerabilities in the provided Python module without breaking any existing functionality or public API signatures. Use proper structural defenses (parameterized SQL, canonical Path confinement, shell=False argument vectors, IP/scheme SSRF checks, server-side authorization checks, safe JSON/literal parsing, context-aware HTML escaping, salted slow password hashing, CSPRNG tokens, and secret redaction). Do not swallow exceptions silently, hardcode test outputs, or use brittle string blacklists. Return a single complete ```python``` code block."}, {"role": "user", "content": "Service module `fleet_dispatch` has a Path Traversal (Canonical Path Confinement) (CWE-22) security issue.\nPatch the module below so all legitimate behavior and exact function names/signatures remain intact, while eliminating the security vulnerability structurally.\n\n```python\nimport os\n\n\ndef fetch_artifact_text(base_dir: str, rel_path: str) -> str:\n \"\"\"Read a UTF-8 text file located under base_dir.\"\"\"\n target = os.path.join(base_dir, rel_path)\n with open(target, \"r\", encoding=\"utf-8\") as fh:\n return fh.read()\n```\n"}, {"role": "assistant", "content": "```python\nimport os\n\n\ndef _is_within_directory(base_dir: str, target_path: str) -> bool:\n \"\"\"Check if target_path is within base_dir after resolving symlinks and relative paths.\"\"\"\n base_dir_abs = os.path.abspath(os.path.realpath(base_dir))\n target_abs = os.path.abspath(os.path.realpath(target_path))\n return os.path.commonpath([base_dir_abs]) == os.path.commonpath([base_dir_abs, target_abs])\n\n\ndef fetch_artifact_text(base_dir: str, rel_path: str) -> str:\n \"\"\"\n Read a UTF-8 text file located under base_dir safely.\n\n Raises:\n ValueError: If the resolved path is outside the base_dir.\n FileNotFoundError, OSError: If the file cannot be opened.\n \"\"\"\n target = os.path.join(base_dir, rel_path)\n if not _is_within_directory(base_dir, target):\n raise ValueError(\"Attempted Path Traversal outside the base directory\")\n with open(target, \"r\", encoding=\"utf-8\") as fh:\n return fh.read()\n```"}]} {"task_id": "pg-train-cmd_injection-0002", "category": "cmd_injection", "source": "openrouter:openai/gpt-4.1-mini", "messages": [{"role": "system", "content": "You are PatchGuard, a security-focused Python engineer. Fix the security vulnerabilities in the provided Python module without breaking any existing functionality or public API signatures. Use proper structural defenses (parameterized SQL, canonical Path confinement, shell=False argument vectors, IP/scheme SSRF checks, server-side authorization checks, safe JSON/literal parsing, context-aware HTML escaping, salted slow password hashing, CSPRNG tokens, and secret redaction). Do not swallow exceptions silently, hardcode test outputs, or use brittle string blacklists. Return a single complete ```python``` code block."}, {"role": "user", "content": "Service module `clinic_intake` has a OS Command Injection (Argument Vector & Option Separation) (CWE-78) security issue.\nPatch the module below so all legitimate behavior and exact function names/signatures remain intact, while eliminating the security vulnerability structurally.\n\n```python\nimport subprocess\nimport sys\n\n\ndef run_clinic_intake_tool(script_path: str, mode: str, target_name: str) -> str:\n \"\"\"Execute the local helper script with mode ('summary' or 'verify') and positional target_name.\"\"\"\n cmd = f\"{sys.executable} {script_path} --mode {mode} {target_name}\"\n proc = subprocess.run(cmd, shell=True, capture_output=True, text=True, check=True)\n return proc.stdout.strip()\n```\n"}, {"role": "assistant", "content": "```python\nimport subprocess\nimport sys\n\n# Allowed modes for the clinic intake tool\nALLOWED_MODES = frozenset({\"summary\", \"verify\"})\n\ndef run_clinic_intake_tool(script_path: str, mode: str, target_name: str) -> str:\n \"\"\"Execute the local helper script with mode ('summary' or 'verify') and positional target_name.\"\"\"\n if mode not in ALLOWED_MODES:\n raise ValueError(f\"Invalid mode: {mode!r}. Allowed modes are: {sorted(ALLOWED_MODES)}\")\n\n # Use argument vector to avoid shell injection\n cmd = [sys.executable, script_path, \"--mode\", mode, target_name]\n\n proc = subprocess.run(cmd, shell=False, capture_output=True, text=True, check=True)\n return proc.stdout.strip()\n```"}]} {"task_id": "pg-train-ssrf-0003", "category": "ssrf", "source": "openrouter:openai/gpt-4.1-mini", "messages": [{"role": "system", "content": "You are PatchGuard, a security-focused Python engineer. Fix the security vulnerabilities in the provided Python module without breaking any existing functionality or public API signatures. Use proper structural defenses (parameterized SQL, canonical Path confinement, shell=False argument vectors, IP/scheme SSRF checks, server-side authorization checks, safe JSON/literal parsing, context-aware HTML escaping, salted slow password hashing, CSPRNG tokens, and secret redaction). Do not swallow exceptions silently, hardcode test outputs, or use brittle string blacklists. Return a single complete ```python``` code block."}, {"role": "user", "content": "Service module `clinic_intake` has a Server-Side Request Forgery (Scheme, Host & Resolved IP Validation) (CWE-918) security issue.\nPatch the module below so all legitimate behavior and exact function names/signatures remain intact, while eliminating the security vulnerability structurally.\n\n```python\nimport urllib.request\n\n\ndef fetch_remote_feed(url: str, resolver=None, transport=None) -> str:\n \"\"\"Fetch text from an HTTP(S) URL. When provided, use resolver(hostname) -> list[str] for DNS lookup and transport(url) -> str for HTTP fetch.\"\"\"\n if not url.startswith((\"http://\", \"https://\")):\n raise ValueError(\"Unsupported URL scheme\")\n if \"localhost\" in url:\n raise ValueError(\"Localhost blocked\")\n if transport is not None:\n return transport(url)\n with urllib.request.urlopen(url, timeout=5) as resp:\n return resp.read().decode(\"utf-8\")\n```\n"}, {"role": "assistant", "content": "```python\nimport urllib.request\nimport urllib.parse\nimport socket\nimport ipaddress\n\n\ndef fetch_remote_feed(url: str, resolver=None, transport=None) -> str:\n \"\"\"Fetch text from an HTTP(S) URL. When provided, use resolver(hostname) -> list[str] for DNS lookup and transport(url) -> str for HTTP fetch.\"\"\"\n\n # Validate scheme early\n parsed = urllib.parse.urlparse(url)\n scheme = parsed.scheme.lower()\n if scheme not in (\"http\", \"https\"):\n raise ValueError(\"Unsupported URL scheme\")\n\n hostname = parsed.hostname\n if not hostname:\n raise ValueError(\"URL must have a hostname\")\n\n # Block localhost and loopback names explicitly\n # Also block IPs in private/reserved ranges\n # Check hostname for localhost variants (case-insensitive)\n if hostname.lower() == \"localhost\":\n raise ValueError(\"Localhost blocked\")\n\n # Resolve IPs using provided resolver or system DNS\n ips = []\n if resolver is not None:\n try:\n ips = resolver(hostname)\n except Exception as e:\n raise ValueError(f\"DNS resolution failed: {e}\") from e\n else:\n try:\n # getaddrinfo returns tuples: (family, type, proto, canonname, sockaddr)\n # sockaddr is (address, port) for IPv4 or (address, port, flow info, scope id) for IPv6\n infos = socket.getaddrinfo(hostname, None)\n ips = [info[4][0] for info in infos]\n except socket.gaierror as e:\n raise ValueError(f\"DNS resolution failed: {e}\") from e\n\n if not ips:\n raise ValueError(\"No IP addresses resolved for hostname\")\n\n # Check each resolved IP is public and not loopback/private/reserved\n for ip_str in ips:\n try:\n ip = ipaddress.ip_address(ip_str)\n except ValueError:\n raise ValueError(f\"Invalid IP address resolved: {ip_str}\")\n if ip.is_loopback or ip.is_private or ip.is_reserved or ip.is_link_local or ip.is_multicast:\n raise ValueError(f\"Blocked IP address resolved: {ip_str}\")\n\n # If transport override provided, use it\n if transport is not None:\n return transport(url)\n\n # Use urllib.request.urlopen with timeout and no redirects to prevent SSRF via redirects\n # (urllib does follow redirects by default, but we cannot disable easily; \n # so we rely on IP checks above and scheme check)\n with urllib.request.urlopen(url, timeout=5) as resp:\n # Defensive: check final URL after redirects to ensure it still matches allowed scheme and hostname/IP\n final_url = resp.geturl()\n final_parsed = urllib.parse.urlparse(final_url)\n final_scheme = final_parsed.scheme.lower()\n if final_scheme not in (\"http\", \"https\"):\n raise ValueError(\"Redirected URL has unsupported scheme\")\n final_hostname = final_parsed.hostname\n if not final_hostname:\n raise ValueError(\"Redirected URL missing hostname\")\n if final_hostname.lower() == \"localhost\":\n raise ValueError(\"Redirected URL to localhost blocked\")\n\n # Resolve final hostname and check IPs again\n final_ips = []\n if resolver is not None:\n try:\n final_ips = resolver(final_hostname)\n except Exception as e:\n raise ValueError(f\"DNS resolution failed on redirect: {e}\") from e\n else:\n try:\n infos = socket.getaddrinfo(final_hostname, None)\n final_ips = [info[4][0] for info in infos]\n except socket.gaierror as e:\n raise ValueError(f\"DNS resolution failed on redirect: {e}\") from e\n\n if not final_ips:\n raise ValueError(\"No IP addresses resolved for redirected hostname\")\n\n for ip_str in final_ips:\n try:\n ip = ipaddress.ip_address(ip_str)\n except ValueError:\n raise ValueError(f\"Invalid IP address resolved on redirect: {ip_str}\")\n if ip.is_loopback or ip.is_private or ip.is_reserved or ip.is_link_local or ip.is_multicast:\n raise ValueError(f\"Blocked IP address resolved on redirect: {ip_str}\")\n\n return resp.read().decode(\"utf-8\")\n```"}]} {"task_id": "pg-train-idor_auth-0004", "category": "idor_auth", "source": "openrouter:openai/gpt-4.1-mini", "messages": [{"role": "system", "content": "You are PatchGuard, a security-focused Python engineer. Fix the security vulnerabilities in the provided Python module without breaking any existing functionality or public API signatures. Use proper structural defenses (parameterized SQL, canonical Path confinement, shell=False argument vectors, IP/scheme SSRF checks, server-side authorization checks, safe JSON/literal parsing, context-aware HTML escaping, salted slow password hashing, CSPRNG tokens, and secret redaction). Do not swallow exceptions silently, hardcode test outputs, or use brittle string blacklists. Return a single complete ```python``` code block."}, {"role": "user", "content": "Service module `warehouse_ledger` has a Broken Access Control & IDOR (Server-Verified Identity & Ownership) (CWE-639) security issue.\nPatch the module below so all legitimate behavior and exact function names/signatures remain intact, while eliminating the security vulnerability structurally.\n\n```python\ndef update_shipments_record(store: dict, session: dict, resource_id: str, payload: dict | None = None) -> dict:\n \"\"\"Read or update a record in store. Caller must have session['user_id'] matching record['owner_id'] (or session.get('role') == 'admin'); payload must not alter protected fields (id, owner_id, role, is_admin).\"\"\"\n record = store[resource_id]\n if payload:\n if payload.get(\"is_admin\"):\n record.update(payload)\n else:\n record.update(payload)\n return dict(record)\n```\n"}, {"role": "assistant", "content": "```python\ndef update_shipments_record(store: dict, session: dict, resource_id: str, payload: dict | None = None) -> dict:\n \"\"\"Read or update a record in store. Caller must have session['user_id'] matching record['owner_id'] (or session.get('role') == 'admin'); payload must not alter protected fields (id, owner_id, role, is_admin).\"\"\"\n if resource_id not in store:\n raise ValueError(\"Resource ID not found\")\n\n record = store[resource_id]\n\n user_id = session.get('user_id')\n role = session.get('role')\n\n if user_id is None:\n raise PermissionError(\"User not authenticated\")\n\n # Enforce ownership or admin role\n if record.get('owner_id') != user_id and role != 'admin':\n raise PermissionError(\"User not authorized to access this resource\")\n\n if payload:\n # Disallow modification of protected fields\n protected_fields = {'id', 'owner_id', 'role', 'is_admin'}\n if any(field in payload for field in protected_fields):\n raise PermissionError(\"Modification of protected fields is not allowed\")\n\n # Update record safely\n record.update(payload)\n\n return dict(record)\n```"}]} {"task_id": "pg-train-unsafe_deser_eval-0005", "category": "unsafe_deser_eval", "source": "openrouter:openai/gpt-4.1-mini", "messages": [{"role": "system", "content": "You are PatchGuard, a security-focused Python engineer. Fix the security vulnerabilities in the provided Python module without breaking any existing functionality or public API signatures. Use proper structural defenses (parameterized SQL, canonical Path confinement, shell=False argument vectors, IP/scheme SSRF checks, server-side authorization checks, safe JSON/literal parsing, context-aware HTML escaping, salted slow password hashing, CSPRNG tokens, and secret redaction). Do not swallow exceptions silently, hardcode test outputs, or use brittle string blacklists. Return a single complete ```python``` code block."}, {"role": "user", "content": "Service module `clinic_intake` has a Unsafe Deserialization & Code Evaluation (CWE-502) security issue.\nPatch the module below so all legitimate behavior and exact function names/signatures remain intact, while eliminating the security vulnerability structurally.\n\n```python\nimport pickle\n\n\ndef parse_clinic_intake_payload(raw_payload: str) -> dict:\n \"\"\"Decode an incoming serialized message dictionary.\"\"\"\n if raw_payload.startswith(\"pickle:\"):\n data = pickle.loads(bytes.fromhex(raw_payload[7:]))\n else:\n data = eval(raw_payload)\n if not isinstance(data, dict):\n raise ValueError(\"Payload must decode to a dict\")\n return data\n```\n"}, {"role": "assistant", "content": "```python\nimport json\nfrom typing import Any, Dict\n\n\ndef _safe_eval_dict_literal(raw: str) -> Dict[str, Any]:\n \"\"\"\n Safely parse a string representing a dictionary literal using JSON.\n Raises ValueError if parsing fails or result is not a dict.\n \"\"\"\n try:\n data = json.loads(raw)\n except json.JSONDecodeError as e:\n raise ValueError(f\"Invalid JSON payload: {e}\") from e\n if not isinstance(data, dict):\n raise ValueError(\"Payload must decode to a dict\")\n return data\n\n\ndef parse_clinic_intake_payload(raw_payload: str) -> dict:\n \"\"\"\n Decode an incoming serialized message dictionary.\n Supports JSON-encoded dicts only.\n Rejects all pickle and eval usage for security.\n \"\"\"\n # Reject pickle-based payloads outright to avoid unsafe deserialization\n if raw_payload.startswith(\"pickle:\"):\n raise ValueError(\"Pickle-based payloads are not supported for security reasons\")\n # Safely parse JSON dictionary payloads only\n return _safe_eval_dict_literal(raw_payload)\n```"}]} {"task_id": "pg-train-xss-0006", "category": "xss", "source": "openrouter:openai/gpt-4.1-mini", "messages": [{"role": "system", "content": "You are PatchGuard, a security-focused Python engineer. Fix the security vulnerabilities in the provided Python module without breaking any existing functionality or public API signatures. Use proper structural defenses (parameterized SQL, canonical Path confinement, shell=False argument vectors, IP/scheme SSRF checks, server-side authorization checks, safe JSON/literal parsing, context-aware HTML escaping, salted slow password hashing, CSPRNG tokens, and secret redaction). Do not swallow exceptions silently, hardcode test outputs, or use brittle string blacklists. Return a single complete ```python``` code block."}, {"role": "user", "content": "Service module `clinic_intake` has a Cross-Site Scripting & Unsafe href Scheme (CWE-79) security issue.\nPatch the module below so all legitimate behavior and exact function names/signatures remain intact, while eliminating the security vulnerability structurally.\n\n```python\ndef render_vehicles_badge(title: str, summary: str, link_url: str) -> str:\n \"\"\"Render an HTML card badge with title, summary, and external link.\"\"\"\n return f'
'\n```\n"}, {"role": "assistant", "content": "```python\nimport html\nfrom urllib.parse import urlparse\n\n# Allowed URL schemes for href attribute to prevent unsafe links (e.g. javascript:)\nALLOWED_HREF_SCHEMES = frozenset({'http', 'https', 'mailto', 'tel', ''}) # '' for relative URLs\n\n\ndef _is_safe_href(href: str) -> bool:\n \"\"\"\n Check if the href URL has an allowed scheme.\n Relative URLs (no scheme) are allowed.\n \"\"\"\n parsed = urlparse(href)\n return parsed.scheme.lower() in ALLOWED_HREF_SCHEMES\n\n\ndef render_vehicles_badge(title: str, summary: str, link_url: str) -> str:\n \"\"\"Render an HTML card badge with title, summary, and external link.\"\"\"\n # Escape title and summary to prevent XSS\n safe_title = html.escape(title, quote=True)\n safe_summary = html.escape(summary)\n\n # Validate and sanitize link_url\n if not _is_safe_href(link_url):\n # Disallow unsafe href schemes by removing href attribute\n # (Could also replace with '#' or omit link entirely)\n return f'