File size: 448,550 Bytes
8168f10 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 | {"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'<div class=\"badge\" title=\"{title}\"><a href=\"{link_url}\">{summary}</a></div>'\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'<div class=\"badge\" title=\"{safe_title}\">{safe_summary}</div>'\n\n # Escape link_url attribute value\n safe_link_url = html.escape(link_url, quote=True)\n\n return f'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_link_url}\">{safe_summary}</a></div>'\n```"}]}
{"task_id": "pg-train-crypto_secrets-0007", "category": "crypto_secrets", "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 Weak Cryptography, Predictable RNG & Secret Exposure in Logs (CWE-327) 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 hashlib\nimport random\nimport string\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage.\"\"\"\n return hashlib.md5(password.encode(\"utf-8\")).hexdigest()\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n return hash_password(password) == stored_hash\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n alphabet = string.ascii_letters + string.digits\n return \"\".join(random.choices(alphabet, k=32))\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for clinic_intake.\"\"\"\n return f\"service=clinic_intake user={user_id} action={action} api_key={api_key}\"\n```\n"}, {"role": "assistant", "content": "```python\nimport hashlib\nimport secrets\nimport hmac\nimport logging\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage using a strong salted hash (PBKDF2-HMAC-SHA256).\"\"\"\n salt = secrets.token_bytes(16)\n # Use 100,000 iterations recommended by OWASP\n dk = hashlib.pbkdf2_hmac(\"sha256\", password.encode(\"utf-8\"), salt, 100_000)\n # Store salt and hash together, hex-encoded, separated by $\n return f\"{salt.hex()}${dk.hex()}\"\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n try:\n salt_hex, hash_hex = stored_hash.split(\"$\", 1)\n salt = bytes.fromhex(salt_hex)\n expected_hash = bytes.fromhex(hash_hex)\n dk = hashlib.pbkdf2_hmac(\"sha256\", password.encode(\"utf-8\"), salt, 100_000)\n # Use hmac.compare_digest to prevent timing attacks\n return hmac.compare_digest(dk, expected_hash)\n except (ValueError, TypeError):\n return False\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n # secrets.token_urlsafe returns a base64url-encoded string of n bytes\n # 24 bytes ~ 32 chars base64url, so use 24 bytes\n return secrets.token_urlsafe(24)\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for clinic_intake with redacted API key.\"\"\"\n redacted_key = _redact_secret(api_key)\n return f\"service=clinic_intake user={user_id} action={action} api_key={redacted_key}\"\n\n\ndef _redact_secret(secret: str, visible_chars: int = 4) -> str:\n \"\"\"Redact all but the last visible_chars characters of a secret for safe logging.\"\"\"\n if not secret or len(secret) <= visible_chars:\n return \"*\" * len(secret)\n return \"*\" * (len(secret) - visible_chars) + secret[-visible_chars:]\n\n\n# Optional: configure logging to avoid accidental secret exposure\nlogging.basicConfig(\n format=\"%(asctime)s %(levelname)s %(message)s\",\n level=logging.INFO,\n)\n```"}]}
{"task_id": "pg-train-sqli-0008", "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 fetch_shipments(db_path: str, query: str, sort_by: str = \"unit_count\", limit: int = 10) -> list[dict]:\n \"\"\"Search shipments matching query on project_code and return sorted rows.\"\"\"\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, project_code, category_tag, unit_count \"\n f\"FROM shipments \"\n f\"WHERE project_code 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\ndef fetch_shipments(db_path: str, query: str, sort_by: str = \"unit_count\", limit: int = 10) -> list[dict]:\n \"\"\"Search shipments matching query on project_code and return sorted rows.\"\"\"\n # Validate limit\n if not isinstance(limit, int) or limit <= 0:\n raise ValueError(\"limit must be a positive integer\")\n\n # Define allow-list of sortable columns to prevent SQL injection via identifiers\n allowed_sort_columns = {\"id\", \"project_code\", \"category_tag\", \"unit_count\"}\n if sort_by not in allowed_sort_columns:\n raise ValueError(f\"Invalid sort_by column: {sort_by}\")\n\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n # Use parameterized query for user input\n sql = (\n f\"SELECT id, project_code, category_tag, unit_count \"\n f\"FROM shipments \"\n f\"WHERE project_code LIKE ? \"\n f\"ORDER BY {sort_by} DESC \"\n f\"LIMIT ?\"\n )\n # Use parameterized arguments\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-0009", "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 `warehouse_ledger` 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 \"\"\"\n Check if target_path is located within base_dir after resolving symlinks and relative components.\n \"\"\"\n base_dir = os.path.abspath(os.path.realpath(base_dir))\n target_path = os.path.abspath(os.path.realpath(target_path))\n return os.path.commonpath([base_dir]) == os.path.commonpath([base_dir, target_path])\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, preventing path traversal attacks.\n Raises FileNotFoundError or PermissionError if the resolved path is outside base_dir.\n \"\"\"\n target = os.path.join(base_dir, rel_path)\n if not _is_within_directory(base_dir, target):\n raise PermissionError(\"Attempted path traversal detected\")\n with open(target, \"r\", encoding=\"utf-8\") as fh:\n return fh.read()\n```"}]}
{"task_id": "pg-train-cmd_injection-0010", "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\nfrom pathlib import Path\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 # Validate mode against allowlist\n if mode not in ALLOWED_MODES:\n raise ValueError(f\"Invalid mode: {mode!r}. Allowed modes: {sorted(ALLOWED_MODES)}\")\n\n # Resolve script_path to an absolute path and ensure it is a file\n script_path_obj = Path(script_path).resolve(strict=True)\n if not script_path_obj.is_file():\n raise FileNotFoundError(f\"Script path does not point to a file: {script_path_obj}\")\n\n # Construct argument vector without shell=True to avoid command injection\n cmd = [\n sys.executable,\n str(script_path_obj),\n '--mode',\n mode,\n target_name,\n ]\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-0011", "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 `fleet_dispatch` 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 ipaddress\nimport socket\nfrom urllib.parse import urlparse\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 # Validate scheme\n parsed = urlparse(url)\n if parsed.scheme not in (\"http\", \"https\"):\n raise ValueError(\"Unsupported URL scheme\")\n\n # Cheap check for localhost in hostname (exact match or suffix)\n hostname = parsed.hostname\n if hostname is None:\n raise ValueError(\"Invalid URL hostname\")\n\n # Block localhost names explicitly\n if hostname == \"localhost\" or hostname.endswith(\".localhost\"):\n raise ValueError(\"Localhost blocked\")\n\n # Resolve hostname to IPs using provided resolver or default socket.getaddrinfo\n try:\n if resolver is not None:\n ips = resolver(hostname)\n if not isinstance(ips, (list, tuple)) or not all(isinstance(ip, str) for ip in ips):\n raise ValueError(\"Resolver must return list of IP strings\")\n else:\n # getaddrinfo returns list of (family, type, proto, canonname, sockaddr)\n addrs = socket.getaddrinfo(hostname, None)\n ips = [addr[-1][0] for addr in addrs]\n except Exception as e:\n raise ValueError(f\"Hostname resolution failed: {e}\")\n\n # Validate each resolved IP is public (not private, loopback, link-local, multicast, or reserved)\n for ip_str in ips:\n try:\n ip_obj = ipaddress.ip_address(ip_str)\n except ValueError:\n raise ValueError(f\"Invalid IP address resolved: {ip_str}\")\n\n if ip_obj.is_loopback or ip_obj.is_private or ip_obj.is_link_local or ip_obj.is_multicast or ip_obj.is_reserved:\n raise ValueError(f\"Blocked IP address: {ip_str}\")\n\n # Use provided transport or default urllib request\n if transport is not None:\n return transport(url)\n\n with urllib.request.urlopen(url, timeout=5) as resp:\n return resp.read().decode(\"utf-8\")\n```"}]}
{"task_id": "pg-train-idor_auth-0012", "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 `payroll_portal` 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_timesheets_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_timesheets_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 user_role = session.get('role')\n\n if user_id is None:\n raise PermissionError(\"Unauthenticated: user_id missing in session\")\n\n if user_role != 'admin' and record.get('owner_id') != user_id:\n raise PermissionError(\"Access denied: user does not own this record\")\n\n if payload:\n protected_fields = {'id', 'owner_id', 'role', 'is_admin'}\n # Check if payload tries to modify any protected field\n if any(field in payload for field in protected_fields):\n raise PermissionError(\"Modification of protected fields is not allowed\")\n\n # Update only allowed fields\n record.update(payload)\n\n return dict(record)\n```"}]}
{"task_id": "pg-train-xss-0014", "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 `fleet_dispatch` 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'<div class=\"badge\" title=\"{title}\"><a href=\"{link_url}\">{summary}</a></div>'\n```\n"}, {"role": "assistant", "content": "```python\nimport html\nfrom urllib.parse import urlparse\n\n# Allow only safe URL schemes for href attributes\n_ALLOWED_HREF_SCHEMES = frozenset({\"http\", \"https\", \"mailto\", \"tel\", \"ftp\"})\n\ndef _is_safe_href(href: str) -> bool:\n \"\"\"\n Check if the href URL uses a safe scheme.\n \"\"\"\n if not href:\n return False\n parsed = urlparse(href)\n # If no scheme, treat as relative URL, which is safe\n if not parsed.scheme:\n return True\n # Check if scheme is in allowed list (case-insensitive)\n return parsed.scheme.lower() in _ALLOWED_HREF_SCHEMES\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, quote=False)\n\n # Validate and sanitize link_url\n if _is_safe_href(link_url):\n safe_link_url = html.escape(link_url, quote=True)\n else:\n # Unsafe href scheme: render link as plain text without href attribute\n safe_link_url = \"\"\n\n if safe_link_url:\n return f'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_link_url}\">{safe_summary}</a></div>'\n else:\n # No href attribute if link is unsafe\n return f'<div class=\"badge\" title=\"{safe_title}\">{safe_summary}</div>'\n```"}]}
{"task_id": "pg-train-crypto_secrets-0015", "category": "crypto_secrets", "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 Weak Cryptography, Predictable RNG & Secret Exposure in Logs (CWE-327) 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 hashlib\nimport random\nimport string\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage.\"\"\"\n return hashlib.md5(password.encode(\"utf-8\")).hexdigest()\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n return hash_password(password) == stored_hash\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n alphabet = string.ascii_letters + string.digits\n return \"\".join(random.choices(alphabet, k=32))\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for clinic_intake.\"\"\"\n return f\"service=clinic_intake user={user_id} action={action} api_key={api_key}\"\n```\n"}, {"role": "assistant", "content": "```python\nimport hashlib\nimport secrets\nimport hmac\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage using salted SHA-256 with a slow key derivation.\"\"\"\n # Use a fixed salt length and a high iteration count for PBKDF2\n salt = secrets.token_bytes(16)\n # Derive a 32-byte key using PBKDF2-HMAC-SHA256\n dk = hashlib.pbkdf2_hmac(\"sha256\", password.encode(\"utf-8\"), salt, 100_000, dklen=32)\n # Store salt and derived key hex-encoded, separated by $\n return f\"{salt.hex()}${dk.hex()}\"\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n try:\n salt_hex, dk_hex = stored_hash.split(\"$\", 1)\n salt = bytes.fromhex(salt_hex)\n stored_dk = bytes.fromhex(dk_hex)\n except (ValueError, TypeError):\n # Malformed stored_hash\n return False\n # Derive key from provided password using the extracted salt\n derived_dk = hashlib.pbkdf2_hmac(\"sha256\", password.encode(\"utf-8\"), salt, 100_000, dklen=32)\n # Use constant-time comparison to prevent timing attacks\n return hmac.compare_digest(derived_dk, stored_dk)\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n # Use secrets.token_urlsafe to generate a secure token string\n # token_urlsafe(n) returns ~1.3*n characters, so 24 bytes ~ 32 chars\n return secrets.token_urlsafe(24)\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for clinic_intake.\"\"\"\n # Redact the api_key to avoid secret exposure in logs\n redacted_key = (\n api_key[:4] + \"...\" + api_key[-4:] if api_key and len(api_key) > 8 else \"***REDACTED***\"\n )\n return f\"service=clinic_intake user={user_id} action={action} api_key={redacted_key}\"\n```"}]}
{"task_id": "pg-train-sqli-0016", "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 `fleet_dispatch` 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 fetch_appointments(db_path: str, query: str, sort_by: str = \"priority_rank\", limit: int = 10) -> list[dict]:\n \"\"\"Search appointments matching query on project_code and return sorted rows.\"\"\"\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, project_code, category_tag, priority_rank \"\n f\"FROM appointments \"\n f\"WHERE project_code 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 fetch_appointments(db_path: str, query: str, sort_by: str = \"priority_rank\", limit: int = 10) -> list[dict]:\n \"\"\"Search appointments matching query on project_code and return sorted rows.\"\"\"\n allowed_sort_columns = {\"id\", \"project_code\", \"category_tag\", \"priority_rank\"}\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 conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, project_code, category_tag, priority_rank \"\n f\"FROM appointments \"\n f\"WHERE project_code LIKE ? \"\n f\"ORDER BY {sort_by} DESC \"\n f\"LIMIT ?\"\n )\n # Use parameterized query for user inputs\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-0017", "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 retrieve_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 \"\"\"\n Check if target_path is located within base_dir after resolving symlinks and relative components.\n\n Args:\n base_dir: The base directory path.\n target_path: The target file path to check.\n\n Returns:\n True if target_path is inside base_dir, False otherwise.\n \"\"\"\n base_dir_real = os.path.realpath(base_dir)\n target_real = os.path.realpath(target_path)\n return os.path.commonpath([base_dir_real]) == os.path.commonpath([base_dir_real, target_real])\n\n\ndef retrieve_artifact_text(base_dir: str, rel_path: str) -> str:\n \"\"\"\n Read a UTF-8 text file located under base_dir safely, preventing path traversal.\n\n Args:\n base_dir: The base directory under which the file must reside.\n rel_path: The relative path to the file from base_dir.\n\n Returns:\n The contents of the file as a string.\n\n Raises:\n ValueError: If the resolved path is outside the base_dir.\n FileNotFoundError, PermissionError, OSError: Propagated from open().\n \"\"\"\n target = os.path.join(base_dir, rel_path)\n if not _is_within_directory(base_dir, target):\n raise ValueError(\"Access to the requested file is denied: path traversal detected\")\n with open(target, \"r\", encoding=\"utf-8\") as fh:\n return fh.read()\n```"}]}
{"task_id": "pg-train-cmd_injection-0018", "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\nfrom typing import Final\n\n# Allowed modes for the clinic intake tool\nALLOWED_MODES: Final = 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}'. Allowed modes are: {', '.join(ALLOWED_MODES)}\")\n\n # Use argument vector to avoid shell injection\n # subprocess.run with shell=False is default and safer\n cmd = [sys.executable, script_path, \"--mode\", mode, target_name]\n proc = subprocess.run(cmd, capture_output=True, text=True, check=True)\n return proc.stdout.strip()\n```"}]}
{"task_id": "pg-train-ssrf-0019", "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 lookup_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 ipaddress\nimport socket\n\n\ndef lookup_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 # Validate scheme\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 hostnames explicitly\n # Normalize hostname for comparison\n hostname_lower = hostname.lower()\n if hostname_lower in (\"localhost\", \"localhost.localdomain\", \"ip6-localhost\"):\n raise ValueError(\"Localhost blocked\")\n\n # Resolve hostname to IP addresses using resolver or system DNS\n try:\n if resolver is not None:\n ips = resolver(hostname)\n if not ips:\n raise ValueError(\"Hostname resolution returned no IPs\")\n else:\n # Use system DNS resolution, get all addresses (IPv4 and IPv6)\n infos = socket.getaddrinfo(hostname, None)\n ips = list({info[4][0] for info in infos})\n except Exception as e:\n raise ValueError(f\"Failed to resolve hostname: {e}\")\n\n # Check resolved IPs for local, private, or loopback addresses\n for ip_str in ips:\n try:\n ip_obj = ipaddress.ip_address(ip_str)\n except ValueError:\n raise ValueError(f\"Invalid IP address resolved: {ip_str}\")\n if ip_obj.is_loopback or ip_obj.is_private or ip_obj.is_link_local or ip_obj.is_reserved or ip_obj.is_unspecified:\n raise ValueError(f\"Blocked IP address: {ip_str}\")\n\n # If transport is provided, delegate fetching to it\n if transport is not None:\n return transport(url)\n\n # Perform the actual HTTP request with timeout\n with urllib.request.urlopen(url, timeout=5) as resp:\n return resp.read().decode(\"utf-8\")\n```"}]}
{"task_id": "pg-train-idor_auth-0020", "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 `fleet_dispatch` 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 user_role = session.get('role')\n\n if user_id is None:\n raise PermissionError(\"User not authenticated\")\n\n if user_role != 'admin' and user_id != record.get('owner_id'):\n raise PermissionError(\"User not authorized to access this resource\")\n\n if payload is None:\n return dict(record)\n\n # Protected fields that must not be altered\n protected_fields = {'id', 'owner_id', 'role', 'is_admin'}\n\n # Check if payload attempts to modify protected fields\n if any(field in payload for field in protected_fields):\n raise PermissionError(\"Payload attempts to modify protected fields\")\n\n # Update record with allowed fields only\n record.update(payload)\n\n return dict(record)\n```"}]}
{"task_id": "pg-train-unsafe_deser_eval-0021", "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 `fleet_dispatch` 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_fleet_dispatch_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 parse_fleet_dispatch_payload(raw_payload: str) -> Dict[str, Any]:\n \"\"\"\n Decode an incoming serialized message dictionary safely.\n\n Supports JSON-encoded payloads and legacy pickle-hex payloads.\n Raises ValueError if the payload is invalid or not a dict.\n \"\"\"\n if raw_payload.startswith(\"pickle:\"):\n # Legacy pickle payloads are unsafe; disallow deserialization.\n raise ValueError(\"Pickle payloads are not supported for security reasons\")\n try:\n data = json.loads(raw_payload)\n except json.JSONDecodeError as e:\n raise ValueError(f\"Invalid JSON payload: {e}\") from e\n\n if not isinstance(data, dict):\n raise ValueError(\"Payload must decode to a dict\")\n return data\n```"}]}
{"task_id": "pg-train-xss-0022", "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 `fleet_dispatch` 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_timesheets_badge(title: str, summary: str, link_url: str) -> str:\n \"\"\"Render an HTML card badge with title, summary, and external link.\"\"\"\n return f'<div class=\"badge\" title=\"{title}\"><a href=\"{link_url}\">{summary}</a></div>'\n```\n"}, {"role": "assistant", "content": "```python\nimport html\nfrom urllib.parse import urlparse\n\n# Allowed URL schemes for href to prevent unsafe schemes like javascript:\n_ALLOWED_HREF_SCHEMES = frozenset({\"http\", \"https\", \"mailto\", \"ftp\", \"tel\"})\n\ndef render_timesheets_badge(title: str, summary: str, link_url: str) -> str:\n \"\"\"Render an HTML card badge with title, summary, and external link.\n \n Escapes HTML special characters in title and summary to prevent XSS.\n Validates the link_url scheme against an allow-list to prevent unsafe href schemes.\n If the scheme is not allowed, the href attribute is omitted.\n \"\"\"\n safe_title = html.escape(title, quote=True)\n safe_summary = html.escape(summary, quote=False) # summary is link text, allow quotes but escape <>&\n \n # Parse and validate URL scheme\n parsed_url = urlparse(link_url)\n if parsed_url.scheme.lower() in _ALLOWED_HREF_SCHEMES:\n safe_href = html.escape(link_url, quote=True)\n href_part = f' href=\"{safe_href}\"'\n else:\n # Unsafe or missing scheme: omit href attribute to avoid unsafe links\n href_part = \"\"\n \n return f'<div class=\"badge\" title=\"{safe_title}\"><a{href_part}>{safe_summary}</a></div>'\n```"}]}
{"task_id": "pg-train-sqli-0024", "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 `warehouse_ledger` 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 retrieve_appointments(db_path: str, query: str, sort_by: str = \"unit_count\", limit: int = 10) -> list[dict]:\n \"\"\"Search appointments matching query on project_code and return sorted rows.\"\"\"\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, project_code, category_tag, unit_count \"\n f\"FROM appointments \"\n f\"WHERE project_code 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 retrieve_appointments(db_path: str, query: str, sort_by: str = \"unit_count\", limit: int = 10) -> list[dict]:\n \"\"\"Search appointments matching query on project_code and return sorted rows.\"\"\"\n allowed_sort_columns = {\"id\", \"project_code\", \"category_tag\", \"unit_count\"}\n if sort_by not in allowed_sort_columns:\n raise ValueError(f\"Invalid sort_by value: {sort_by!r}\")\n\n try:\n limit = int(limit)\n except Exception as e:\n raise ValueError(f\"Invalid limit value: {limit!r}\") from e\n if limit <= 0:\n raise ValueError(\"limit must be a positive integer\")\n\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, project_code, category_tag, unit_count \"\n f\"FROM appointments \"\n f\"WHERE project_code LIKE ? \"\n f\"ORDER BY {sort_by} DESC \"\n f\"LIMIT ?\"\n )\n # Use parameterized query for user inputs to prevent SQL injection\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-0025", "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 `payroll_portal` 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 query_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 \"\"\"\n Check if the target_path is located within the base_dir after resolving symbolic links and relative paths.\n \"\"\"\n base_dir_real = os.path.realpath(base_dir)\n target_real = os.path.realpath(target_path)\n return os.path.commonpath([base_dir_real]) == os.path.commonpath([base_dir_real, target_real])\n\n\ndef query_artifact_text(base_dir: str, rel_path: str) -> str:\n \"\"\"Read a UTF-8 text file located under base_dir, preventing path traversal.\"\"\"\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 base_dir\")\n with open(target, \"r\", encoding=\"utf-8\") as fh:\n return fh.read()\n```"}]}
{"task_id": "pg-train-cmd_injection-0026", "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 `fleet_dispatch` 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_fleet_dispatch_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\nfrom typing import Final\n\n# Allowed modes for the fleet dispatch tool\nALLOWED_MODES: Final = frozenset({\"summary\", \"verify\"})\n\n\ndef run_fleet_dispatch_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 # Construct argument vector to avoid shell injection\n cmd = [sys.executable, script_path, \"--mode\", mode, target_name]\n\n # Use subprocess.run with shell=False and argument vector\n proc = subprocess.run(cmd, capture_output=True, text=True, check=True)\n return proc.stdout.strip()\n```"}]}
{"task_id": "pg-train-ssrf-0027", "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 retrieve_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 retrieve_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 # Validate scheme\n parsed = urllib.parse.urlparse(url)\n if parsed.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 # Use canonical hostname lowercase for comparison\n hostname_lower = hostname.lower()\n if hostname_lower in (\"localhost\", \"localhost.localdomain\", \"ip6-localhost\"):\n raise ValueError(\"Localhost blocked\")\n\n # Resolve hostname to IPs using provided resolver or default\n try:\n if resolver is not None:\n ip_strs = resolver(hostname)\n if not isinstance(ip_strs, (list, tuple)) or not all(isinstance(ip, str) for ip in ip_strs):\n raise ValueError(\"Resolver must return list[str]\")\n else:\n # Use getaddrinfo to get all IP addresses for hostname\n addrinfo = socket.getaddrinfo(hostname, None)\n ip_strs = list({ai[4][0] for ai in addrinfo})\n except Exception as e:\n raise ValueError(f\"Hostname resolution failed: {e}\")\n\n # Validate resolved IPs are public routable addresses\n for ip_str in ip_strs:\n try:\n ip_obj = ipaddress.ip_address(ip_str)\n except ValueError:\n raise ValueError(f\"Invalid IP address resolved: {ip_str}\")\n\n if ip_obj.is_loopback or ip_obj.is_private or ip_obj.is_link_local or ip_obj.is_reserved or ip_obj.is_multicast:\n raise ValueError(f\"Resolved IP address not allowed: {ip_str}\")\n\n # If transport is provided, use it (assumed safe)\n if transport is not None:\n return transport(url)\n\n # Default fetch with urllib.request.urlopen\n with urllib.request.urlopen(url, timeout=5) as resp:\n return resp.read().decode(\"utf-8\")\n```"}]}
{"task_id": "pg-train-idor_auth-0028", "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 `fleet_dispatch` 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_vehicles_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_vehicles_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 in store\")\n\n record = store[resource_id]\n\n # Authorization check: user must be owner or admin\n user_id = session.get('user_id')\n user_role = session.get('role')\n if user_id is None:\n raise PermissionError(\"User not authenticated\")\n if not (user_id == record.get('owner_id') or user_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(f\"Modification of protected fields {protected_fields} is not allowed\")\n\n # Update record safely\n record.update(payload)\n\n return dict(record)\n```"}]}
{"task_id": "pg-train-crypto_secrets-0031", "category": "crypto_secrets", "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 Weak Cryptography, Predictable RNG & Secret Exposure in Logs (CWE-327) 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 hashlib\nimport random\nimport string\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage.\"\"\"\n return hashlib.md5(password.encode(\"utf-8\")).hexdigest()\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n return hash_password(password) == stored_hash\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n alphabet = string.ascii_letters + string.digits\n return \"\".join(random.choices(alphabet, k=32))\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for warehouse_ledger.\"\"\"\n return f\"service=warehouse_ledger user={user_id} action={action} api_key={api_key}\"\n```\n"}, {"role": "assistant", "content": "```python\nimport hashlib\nimport secrets\nimport hmac\nimport html\n\n\n# Constants for PBKDF2\n_PBKDF2_ITERATIONS = 100_000\n_SALT_LENGTH = 16 # bytes\n_HASH_NAME = \"sha256\"\n_DERIVED_KEY_LENGTH = 32 # bytes\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage using PBKDF2 with a random salt.\"\"\"\n salt = secrets.token_bytes(_SALT_LENGTH)\n dk = hashlib.pbkdf2_hmac(\n _HASH_NAME,\n password.encode(\"utf-8\"),\n salt,\n _PBKDF2_ITERATIONS,\n dklen=_DERIVED_KEY_LENGTH,\n )\n # Store as hex: salt + derived key, separated by $\n return f\"{salt.hex()}${dk.hex()}\"\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n try:\n salt_hex, dk_hex = stored_hash.split(\"$\", 1)\n salt = bytes.fromhex(salt_hex)\n stored_dk = bytes.fromhex(dk_hex)\n except (ValueError, TypeError):\n # Malformed stored hash\n return False\n\n derived_key = hashlib.pbkdf2_hmac(\n _HASH_NAME,\n password.encode(\"utf-8\"),\n salt,\n _PBKDF2_ITERATIONS,\n dklen=len(stored_dk),\n )\n # Use hmac.compare_digest to prevent timing attacks\n return hmac.compare_digest(derived_key, stored_dk)\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n # Generate 24 random bytes and encode as 48-character hex string (each byte = 2 hex chars)\n # 48 chars > 32 chars requirement\n return secrets.token_hex(24)\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for warehouse_ledger with safe escaping and redaction.\"\"\"\n # Redact api_key except last 4 chars if longer than 8 chars, else redact fully\n if len(api_key) > 8:\n redacted_key = \"*\" * (len(api_key) - 4) + api_key[-4:]\n else:\n redacted_key = \"*\" * len(api_key)\n\n # Escape user_id and action for safe logging (avoid injection issues)\n safe_user_id = html.escape(user_id, quote=True)\n safe_action = html.escape(action, quote=True)\n\n return f\"service=warehouse_ledger user={safe_user_id} action={safe_action} api_key={redacted_key}\"\n```"}]}
{"task_id": "pg-train-sqli-0032", "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 retrieve_timesheets(db_path: str, query: str, sort_by: str = \"unit_count\", limit: int = 10) -> list[dict]:\n \"\"\"Search timesheets 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 timesheets \"\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 retrieve_timesheets(db_path: str, query: str, sort_by: str = \"unit_count\", limit: int = 10) -> list[dict]:\n \"\"\"Search timesheets 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 query for query and limit, and whitelist sort_by\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 timesheets \"\n f\"WHERE visit_reason LIKE ? \"\n f\"ORDER BY {sort_by} DESC \"\n f\"LIMIT ?\"\n )\n # Use parameterized inputs with wildcards included in parameter\n param_query = f\"%{query}%\"\n rows = conn.execute(sql, (param_query, limit)).fetchall()\n return [dict(r) for r in rows]\n finally:\n conn.close()\n```"}]}
{"task_id": "pg-train-path_traversal-0033", "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 `clinic_intake` 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 lookup_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 \"\"\"\n Check if target_path is located within base_dir after resolving symlinks and relative components.\n \"\"\"\n base_dir_real = os.path.realpath(base_dir)\n target_real = os.path.realpath(target_path)\n return os.path.commonpath([base_dir_real]) == os.path.commonpath([base_dir_real, target_real])\n\n\ndef lookup_artifact_text(base_dir: str, rel_path: str) -> str:\n \"\"\"\n Read a UTF-8 text file located under base_dir, ensuring no path traversal outside base_dir.\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 of base_dir is not allowed\")\n with open(target, \"r\", encoding=\"utf-8\") as fh:\n return fh.read()\n```"}]}
{"task_id": "pg-train-cmd_injection-0034", "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 `fleet_dispatch` 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_fleet_dispatch_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\nimport os\n\n# Allowed modes for the fleet dispatch tool\n_ALLOWED_MODES = frozenset({\"summary\", \"verify\"})\n\ndef run_fleet_dispatch_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\n This function uses a safe subprocess call with argument vector to prevent OS command injection.\n It also validates mode against an allowlist and ensures script_path is a file.\n \"\"\"\n if mode not in _ALLOWED_MODES:\n raise ValueError(f\"Invalid mode: {mode!r}. Allowed modes: {_ALLOWED_MODES}\")\n\n # Resolve and validate script_path is a file\n script_path = os.path.abspath(script_path)\n if not os.path.isfile(script_path):\n raise FileNotFoundError(f\"Script path does not exist or is not a file: {script_path}\")\n\n # Construct argument vector without shell=True to prevent injection\n cmd = [sys.executable, script_path, \"--mode\", mode, target_name]\n\n proc = subprocess.run(cmd, capture_output=True, text=True, check=True)\n return proc.stdout.strip()\n```"}]}
{"task_id": "pg-train-ssrf-0035", "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 `fleet_dispatch` 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 query_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 ipaddress\nimport socket\nfrom urllib.parse import urlparse\n\n\ndef query_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 # Validate scheme early\n parsed = 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 hostname is None:\n raise ValueError(\"URL must have a hostname\")\n\n # Block localhost and loopback names explicitly\n # Normalize hostname for comparison\n hostname_lower = hostname.lower()\n if hostname_lower in {\"localhost\", \"ip6-localhost\"}:\n raise ValueError(\"Localhost blocked\")\n\n # Resolve IP addresses using provided resolver or default DNS\n if resolver is not None:\n try:\n ips = resolver(hostname)\n except Exception as e:\n raise ValueError(f\"Hostname resolution failed: {e}\") from e\n else:\n try:\n # getaddrinfo returns tuples with address info, extract IPs\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\"Hostname resolution failed: {e}\") from e\n\n # Validate each resolved IP to prevent SSRF to private/local IPs\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\n if ip.is_loopback or ip.is_link_local or ip.is_private or ip.is_reserved or ip.is_multicast:\n raise ValueError(f\"Blocked IP address: {ip_str}\")\n\n # If transport override is provided, use it (assumed safe)\n if transport is not None:\n return transport(url)\n\n # Perform the actual fetch with a timeout\n with urllib.request.urlopen(url, timeout=5) as resp:\n return resp.read().decode(\"utf-8\")\n```"}]}
{"task_id": "pg-train-idor_auth-0036", "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 `clinic_intake` 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 does not exist\")\n\n record = store[resource_id]\n\n user_id = session.get('user_id')\n user_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 user_role != 'admin' and record.get('owner_id') != user_id:\n raise PermissionError(\"User not authorized to access this record\")\n\n if payload is not None:\n # Disallow updates to 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(\"Payload attempts to modify protected fields\")\n\n # Update record with safe payload\n record.update(payload)\n\n return dict(record)\n```"}]}
{"task_id": "pg-train-unsafe_deser_eval-0037", "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_literal(raw: str) -> Any:\n \"\"\"Safely evaluate a string literal to a Python object using json.loads.\"\"\"\n try:\n return json.loads(raw)\n except json.JSONDecodeError as e:\n raise ValueError(f\"Payload is not valid JSON: {e}\") from e\n\n\ndef parse_clinic_intake_payload(raw_payload: str) -> Dict:\n \"\"\"\n Decode an incoming serialized message dictionary.\n\n Supports only JSON-encoded dicts or hex-encoded pickled dicts.\n Pickle deserialization is allowed only if the payload starts with 'pickle:' prefix.\n \"\"\"\n if raw_payload.startswith(\"pickle:\"):\n # Restrict pickle loading to only dict objects to mitigate code execution risk.\n # Use pickle.Unpickler with a restricted find_class to prevent arbitrary code execution.\n import pickle\n\n class RestrictedUnpickler(pickle.Unpickler):\n def find_class(self, module: str, name: str) -> Any:\n # Only allow built-in dict type\n if module == \"builtins\" and name == \"dict\":\n return dict\n raise pickle.UnpicklingError(f\"Global '{module}.{name}' is forbidden\")\n\n try:\n data = RestrictedUnpickler(\n io.BytesIO(bytes.fromhex(raw_payload[7:]))\n ).load()\n except Exception as e:\n raise ValueError(f\"Invalid pickle payload: {e}\") from e\n else:\n data = _safe_eval_literal(raw_payload)\n\n if not isinstance(data, dict):\n raise ValueError(\"Payload must decode to a dict\")\n return data\n```"}]}
{"task_id": "pg-train-xss-0038", "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_shipments_badge(title: str, summary: str, link_url: str) -> str:\n \"\"\"Render an HTML card badge with title, summary, and external link.\"\"\"\n return f'<div class=\"badge\" title=\"{title}\"><a href=\"{link_url}\">{summary}</a></div>'\n```\n"}, {"role": "assistant", "content": "```python\nimport html\nfrom urllib.parse import urlparse\n\n# Allowed URL schemes for href attribute\nALLOWED_HREF_SCHEMES = frozenset({'http', 'https', 'mailto', 'tel'})\n\ndef render_shipments_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 # Parse and validate the URL scheme\n parsed_url = urlparse(link_url)\n if parsed_url.scheme.lower() not in ALLOWED_HREF_SCHEMES:\n # If scheme is not allowed, render without href to avoid unsafe links\n return f'<div class=\"badge\" title=\"{safe_title}\">{safe_summary}</div>'\n\n # Escape the URL for safe inclusion in href attribute\n # Although urlparse ensures scheme, we still escape to prevent injection\n safe_link_url = html.escape(link_url, quote=True)\n\n return f'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_link_url}\">{safe_summary}</a></div>'\n```"}]}
{"task_id": "pg-train-crypto_secrets-0039", "category": "crypto_secrets", "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 Weak Cryptography, Predictable RNG & Secret Exposure in Logs (CWE-327) 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 hashlib\nimport random\nimport string\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage.\"\"\"\n return hashlib.md5(password.encode(\"utf-8\")).hexdigest()\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n return hash_password(password) == stored_hash\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n alphabet = string.ascii_letters + string.digits\n return \"\".join(random.choices(alphabet, k=32))\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for payroll_portal.\"\"\"\n return f\"service=payroll_portal user={user_id} action={action} api_key={api_key}\"\n```\n"}, {"role": "assistant", "content": "```python\nimport hashlib\nimport secrets\nimport hmac\nimport logging\n\n# Use a secure password hashing scheme with salt and slow hashing (PBKDF2-HMAC-SHA256)\n# Constants for PBKDF2\n_PBKDF2_ITERATIONS = 100_000\n_SALT_LENGTH = 16 # bytes\n_HASH_LENGTH = 32 # bytes\n\nlogger = logging.getLogger(__name__)\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage using PBKDF2-HMAC-SHA256 with a random salt.\"\"\"\n if not isinstance(password, str):\n raise TypeError(\"Password must be a string\")\n salt = secrets.token_bytes(_SALT_LENGTH)\n dk = hashlib.pbkdf2_hmac(\n 'sha256',\n password.encode('utf-8'),\n salt,\n _PBKDF2_ITERATIONS,\n dklen=_HASH_LENGTH\n )\n # Store as hex: iterations$salt_hex$hash_hex\n return f\"{_PBKDF2_ITERATIONS}${salt.hex()}${dk.hex()}\"\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n if not isinstance(password, str) or not isinstance(stored_hash, str):\n return False\n try:\n iterations_str, salt_hex, hash_hex = stored_hash.split('$')\n iterations = int(iterations_str)\n salt = bytes.fromhex(salt_hex)\n expected_hash = bytes.fromhex(hash_hex)\n except (ValueError, TypeError):\n return False\n\n dk = hashlib.pbkdf2_hmac(\n 'sha256',\n password.encode('utf-8'),\n salt,\n iterations,\n dklen=len(expected_hash)\n )\n # Use hmac.compare_digest to prevent timing attacks\n return hmac.compare_digest(dk, expected_hash)\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n # Use secrets.token_urlsafe to generate a secure token string\n # token_urlsafe(n) returns a string with about 4/3 * n bytes, so 24 bytes ~ 32 chars\n token = secrets.token_urlsafe(24)\n # Ensure token length is at least 32 characters, pad if needed (unlikely)\n if len(token) < 32:\n # Generate additional secure random characters from urlsafe alphabet\n extra = secrets.token_urlsafe(32 - len(token))\n token += extra\n return token\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for payroll_portal, redacting sensitive api_key.\"\"\"\n # Redact api_key except last 4 chars for security\n if not isinstance(api_key, str):\n redacted_key = \"<invalid_api_key>\"\n elif len(api_key) <= 4:\n redacted_key = \"*\" * len(api_key)\n else:\n redacted_key = \"*\" * (len(api_key) - 4) + api_key[-4:]\n # Escape user_id and action minimally (replace whitespace with underscores)\n safe_user_id = user_id.replace(\" \", \"_\") if isinstance(user_id, str) else \"<invalid_user_id>\"\n safe_action = action.replace(\" \", \"_\") if isinstance(action, str) else \"<invalid_action>\"\n return f\"service=payroll_portal user={safe_user_id} action={safe_action} api_key={redacted_key}\"\n```"}]}
{"task_id": "pg-train-sqli-0040", "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 `clinic_intake` 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 lookup_vehicles(db_path: str, query: str, sort_by: str = \"unit_count\", limit: int = 10) -> list[dict]:\n \"\"\"Search vehicles matching query on manifest_note and return sorted rows.\"\"\"\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, manifest_note, category_tag, unit_count \"\n f\"FROM vehicles \"\n f\"WHERE manifest_note 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 lookup_vehicles(db_path: str, query: str, sort_by: str = \"unit_count\", limit: int = 10) -> list[dict]:\n \"\"\"Search vehicles matching query on manifest_note and return sorted rows.\"\"\"\n # Validate sort_by against an allow-list of valid column names to prevent SQL injection\n allowed_sort_columns = {\"id\", \"manifest_note\", \"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 # Validate limit is a positive integer\n if not isinstance(limit, int) or limit <= 0:\n raise ValueError(\"limit must be a positive integer\")\n\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n # Use parameterized query for the LIKE clause\n sql = (\n f\"SELECT id, manifest_note, category_tag, unit_count \"\n f\"FROM vehicles \"\n f\"WHERE manifest_note LIKE ? \"\n f\"ORDER BY {sort_by} DESC \"\n f\"LIMIT ?\"\n )\n # Prepare parameters: wrap query with % for LIKE pattern\n params = (f\"%{query}%\", limit)\n rows = conn.execute(sql, params).fetchall()\n return [dict(r) for r in rows]\n finally:\n conn.close()\n```"}]}
{"task_id": "pg-train-path_traversal-0041", "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 `payroll_portal` 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\nfrom typing import Optional\n\n\ndef _canonicalize_and_validate_path(base_dir: str, rel_path: str) -> Optional[str]:\n \"\"\"\n Resolve the canonical absolute path of the target file and ensure it is confined within base_dir.\n\n Args:\n base_dir: The base directory under which the file must reside.\n rel_path: The relative path to the target file.\n\n Returns:\n The canonical absolute path if valid and confined within base_dir; otherwise, None.\n \"\"\"\n base_dir_abs = os.path.abspath(base_dir)\n target_path = os.path.abspath(os.path.join(base_dir_abs, rel_path))\n if os.path.commonpath([base_dir_abs, target_path]) != base_dir_abs:\n return None\n return target_path\n\n\ndef fetch_artifact_text(base_dir: str, rel_path: str) -> str:\n \"\"\"Read a UTF-8 text file located under base_dir, preventing path traversal.\"\"\"\n target = _canonicalize_and_validate_path(base_dir, rel_path)\n if target is None:\n raise ValueError(\"Invalid file path: path traversal detected\")\n with open(target, \"r\", encoding=\"utf-8\") as fh:\n return fh.read()\n```"}]}
{"task_id": "pg-train-cmd_injection-0042", "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 `fleet_dispatch` 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_fleet_dispatch_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\nfrom pathlib import Path\n\n# Allowed modes for the fleet dispatch tool\nALLOWED_MODES = frozenset({\"summary\", \"verify\"})\n\ndef run_fleet_dispatch_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 # Validate mode against allowlist\n if mode not in ALLOWED_MODES:\n raise ValueError(f\"Invalid mode: {mode!r}. Allowed modes are: {sorted(ALLOWED_MODES)}\")\n\n # Canonicalize and confine script_path to local filesystem (prevent path traversal or unexpected locations)\n script_path_obj = Path(script_path).resolve(strict=True)\n # Optional: enforce script_path is within a trusted directory, e.g., current working directory or a known base path\n # Here, we just ensure it is an absolute resolved path to avoid surprises\n\n # Construct argument vector without shell=True to prevent command injection\n cmd = [\n sys.executable,\n str(script_path_obj),\n \"--mode\",\n mode,\n target_name,\n ]\n\n proc = subprocess.run(cmd, capture_output=True, text=True, check=True)\n return proc.stdout.strip()\n```"}]}
{"task_id": "pg-train-ssrf-0043", "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 `fleet_dispatch` 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 retrieve_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 ipaddress\nimport socket\n\n\ndef retrieve_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 # Validate scheme cheaply\n parsed = urllib.parse.urlparse(url)\n if parsed.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 loopback, link-local, multicast, private ranges\n # Resolve hostname to IPs using provided resolver or system resolver\n try:\n if resolver is not None:\n ips = resolver(hostname)\n if not isinstance(ips, (list, tuple)) or not all(isinstance(ip, str) for ip in ips):\n raise ValueError(\"Resolver must return list of IP strings\")\n else:\n # Use system DNS resolver\n infos = socket.getaddrinfo(hostname, None)\n ips = [info[4][0] for info in infos]\n except Exception as e:\n raise ValueError(f\"Hostname resolution failed: {e}\")\n\n # Check each resolved IP for disallowed addresses\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\n if ip.is_loopback:\n raise ValueError(\"Loopback IP addresses are blocked\")\n if ip.is_link_local:\n raise ValueError(\"Link-local IP addresses are blocked\")\n if ip.is_multicast:\n raise ValueError(\"Multicast IP addresses are blocked\")\n if ip.is_private:\n # Optional: block private IPs to prevent SSRF to internal networks\n raise ValueError(\"Private IP addresses are blocked\")\n if ip.is_reserved:\n raise ValueError(\"Reserved IP addresses are blocked\")\n if ip.is_unspecified:\n raise ValueError(\"Unspecified IP addresses are blocked\")\n\n # Block explicit localhost hostname variants (case-insensitive)\n if hostname.lower() in {\"localhost\", \"localhost.\"}:\n raise ValueError(\"Localhost hostname is blocked\")\n\n # If transport is provided, use it (assumed safe)\n if transport is not None:\n return transport(url)\n\n # Perform the HTTP request with timeout\n with urllib.request.urlopen(url, timeout=5) as resp:\n return resp.read().decode(\"utf-8\")\n```"}]}
{"task_id": "pg-train-idor_auth-0044", "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 `payroll_portal` 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_appointments_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_appointments_record(store: dict, session: dict, resource_id: str, payload: dict | None = None) -> dict:\n \"\"\"\n Read or update a record in store.\n Caller must have session['user_id'] matching record['owner_id'] or session.get('role') == 'admin'.\n Payload must not alter protected fields (id, owner_id, role, is_admin).\n \n Raises:\n KeyError: if resource_id not in store.\n PermissionError: if caller is not authorized to access or modify the record.\n ValueError: if payload attempts to modify protected fields.\n \"\"\"\n if resource_id not in store:\n raise KeyError(f\"Resource ID {resource_id} not found\")\n\n record = store[resource_id]\n\n user_id = session.get('user_id')\n user_role = session.get('role')\n\n # Authorization check: user must be owner or admin\n if user_id != record.get('owner_id') and user_role != 'admin':\n raise PermissionError(\"User not authorized to access this record\")\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 ValueError(f\"Modification of protected fields {protected_fields} is not allowed\")\n\n # Update record only with allowed fields\n record.update(payload)\n\n return dict(record)\n```"}]}
{"task_id": "pg-train-xss-0046", "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 `fleet_dispatch` 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_timesheets_badge(title: str, summary: str, link_url: str) -> str:\n \"\"\"Render an HTML card badge with title, summary, and external link.\"\"\"\n return f'<div class=\"badge\" title=\"{title}\"><a href=\"{link_url}\">{summary}</a></div>'\n```\n"}, {"role": "assistant", "content": "```python\nimport html\nfrom urllib.parse import urlparse\n\n# Allow only safe URL schemes for href attributes to prevent XSS via javascript: or data: URIs.\n_ALLOWED_HREF_SCHEMES = frozenset({\"http\", \"https\", \"mailto\", \"ftp\", \"tel\"})\n\ndef render_timesheets_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 injection of HTML or scripts.\n safe_title = html.escape(title, quote=True)\n safe_summary = html.escape(summary)\n\n # Parse and validate the link_url scheme.\n parsed_url = urlparse(link_url)\n if parsed_url.scheme.lower() not in _ALLOWED_HREF_SCHEMES:\n # If scheme is not allowed, render link text without href to avoid unsafe navigation.\n return f'<div class=\"badge\" title=\"{safe_title}\"><span>{safe_summary}</span></div>'\n\n # Escape the link_url for safe inclusion in href attribute.\n # href attribute values should be escaped for quotes and ampersands.\n safe_link_url = html.escape(link_url, quote=True)\n\n return f'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_link_url}\">{safe_summary}</a></div>'\n```"}]}
{"task_id": "pg-train-sqli-0048", "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 `warehouse_ledger` 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 project_code and return sorted rows.\"\"\"\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, project_code, category_tag, unit_count \"\n f\"FROM shipments \"\n f\"WHERE project_code 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\ndef query_shipments(db_path: str, query: str, sort_by: str = \"unit_count\", limit: int = 10) -> list[dict]:\n \"\"\"Search shipments matching query on project_code and return sorted rows.\"\"\"\n allowed_sort_columns = {\"id\", \"project_code\", \"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 try:\n limit_int = int(limit)\n except (ValueError, TypeError):\n raise ValueError(\"limit must be an integer\")\n\n if limit_int <= 0:\n raise ValueError(\"limit must be positive\")\n\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, project_code, category_tag, unit_count \"\n f\"FROM shipments \"\n f\"WHERE project_code LIKE ? \"\n f\"ORDER BY {sort_by} DESC \"\n f\"LIMIT ?\"\n )\n # Use parameterized queries for user input\n rows = conn.execute(sql, (f\"%{query}%\", limit_int)).fetchall()\n return [dict(r) for r in rows]\n finally:\n conn.close()\n```"}]}
{"task_id": "pg-train-path_traversal-0049", "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 `payroll_portal` 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 query_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_real = os.path.realpath(base_dir)\n target_path_real = os.path.realpath(target_path)\n common_path = os.path.commonpath([base_dir_real, target_path_real])\n return common_path == base_dir_real\n\n\ndef query_artifact_text(base_dir: str, rel_path: str) -> str:\n \"\"\"\n Read a UTF-8 text file located under base_dir, preventing path traversal attacks.\n\n Raises:\n FileNotFoundError: If the resolved path is outside base_dir or the file does not exist.\n OSError: For other OS-related errors.\n \"\"\"\n target = os.path.join(base_dir, rel_path)\n if not _is_within_directory(base_dir, target):\n raise FileNotFoundError(\"Attempted Path Traversal outside base directory\")\n with open(target, \"r\", encoding=\"utf-8\") as fh:\n return fh.read()\n```"}]}
{"task_id": "pg-train-cmd_injection-0050", "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 `fleet_dispatch` 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_fleet_dispatch_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 fleet dispatch tool\nALLOWED_MODES = frozenset({'summary', 'verify'})\n\ndef run_fleet_dispatch_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 # Construct argument list to avoid shell=True and prevent command injection\n cmd = [sys.executable, script_path, '--mode', mode, target_name]\n\n proc = subprocess.run(cmd, capture_output=True, text=True, check=True)\n return proc.stdout.strip()\n```"}]}
{"task_id": "pg-train-ssrf-0051", "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 `payroll_portal` 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 lookup_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 lookup_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 # Validate scheme first (cheap)\n parsed = urllib.parse.urlparse(url)\n if parsed.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 # Use canonical form for hostname to avoid tricks\n # Reject if hostname is localhost or resolves to loopback/localhost IPs\n\n # Cheap check on hostname string\n if hostname.lower() == \"localhost\":\n raise ValueError(\"Localhost blocked\")\n\n # Resolve hostname to IPs using provided resolver or default\n try:\n if resolver is not None:\n ips = resolver(hostname)\n if not isinstance(ips, (list, tuple)) or not all(isinstance(ip, str) for ip in ips):\n raise ValueError(\"Resolver must return list of IP strings\")\n else:\n # Use socket.getaddrinfo to get all IPs (both IPv4 and IPv6)\n infos = socket.getaddrinfo(hostname, None, proto=socket.IPPROTO_TCP)\n ips = []\n for info in infos:\n sockaddr = info[4]\n ip = sockaddr[0]\n ips.append(ip)\n except Exception as e:\n raise ValueError(f\"Failed to resolve hostname: {e}\")\n\n # Validate each resolved IP is not loopback, link-local, multicast, or private ranges\n for ip_str in ips:\n try:\n ip_obj = ipaddress.ip_address(ip_str)\n except ValueError:\n raise ValueError(f\"Invalid IP address resolved: {ip_str}\")\n\n if ip_obj.is_loopback:\n raise ValueError(f\"Resolved IP {ip_str} is loopback, blocked\")\n if ip_obj.is_link_local:\n raise ValueError(f\"Resolved IP {ip_str} is link-local, blocked\")\n if ip_obj.is_multicast:\n raise ValueError(f\"Resolved IP {ip_str} is multicast, blocked\")\n # Optionally block private IPs (RFC1918, RFC4193)\n # This depends on policy; here we block private IPs to prevent SSRF to internal network\n if ip_obj.is_private:\n raise ValueError(f\"Resolved IP {ip_str} is private, blocked\")\n\n # All checks passed, perform fetch\n if transport is not None:\n return transport(url)\n\n with urllib.request.urlopen(url, timeout=5) as resp:\n return resp.read().decode(\"utf-8\")\n```"}]}
{"task_id": "pg-train-idor_auth-0052", "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_appointments_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_appointments_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 does not exist.\")\n record = store[resource_id]\n\n user_id = session.get('user_id')\n user_role = session.get('role')\n\n if user_id is None:\n raise PermissionError(\"User not authenticated.\")\n\n # Verify access control: user must be owner or admin\n if user_role != 'admin' and record.get('owner_id') != user_id:\n raise PermissionError(\"User not authorized to access this resource.\")\n\n if payload:\n # Disallow changes to 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(f\"Modification of protected fields {protected_fields} is not allowed.\")\n\n # Update record with allowed fields only\n record.update(payload)\n\n return dict(record)\n```"}]}
{"task_id": "pg-train-unsafe_deser_eval-0053", "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 `payroll_portal` 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_payroll_portal_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_literal(raw: str) -> Any:\n \"\"\"Safely parse a string literal to a Python object using json.loads.\"\"\"\n try:\n return json.loads(raw)\n except json.JSONDecodeError as e:\n raise ValueError(\"Payload must be valid JSON\") from e\n\n\ndef parse_payroll_portal_payload(raw_payload: str) -> Dict:\n \"\"\"\n Decode an incoming serialized message dictionary.\n\n Supports JSON-encoded payloads only.\n Raises ValueError if the payload is invalid or does not decode to a dict.\n \"\"\"\n if raw_payload.startswith(\"pickle:\"):\n # Reject pickle deserialization to prevent unsafe code execution\n raise ValueError(\"Pickle deserialization is disallowed for security reasons\")\n data = _safe_eval_literal(raw_payload)\n if not isinstance(data, dict):\n raise ValueError(\"Payload must decode to a dict\")\n return data\n```"}]}
{"task_id": "pg-train-xss-0054", "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 `payroll_portal` 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_timesheets_badge(title: str, summary: str, link_url: str) -> str:\n \"\"\"Render an HTML card badge with title, summary, and external link.\"\"\"\n return f'<div class=\"badge\" title=\"{title}\"><a href=\"{link_url}\">{summary}</a></div>'\n```\n"}, {"role": "assistant", "content": "```python\nimport html\nfrom urllib.parse import urlparse\n\n# Allowed URL schemes for href attribute to prevent unsafe schemes like javascript:\nALLOWED_HREF_SCHEMES = frozenset({\"http\", \"https\", \"mailto\", \"ftp\", \"tel\"})\n\ndef render_timesheets_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 # Parse and validate the URL scheme\n parsed_url = urlparse(link_url)\n if parsed_url.scheme.lower() not in ALLOWED_HREF_SCHEMES:\n # If scheme is not allowed, do not render a clickable link; render summary as plain text\n return f'<div class=\"badge\" title=\"{safe_title}\">{safe_summary}</div>'\n\n # Escape the URL to prevent injection in href attribute\n safe_link_url = html.escape(link_url, quote=True)\n\n return f'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_link_url}\">{safe_summary}</a></div>'\n```"}]}
{"task_id": "pg-train-sqli-0056", "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 `warehouse_ledger` 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 retrieve_timesheets(db_path: str, query: str, sort_by: str = \"unit_count\", limit: int = 10) -> list[dict]:\n \"\"\"Search timesheets matching query on project_code and return sorted rows.\"\"\"\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, project_code, category_tag, unit_count \"\n f\"FROM timesheets \"\n f\"WHERE project_code 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 retrieve_timesheets(db_path: str, query: str, sort_by: str = \"unit_count\", limit: int = 10) -> list[dict]:\n \"\"\"Search timesheets matching query on project_code and return sorted rows.\"\"\"\n allowed_sort_columns = {\"id\", \"project_code\", \"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 conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n \"SELECT id, project_code, category_tag, unit_count \"\n \"FROM timesheets \"\n \"WHERE project_code LIKE ? \"\n f\"ORDER BY {sort_by} DESC \"\n \"LIMIT ?\"\n )\n # Use parameterized queries for query and limit\n param_query = f\"%{query}%\"\n rows = conn.execute(sql, (param_query, limit)).fetchall()\n return [dict(r) for r in rows]\n finally:\n conn.close()\n```"}]}
{"task_id": "pg-train-path_traversal-0057", "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 `warehouse_ledger` 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 \"\"\"\n Check if the target_path is located within base_dir after resolving symlinks and relative paths.\n \"\"\"\n base_dir = os.path.abspath(base_dir)\n target_path = os.path.abspath(target_path)\n return os.path.commonpath([base_dir]) == os.path.commonpath([base_dir, target_path])\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, preventing path traversal attacks.\n \n Raises:\n ValueError: If the resolved path is outside the base_dir.\n FileNotFoundError, OSError: If the file cannot be accessed.\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 detected: file outside base directory\")\n with open(target, \"r\", encoding=\"utf-8\") as fh:\n return fh.read()\n```"}]}
{"task_id": "pg-train-cmd_injection-0058", "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 `fleet_dispatch` 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_fleet_dispatch_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\nfrom pathlib import Path\n\n# Allowed modes for the fleet dispatch tool\nALLOWED_MODES = frozenset({\"summary\", \"verify\"})\n\ndef run_fleet_dispatch_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 # Validate mode against allowlist\n if mode not in ALLOWED_MODES:\n raise ValueError(f\"Invalid mode: {mode!r}. Allowed modes are: {sorted(ALLOWED_MODES)}\")\n\n # Resolve and validate script_path to be an absolute path and prevent path traversal\n script_path_obj = Path(script_path).resolve(strict=True)\n\n # Construct argument vector safely without shell=True\n cmd = [\n sys.executable,\n str(script_path_obj),\n \"--mode\",\n mode,\n target_name,\n ]\n\n proc = subprocess.run(cmd, capture_output=True, text=True, check=True)\n return proc.stdout.strip()\n```"}]}
{"task_id": "pg-train-ssrf-0059", "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 `fleet_dispatch` 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 retrieve_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 ipaddress\nimport socket\nfrom urllib.parse import urlparse\nimport urllib.request\n\n\ndef retrieve_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 # Validate scheme early\n parsed = urlparse(url)\n if parsed.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 # Disallow localhost by hostname (exact match or common aliases)\n # Use canonical lowercase for comparison\n hostname_lc = hostname.lower()\n if hostname_lc in (\"localhost\", \"localhost.localdomain\", \"ip6-localhost\"):\n raise ValueError(\"Localhost blocked\")\n\n # Resolve hostname to IP addresses\n if resolver is not None:\n try:\n ips = resolver(hostname)\n except Exception as e:\n raise ValueError(f\"Failed to resolve hostname: {e}\") from e\n else:\n try:\n # getaddrinfo returns list of tuples: (family, type, proto, canonname, sockaddr)\n # sockaddr is (address, port) for IPv4, (address, port, flowinfo, scopeid) for IPv6\n addrinfos = socket.getaddrinfo(hostname, None)\n ips = [info[-1][0] for info in addrinfos]\n except Exception as e:\n raise ValueError(f\"Failed to resolve hostname: {e}\") from e\n\n # Validate all resolved IPs are public routable (not private, loopback, link-local, multicast, unspecified)\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_link_local or ip.is_multicast or ip.is_unspecified:\n raise ValueError(f\"Disallowed IP address resolved: {ip_str}\")\n\n # If transport is provided, use it (assumed safe)\n if transport is not None:\n return transport(url)\n\n # Perform the actual HTTP request with timeout\n with urllib.request.urlopen(url, timeout=5) as resp:\n return resp.read().decode(\"utf-8\")\n```"}]}
{"task_id": "pg-train-idor_auth-0060", "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 `clinic_intake` 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_vehicles_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_vehicles_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 not found\")\n\n record = store[resource_id]\n\n user_id = session.get('user_id')\n user_role = session.get('role')\n\n if user_id is None:\n raise PermissionError(\"Unauthenticated: user_id missing in session\")\n\n # Enforce ownership or admin role\n if record.get('owner_id') != user_id and user_role != 'admin':\n raise PermissionError(\"Access denied: user does not own this resource and is not admin\")\n\n if payload:\n # Disallow changes to protected fields\n protected_fields = {'id', 'owner_id', 'role', 'is_admin'}\n for key in payload:\n if key in protected_fields:\n raise PermissionError(f\"Modification of protected field '{key}' 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-0061", "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 `fleet_dispatch` 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_fleet_dispatch_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 parse_fleet_dispatch_payload(raw_payload: str) -> Dict[str, Any]:\n \"\"\"\n Decode an incoming serialized message dictionary safely.\n\n Supports JSON-encoded payloads only. Raises ValueError if decoding fails\n or if the decoded object is not a dictionary.\n \"\"\"\n try:\n data = json.loads(raw_payload)\n except json.JSONDecodeError as e:\n raise ValueError(\"Payload must be valid JSON\") from e\n\n if not isinstance(data, dict):\n raise ValueError(\"Payload must decode to a dict\")\n return data\n```"}]}
{"task_id": "pg-train-xss-0062", "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 `fleet_dispatch` 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_appointments_badge(title: str, summary: str, link_url: str) -> str:\n \"\"\"Render an HTML card badge with title, summary, and external link.\"\"\"\n return f'<div class=\"badge\" title=\"{title}\"><a href=\"{link_url}\">{summary}</a></div>'\n```\n"}, {"role": "assistant", "content": "```python\nimport html\nfrom urllib.parse import urlparse\n\n# Allowed URL schemes for href attributes to prevent unsafe links (e.g. javascript:)\nALLOWED_HREF_SCHEMES = frozenset({\"http\", \"https\", \"mailto\", \"tel\", \"\"}) # \"\" for relative URLs\n\ndef _is_safe_href(href: str) -> bool:\n \"\"\"Check if the href URL has a safe scheme.\"\"\"\n parsed = urlparse(href)\n # urlparse returns empty scheme for relative URLs, which we allow\n return parsed.scheme.lower() in ALLOWED_HREF_SCHEMES\n\ndef render_appointments_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, quote=False) # allow quotes in text content\n\n # Validate and escape link_url\n if not _is_safe_href(link_url):\n # If unsafe, do not render as link, render summary as plain text\n return f'<div class=\"badge\" title=\"{safe_title}\">{safe_summary}</div>'\n safe_link_url = html.escape(link_url, quote=True)\n\n return f'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_link_url}\">{safe_summary}</a></div>'\n```"}]}
{"task_id": "pg-train-sqli-0064", "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 `fleet_dispatch` 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 retrieve_timesheets(db_path: str, query: str, sort_by: str = \"priority_rank\", limit: int = 10) -> list[dict]:\n \"\"\"Search timesheets matching query on manifest_note and return sorted rows.\"\"\"\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, manifest_note, category_tag, priority_rank \"\n f\"FROM timesheets \"\n f\"WHERE manifest_note 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 retrieve_timesheets(db_path: str, query: str, sort_by: str = \"priority_rank\", limit: int = 10) -> list[dict]:\n \"\"\"Search timesheets matching query on manifest_note and return sorted rows.\"\"\"\n allowed_sort_columns = {\"id\", \"manifest_note\", \"category_tag\", \"priority_rank\"}\n\n if sort_by not in allowed_sort_columns:\n raise ValueError(f\"Invalid sort_by column: {sort_by}\")\n\n if not isinstance(limit, int) or limit <= 0:\n raise ValueError(\"limit must be a positive integer\")\n\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, manifest_note, category_tag, priority_rank \"\n f\"FROM timesheets \"\n f\"WHERE manifest_note LIKE ? \"\n f\"ORDER BY {sort_by} DESC \"\n f\"LIMIT ?\"\n )\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-0065", "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 `clinic_intake` 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 lookup_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 \"\"\"\n Check if target_path is located within base_dir after resolving symlinks and relative components.\n\n Args:\n base_dir: The base directory path.\n target_path: The target file path to verify.\n\n Returns:\n True if target_path is inside base_dir, False otherwise.\n \"\"\"\n base_dir_real = os.path.realpath(base_dir)\n target_real = os.path.realpath(target_path)\n return os.path.commonpath([base_dir_real]) == os.path.commonpath([base_dir_real, target_real])\n\n\ndef lookup_artifact_text(base_dir: str, rel_path: str) -> str:\n \"\"\"\n Read a UTF-8 text file located under base_dir, preventing path traversal attacks.\n\n Args:\n base_dir: The base directory under which files are allowed to be read.\n rel_path: The relative path to the target file within base_dir.\n\n Returns:\n The contents of the file as a string.\n\n Raises:\n FileNotFoundError: If the file does not exist.\n ValueError: If the resolved path is outside of base_dir.\n OSError: For other I/O related errors.\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 detected: access outside base_dir is forbidden\")\n with open(target, \"r\", encoding=\"utf-8\") as fh:\n return fh.read()\n```"}]}
{"task_id": "pg-train-cmd_injection-0066", "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 `warehouse_ledger` 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_warehouse_ledger_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 warehouse ledger tool\nALLOWED_MODES = frozenset({\"summary\", \"verify\"})\n\ndef run_warehouse_ledger_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\n This function uses subprocess with argument vectors to prevent OS command injection.\n It also validates the mode argument against an allow-list.\n \"\"\"\n if mode not in ALLOWED_MODES:\n raise ValueError(f\"Invalid mode: {mode!r}. Allowed modes are: {sorted(ALLOWED_MODES)}\")\n\n # Construct the argument vector safely without shell=True\n cmd = [\n sys.executable,\n script_path,\n \"--mode\",\n mode,\n target_name,\n ]\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-0067", "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 `payroll_portal` 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 lookup_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 lookup_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 cheaply\n parsed = urllib.parse.urlparse(url)\n if parsed.scheme not in (\"http\", \"https\"):\n raise ValueError(\"Unsupported URL scheme\")\n\n hostname = parsed.hostname\n if hostname is None:\n raise ValueError(\"URL must have a hostname\")\n\n # Block localhost and loopback IPs by hostname and resolved IPs\n # Check if hostname is localhost or equivalent\n if hostname.lower() in (\"localhost\", \"localhost.localdomain\", \"ip6-localhost\"):\n raise ValueError(\"Localhost blocked\")\n\n # Resolve hostname to IP addresses using provided resolver or default\n if resolver is not None:\n try:\n resolved_ips = resolver(hostname)\n if not isinstance(resolved_ips, (list, tuple)):\n raise ValueError(\"Resolver must return a list or tuple of IP strings\")\n except Exception as e:\n raise ValueError(f\"Failed to resolve hostname: {e}\")\n else:\n try:\n # getaddrinfo returns list of tuples, extract IPs\n infos = socket.getaddrinfo(hostname, None)\n resolved_ips = list({info[4][0] for info in infos})\n except socket.gaierror as e:\n raise ValueError(f\"DNS resolution failed: {e}\")\n\n # Check each resolved IP to ensure it is not loopback, link-local, or private\n for ip_str in resolved_ips:\n try:\n ip_obj = ipaddress.ip_address(ip_str)\n except ValueError:\n raise ValueError(f\"Invalid IP address resolved: {ip_str}\")\n\n if ip_obj.is_loopback:\n raise ValueError(f\"Resolved IP {ip_str} is loopback, blocked\")\n if ip_obj.is_link_local:\n raise ValueError(f\"Resolved IP {ip_str} is link-local, blocked\")\n if ip_obj.is_private:\n raise ValueError(f\"Resolved IP {ip_str} is private, blocked\")\n if ip_obj.is_reserved:\n raise ValueError(f\"Resolved IP {ip_str} is reserved, blocked\")\n if ip_obj.is_multicast:\n raise ValueError(f\"Resolved IP {ip_str} is multicast, blocked\")\n\n # If transport is provided, use it (assumed safe)\n if transport is not None:\n return transport(url)\n\n # Use urllib.request.urlopen with timeout, no shell or external calls\n with urllib.request.urlopen(url, timeout=5) as resp:\n return resp.read().decode(\"utf-8\")\n```"}]}
{"task_id": "pg-train-idor_auth-0068", "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 `clinic_intake` 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');\n 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 is None:\n return dict(record)\n\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(f\"Modification of protected fields {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-0069", "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_parse_json(raw_payload: str) -> Dict[str, Any]:\n \"\"\"Safely parse a JSON string into a dictionary.\"\"\"\n data = json.loads(raw_payload)\n if not isinstance(data, dict):\n raise ValueError(\"Payload must decode to a dict\")\n return data\n\n\ndef _safe_parse_pickle(hex_payload: str) -> Dict[str, Any]:\n \"\"\"Safely parse a hex-encoded pickle payload after strict type checks.\"\"\"\n import pickle\n import io\n\n # Restrict unpickling to only built-in safe types (dict, list, str, int, float, bool, None)\n # by subclassing Unpickler and overriding find_class to prevent arbitrary code execution.\n class RestrictedUnpickler(pickle.Unpickler):\n def find_class(self, module: str, name: str) -> Any:\n # Only allow safe builtins\n safe_builtins = {\n 'builtins': {\n 'dict', 'list', 'set', 'frozenset', 'str', 'int', 'float', 'bool', 'tuple', 'NoneType'\n }\n }\n if module == \"builtins\" and name in safe_builtins.get(module, set()):\n return getattr(__import__(module), name)\n raise pickle.UnpicklingError(f\"Global '{module}.{name}' is forbidden\")\n\n try:\n bytes_payload = bytes.fromhex(hex_payload)\n file_like = io.BytesIO(bytes_payload)\n data = RestrictedUnpickler(file_like).load()\n except Exception as ex:\n raise ValueError(f\"Invalid pickle payload: {ex}\") from ex\n\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 safely.\n\n Supports JSON strings or hex-encoded pickle payloads prefixed with 'pickle:'.\n Unsafe deserialization and code evaluation are prevented.\n \"\"\"\n if raw_payload.startswith(\"pickle:\"):\n return _safe_parse_pickle(raw_payload[7:])\n else:\n return _safe_parse_json(raw_payload)\n```"}]}
{"task_id": "pg-train-crypto_secrets-0071", "category": "crypto_secrets", "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 Weak Cryptography, Predictable RNG & Secret Exposure in Logs (CWE-327) 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 hashlib\nimport random\nimport string\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage.\"\"\"\n return hashlib.md5(password.encode(\"utf-8\")).hexdigest()\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n return hash_password(password) == stored_hash\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n alphabet = string.ascii_letters + string.digits\n return \"\".join(random.choices(alphabet, k=32))\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for clinic_intake.\"\"\"\n return f\"service=clinic_intake user={user_id} action={action} api_key={api_key}\"\n```\n"}, {"role": "assistant", "content": "```python\nimport hashlib\nimport secrets\nimport hmac\nfrom typing import Optional\n\n\n# Use a strong password hashing scheme with salt and slow hashing.\n# Here, we use PBKDF2 with SHA256, a per-password salt, and many iterations.\n# This function returns a string encoding the salt and hash for storage.\ndef hash_password(password: str, *, salt: Optional[bytes] = None) -> str:\n \"\"\"Hash a user password for storage using PBKDF2-HMAC-SHA256 with a salt.\"\"\"\n if salt is None:\n salt = secrets.token_bytes(16)\n # 100,000 iterations is a reasonable default for PBKDF2\n iterations = 100_000\n dk = hashlib.pbkdf2_hmac(\"sha256\", password.encode(\"utf-8\"), salt, iterations)\n # Store as hex: iterations$salt_hex$hash_hex\n return f\"{iterations}${salt.hex()}${dk.hex()}\"\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n try:\n iterations_str, salt_hex, hash_hex = stored_hash.split(\"$\", 2)\n iterations = int(iterations_str)\n salt = bytes.fromhex(salt_hex)\n expected_hash = bytes.fromhex(hash_hex)\n except (ValueError, TypeError):\n # Malformed stored_hash\n return False\n test_hash = hashlib.pbkdf2_hmac(\"sha256\", password.encode(\"utf-8\"), salt, iterations)\n # Use hmac.compare_digest to prevent timing attacks\n return hmac.compare_digest(test_hash, expected_hash)\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n # Generate 32 bytes of secure random data and encode as hex (64 chars)\n return secrets.token_hex(32)\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for clinic_intake with secret redaction.\"\"\"\n # Redact api_key except last 4 characters for security\n redacted_key = (\n f\"{'*' * (len(api_key) - 4)}{api_key[-4:]}\" if len(api_key) > 4 else \"*\" * len(api_key)\n )\n return f\"service=clinic_intake user={user_id} action={action} api_key={redacted_key}\"\n```"}]}
{"task_id": "pg-train-sqli-0072", "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 `fleet_dispatch` 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 retrieve_shipments(db_path: str, query: str, sort_by: str = \"priority_rank\", limit: int = 10) -> list[dict]:\n \"\"\"Search shipments matching query on manifest_note and return sorted rows.\"\"\"\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, manifest_note, category_tag, priority_rank \"\n f\"FROM shipments \"\n f\"WHERE manifest_note 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 retrieve_shipments(db_path: str, query: str, sort_by: str = \"priority_rank\", limit: int = 10) -> list[dict]:\n \"\"\"Search shipments matching query on manifest_note and return sorted rows.\"\"\"\n # Validate limit\n if not isinstance(limit, int) or limit <= 0:\n raise ValueError(\"limit must be a positive integer\")\n # Validate sort_by against an allow-list of known safe columns\n allowed_sort_columns = {\"id\", \"manifest_note\", \"category_tag\", \"priority_rank\"}\n if sort_by not in allowed_sort_columns:\n raise ValueError(f\"Invalid sort_by column: {sort_by}\")\n\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n # Use parameterized query for user input\n sql = (\n f\"SELECT id, manifest_note, category_tag, priority_rank \"\n f\"FROM shipments \"\n f\"WHERE manifest_note LIKE ? \"\n f\"ORDER BY {sort_by} DESC \"\n f\"LIMIT ?\"\n )\n # Parameterize query with wildcards for LIKE and limit as int\n params = (f\"%{query}%\", limit)\n rows = conn.execute(sql, params).fetchall()\n return [dict(r) for r in rows]\n finally:\n conn.close()\n```"}]}
{"task_id": "pg-train-path_traversal-0073", "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 `payroll_portal` 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 \"\"\"\n Check if the target_path is located within base_dir after resolving symlinks and relative components.\n \"\"\"\n base_dir = os.path.abspath(os.path.realpath(base_dir))\n target_path = os.path.abspath(os.path.realpath(target_path))\n return os.path.commonpath([base_dir]) == os.path.commonpath([base_dir, target_path])\n\n\ndef fetch_artifact_text(base_dir: str, rel_path: str) -> str:\n \"\"\"Read a UTF-8 text file located under base_dir, preventing path traversal.\"\"\"\n target = os.path.join(base_dir, rel_path)\n if not _is_within_directory(base_dir, target):\n raise ValueError(\"Attempted Path Traversal detected: access outside base_dir is forbidden\")\n with open(target, \"r\", encoding=\"utf-8\") as fh:\n return fh.read()\n```"}]}
{"task_id": "pg-train-cmd_injection-0074", "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 `payroll_portal` 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_payroll_portal_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 payroll portal tool\nALLOWED_MODES = frozenset({'summary', 'verify'})\n\ndef run_payroll_portal_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: {ALLOWED_MODES}\")\n\n # Use argument vector to avoid shell injection\n cmd = [\n sys.executable,\n script_path,\n '--mode',\n mode,\n 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-0075", "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 `fleet_dispatch` 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 query_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 query_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 if parsed.scheme not in (\"http\", \"https\"):\n raise ValueError(\"Unsupported URL scheme\")\n\n hostname = parsed.hostname\n if hostname is None:\n raise ValueError(\"URL must have a hostname\")\n\n # Block localhost and loopback names explicitly\n # Use canonical hostname check (lowercase)\n hostname_lc = hostname.lower()\n if hostname_lc in (\"localhost\", \"localhost.localdomain\"):\n raise ValueError(\"Localhost blocked\")\n\n # Resolve IP addresses using provided resolver or default system resolver\n def resolve(name):\n if resolver is not None:\n ips = resolver(name)\n if not isinstance(ips, (list, tuple)) or not all(isinstance(ip, str) for ip in ips):\n raise ValueError(\"Resolver must return list of IP strings\")\n return ips\n else:\n try:\n # getaddrinfo returns list of (family, type, proto, canonname, sockaddr)\n infos = socket.getaddrinfo(name, None)\n ips = []\n for info in infos:\n sockaddr = info[4]\n ip = sockaddr[0]\n ips.append(ip)\n return list(set(ips))\n except socket.gaierror:\n raise ValueError(\"Hostname resolution failed\")\n\n ips = resolve(hostname)\n\n # Check all resolved IPs to ensure none are private, loopback, link-local, or unspecified\n for ip_str in ips:\n try:\n ip_obj = ipaddress.ip_address(ip_str)\n except ValueError:\n raise ValueError(f\"Invalid IP address resolved: {ip_str}\")\n\n if ip_obj.is_loopback:\n raise ValueError(\"Loopback IP addresses are blocked\")\n if ip_obj.is_private:\n raise ValueError(\"Private IP addresses are blocked\")\n if ip_obj.is_link_local:\n raise ValueError(\"Link-local IP addresses are blocked\")\n if ip_obj.is_unspecified:\n raise ValueError(\"Unspecified IP addresses are blocked\")\n # Optionally block multicast or reserved IPs if needed\n # if ip_obj.is_multicast or ip_obj.is_reserved:\n # raise ValueError(\"Multicast or reserved IP addresses are blocked\")\n\n # If transport is provided, use it to fetch\n if transport is not None:\n return transport(url)\n\n # Default fetch\n with urllib.request.urlopen(url, timeout=5) as resp:\n return resp.read().decode(\"utf-8\")\n```"}]}
{"task_id": "pg-train-idor_auth-0076", "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_timesheets_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_timesheets_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 does not exist\")\n\n record = store[resource_id]\n\n user_id = session.get('user_id')\n user_role = session.get('role')\n\n if user_id is None:\n raise PermissionError(\"User not authenticated\")\n\n # Access control: user must be owner or admin\n if user_id != record.get('owner_id') and user_role != 'admin':\n raise PermissionError(\"User not authorized to access this resource\")\n\n if payload:\n # Prevent 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(f\"Modification of protected fields {protected_fields} is not allowed\")\n\n # Update record safely\n record.update(payload)\n\n return dict(record)\n```"}]}
{"task_id": "pg-train-xss-0078", "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 `warehouse_ledger` 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_appointments_badge(title: str, summary: str, link_url: str) -> str:\n \"\"\"Render an HTML card badge with title, summary, and external link.\"\"\"\n return f'<div class=\"badge\" title=\"{title}\"><a href=\"{link_url}\">{summary}</a></div>'\n```\n"}, {"role": "assistant", "content": "```python\nimport html\nfrom urllib.parse import urlparse\n\n# Allowed URL schemes for href attribute to prevent unsafe schemes like javascript:\nALLOWED_HREF_SCHEMES = frozenset({\"http\", \"https\", \"mailto\", \"tel\", \"ftp\"})\n\ndef render_appointments_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 # Parse and validate the link_url scheme\n parsed_url = urlparse(link_url)\n if parsed_url.scheme and parsed_url.scheme.lower() not in ALLOWED_HREF_SCHEMES:\n # Unsafe scheme, drop the href attribute by rendering summary without link\n return f'<div class=\"badge\" title=\"{safe_title}\">{safe_summary}</div>'\n\n # Escape the URL for safe inclusion in href attribute\n safe_link_url = html.escape(link_url, quote=True)\n\n return f'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_link_url}\">{safe_summary}</a></div>'\n```"}]}
{"task_id": "pg-train-sqli-0080", "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 `warehouse_ledger` 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 lookup_timesheets(db_path: str, query: str, sort_by: str = \"created_at\", limit: int = 10) -> list[dict]:\n \"\"\"Search timesheets matching query on project_code and return sorted rows.\"\"\"\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, project_code, category_tag, created_at \"\n f\"FROM timesheets \"\n f\"WHERE project_code 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 lookup_timesheets(db_path: str, query: str, sort_by: str = \"created_at\", limit: int = 10) -> list[dict]:\n \"\"\"Search timesheets matching query on project_code and return sorted rows.\"\"\"\n # Validate limit\n if not isinstance(limit, int) or limit <= 0:\n raise ValueError(\"limit must be a positive integer\")\n\n # Define allowed columns for sorting to prevent SQL injection via identifiers\n allowed_sort_columns = {\"id\", \"project_code\", \"category_tag\", \"created_at\"}\n if sort_by not in allowed_sort_columns:\n raise ValueError(f\"Invalid sort_by column: {sort_by}\")\n\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n # Use parameterized query for the LIKE clause\n sql = (\n f\"SELECT id, project_code, category_tag, created_at \"\n f\"FROM timesheets \"\n f\"WHERE project_code LIKE ? \"\n f\"ORDER BY {sort_by} DESC \"\n f\"LIMIT ?\"\n )\n # Use parameterized arguments\n param_query = f\"%{query}%\"\n rows = conn.execute(sql, (param_query, limit)).fetchall()\n return [dict(r) for r in rows]\n finally:\n conn.close()\n```"}]}
{"task_id": "pg-train-path_traversal-0081", "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 `payroll_portal` 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\nfrom typing import Optional\n\n\ndef _safe_join(base_dir: str, rel_path: str) -> Optional[str]:\n \"\"\"\n Safely join base_dir and rel_path ensuring the resulting path is within base_dir.\n\n Args:\n base_dir: The base directory path.\n rel_path: The relative path to join with base_dir.\n\n Returns:\n The canonical absolute path if it's inside base_dir; otherwise, None.\n \"\"\"\n base_dir_abs = os.path.abspath(base_dir)\n target_path = os.path.abspath(os.path.join(base_dir_abs, rel_path))\n if os.path.commonpath([base_dir_abs]) == os.path.commonpath([base_dir_abs, target_path]):\n return target_path\n return None\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, preventing path traversal attacks.\n\n Args:\n base_dir: The base directory under which the file must reside.\n rel_path: The relative path to the file from base_dir.\n\n Returns:\n The content of the file as a string.\n\n Raises:\n FileNotFoundError: If the file does not exist or path is outside base_dir.\n OSError: For other OS-related errors during file access.\n \"\"\"\n safe_path = _safe_join(base_dir, rel_path)\n if safe_path is None:\n raise FileNotFoundError(f\"Attempted path traversal outside base directory: {rel_path}\")\n with open(safe_path, \"r\", encoding=\"utf-8\") as fh:\n return fh.read()\n```"}]}
{"task_id": "pg-train-cmd_injection-0082", "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 `warehouse_ledger` 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_warehouse_ledger_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\nfrom pathlib import Path\n\n# Allowed modes for the warehouse ledger tool\nALLOWED_MODES = frozenset({\"summary\", \"verify\"})\n\ndef run_warehouse_ledger_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 # Validate mode against allowlist\n if mode not in ALLOWED_MODES:\n raise ValueError(f\"Invalid mode: {mode!r}. Allowed modes: {sorted(ALLOWED_MODES)}\")\n\n # Resolve and validate script_path to an absolute path\n script_path_obj = Path(script_path).resolve(strict=True)\n # Optionally, add confinement here if needed, e.g. ensure script_path is under a trusted directory\n\n # Validate target_name as a safe filename (no path separators)\n target_name_obj = Path(target_name)\n if target_name_obj.is_absolute() or \"..\" in target_name_obj.parts:\n raise ValueError(f\"Invalid target_name: {target_name!r}. Must be a relative filename without path traversal.\")\n\n # Construct argument list without shell=True to prevent injection\n cmd = [sys.executable, str(script_path_obj), \"--mode\", mode, target_name]\n\n proc = subprocess.run(cmd, capture_output=True, text=True, check=True)\n return proc.stdout.strip()\n```"}]}
{"task_id": "pg-train-ssrf-0083", "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 query_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 ipaddress\nimport socket\n\n\ndef query_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 # Validate scheme cheaply\n parsed = urllib.parse.urlparse(url)\n if parsed.scheme not in (\"http\", \"https\"):\n raise ValueError(\"Unsupported URL scheme\")\n\n hostname = parsed.hostname\n if hostname is None:\n raise ValueError(\"URL must have a hostname\")\n\n # Block localhost and loopback names explicitly\n # Also block IPs in loopback, link-local, and private ranges\n # Use canonical hostname check (case-insensitive)\n if hostname.lower() in {\"localhost\", \"ip6-localhost\"}:\n raise ValueError(\"Localhost blocked\")\n\n # Resolve IP addresses using resolver if provided, else system DNS\n try:\n if resolver:\n ips = resolver(hostname)\n if not ips:\n raise ValueError(\"Hostname resolution failed\")\n else:\n # Use getaddrinfo to get all IP addresses (IPv4 and IPv6)\n infos = socket.getaddrinfo(hostname, None)\n ips = [info[4][0] for info in infos]\n except Exception as e:\n raise ValueError(f\"Hostname resolution failed: {e}\")\n\n # Validate each resolved IP address to prevent SSRF to local/internal networks\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\n # Reject loopback, link-local, multicast, private, and unspecified addresses\n if ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_unspecified or ip.is_reserved:\n raise ValueError(f\"IP address {ip} is not allowed\")\n if ip.version == 4 and ip.is_private:\n raise ValueError(f\"Private IPv4 address {ip} is not allowed\")\n if ip.version == 6 and (\n ip.is_site_local or ip.is_private\n ):\n raise ValueError(f\"Private IPv6 address {ip} is not allowed\")\n\n # If a custom transport is provided, use it\n if transport is not None:\n return transport(url)\n\n # Perform the actual request with a timeout\n with urllib.request.urlopen(url, timeout=5) as resp:\n return resp.read().decode(\"utf-8\")\n```"}]}
{"task_id": "pg-train-idor_auth-0084", "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 `clinic_intake` 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 not found\")\n\n record = store[resource_id]\n\n user_id = session.get('user_id')\n user_role = session.get('role')\n\n if user_id is None:\n raise PermissionError(\"Unauthenticated session\")\n\n # Authorization check: must be owner or admin\n if not (user_role == 'admin' or user_id == record.get('owner_id')):\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-xss-0086", "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_shipments_badge(title: str, summary: str, link_url: str) -> str:\n \"\"\"Render an HTML card badge with title, summary, and external link.\"\"\"\n return f'<div class=\"badge\" title=\"{title}\"><a href=\"{link_url}\">{summary}</a></div>'\n```\n"}, {"role": "assistant", "content": "```python\nimport html\nfrom urllib.parse import urlparse\n\n# Allow only safe URL schemes for href attributes\n_ALLOWED_HREF_SCHEMES = frozenset({\"http\", \"https\", \"mailto\", \"tel\", \"\"})\n\ndef render_shipments_badge(title: str, summary: str, link_url: str) -> str:\n \"\"\"Render an HTML card badge with title, summary, and external link.\n\n Escapes title and summary to prevent XSS.\n Validates link_url scheme to prevent unsafe href schemes.\n \"\"\"\n # Escape title and summary for safe HTML embedding\n safe_title = html.escape(title, quote=True)\n safe_summary = html.escape(summary)\n\n # Parse the URL and validate scheme\n parsed = urlparse(link_url)\n scheme = parsed.scheme.lower()\n\n # If scheme is not in allowed list, neutralize the href to prevent XSS/phishing\n if scheme not in _ALLOWED_HREF_SCHEMES:\n safe_href = \"#\"\n else:\n # Rebuild the URL to avoid injection via control characters or spaces\n # We trust the original URL if scheme is allowed, but still escape it\n safe_href = html.escape(link_url, quote=True)\n\n return f'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_href}\">{safe_summary}</a></div>'\n```"}]}
{"task_id": "pg-train-crypto_secrets-0087", "category": "crypto_secrets", "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 Weak Cryptography, Predictable RNG & Secret Exposure in Logs (CWE-327) 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 hashlib\nimport random\nimport string\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage.\"\"\"\n return hashlib.md5(password.encode(\"utf-8\")).hexdigest()\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n return hash_password(password) == stored_hash\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n alphabet = string.ascii_letters + string.digits\n return \"\".join(random.choices(alphabet, k=32))\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for warehouse_ledger.\"\"\"\n return f\"service=warehouse_ledger user={user_id} action={action} api_key={api_key}\"\n```\n"}, {"role": "assistant", "content": "```python\nimport hashlib\nimport secrets\nimport hmac\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage using a salted PBKDF2-HMAC-SHA256.\"\"\"\n salt = secrets.token_bytes(16)\n # Use 100,000 iterations for PBKDF2\n dk = hashlib.pbkdf2_hmac(\"sha256\", password.encode(\"utf-8\"), salt, 100_000)\n # Store salt and hash hex-encoded, separated by $\n return f\"{salt.hex()}${dk.hex()}\"\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored salted hash.\"\"\"\n try:\n salt_hex, hash_hex = stored_hash.split(\"$\", 1)\n salt = bytes.fromhex(salt_hex)\n expected_hash = bytes.fromhex(hash_hex)\n except (ValueError, TypeError):\n # Malformed stored_hash\n return False\n test_hash = hashlib.pbkdf2_hmac(\"sha256\", password.encode(\"utf-8\"), salt, 100_000)\n # Use hmac.compare_digest to prevent timing attacks\n return hmac.compare_digest(test_hash, expected_hash)\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n # Use secrets.token_urlsafe to get a URL-safe base64-encoded token\n # 24 bytes -> 32 chars base64 approx\n return secrets.token_urlsafe(24)\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for warehouse_ledger with redacted api_key.\"\"\"\n redacted_key = (\n api_key[:4] + \"...\" + api_key[-4:] if len(api_key) > 8 else \"REDACTED\"\n )\n return f\"service=warehouse_ledger user={user_id} action={action} api_key={redacted_key}\"\n```"}]}
{"task_id": "pg-train-sqli-0088", "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 retrieve_timesheets(db_path: str, query: str, sort_by: str = \"unit_count\", limit: int = 10) -> list[dict]:\n \"\"\"Search timesheets matching query on manifest_note and return sorted rows.\"\"\"\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, manifest_note, category_tag, unit_count \"\n f\"FROM timesheets \"\n f\"WHERE manifest_note 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 retrieve_timesheets(db_path: str, query: str, sort_by: str = \"unit_count\", limit: int = 10) -> list[dict]:\n \"\"\"Search timesheets matching query on manifest_note and return sorted rows.\"\"\"\n allowed_sort_columns = {\"id\", \"manifest_note\", \"category_tag\", \"unit_count\"}\n\n if sort_by not in allowed_sort_columns:\n raise ValueError(f\"Invalid sort_by column: {sort_by!r}\")\n\n try:\n limit = int(limit)\n except Exception:\n raise ValueError(\"limit must be an integer\")\n if limit <= 0:\n raise ValueError(\"limit must be a positive integer\")\n\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, manifest_note, category_tag, unit_count \"\n f\"FROM timesheets \"\n f\"WHERE manifest_note LIKE ? \"\n f\"ORDER BY {sort_by} DESC \"\n f\"LIMIT ?\"\n )\n # Use parameterized queries for user inputs\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-0089", "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 `payroll_portal` 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 \"\"\"\n Check if target_path is located within base_dir after resolving symlinks and relative components.\n \"\"\"\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, preventing path traversal attacks by\n ensuring the resolved path is confined within base_dir.\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 base directory\")\n with open(target, \"r\", encoding=\"utf-8\") as fh:\n return fh.read()\n```"}]}
{"task_id": "pg-train-cmd_injection-0090", "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 `payroll_portal` 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_payroll_portal_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 payroll portal tool\nALLOWED_MODES = frozenset({\"summary\", \"verify\"})\n\ndef run_payroll_portal_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 # Construct argument vector to avoid shell=True and prevent command 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-0091", "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 `fleet_dispatch` 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 lookup_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 lookup_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 # Validate scheme\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 hostname is None:\n raise ValueError(\"URL must have a hostname\")\n\n # Block localhost and loopback hostnames explicitly\n # This covers localhost, localhost.localdomain, and any variants\n # Also block direct IP addresses in loopback range\n try:\n ip = ipaddress.ip_address(hostname)\n except ValueError:\n # Not an IP, check if hostname is localhost or equivalent\n if hostname.lower() == \"localhost\":\n raise ValueError(\"Localhost blocked\")\n else:\n # It's an IP address, block loopback and link-local addresses\n if ip.is_loopback or ip.is_link_local:\n raise ValueError(\"Localhost or link-local IP blocked\")\n\n # Resolve hostname to IPs using provided resolver or system DNS\n if resolver is not None:\n resolved_ips = resolver(hostname)\n if not isinstance(resolved_ips, (list, tuple)) or not all(isinstance(i, str) for i in resolved_ips):\n raise ValueError(\"Resolver must return a list of IP strings\")\n else:\n try:\n infos = socket.getaddrinfo(hostname, None)\n resolved_ips = list({info[4][0] for info in infos})\n except socket.gaierror as e:\n raise ValueError(f\"DNS resolution failed for hostname {hostname}\") from e\n\n # Check all resolved IPs for loopback, link-local, private, and unspecified addresses\n for ip_str in resolved_ips:\n try:\n ip_obj = ipaddress.ip_address(ip_str)\n except ValueError:\n raise ValueError(f\"Resolved IP address {ip_str} is invalid\")\n # Block loopback, link-local, private, and unspecified IPs to prevent SSRF\n if ip_obj.is_loopback or ip_obj.is_link_local or ip_obj.is_private or ip_obj.is_unspecified:\n raise ValueError(f\"Blocked IP address {ip_str} resolved from hostname {hostname}\")\n\n # Perform the fetch\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```"}]}
{"task_id": "pg-train-idor_auth-0092", "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 `clinic_intake` 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 \"\"\"\n Read or update a record in store.\n\n Authorization:\n - Caller must have session['user_id'] matching record['owner_id'], or\n - session.get('role') == 'admin'.\n\n Payload restrictions:\n - Must not alter protected fields: id, owner_id, role, is_admin.\n\n Raises:\n - KeyError: if resource_id not in store.\n - PermissionError: if caller not authorized.\n - ValueError: if payload attempts to modify protected fields.\n \"\"\"\n if resource_id not in store:\n raise KeyError(f\"Resource ID {resource_id} not found in store\")\n\n record = store[resource_id]\n\n user_id = session.get('user_id')\n user_role = session.get('role')\n\n if user_role != 'admin' and user_id != record.get('owner_id'):\n raise PermissionError(\"User not authorized to access this resource\")\n\n if payload:\n protected_fields = {'id', 'owner_id', 'role', 'is_admin'}\n # Check if payload attempts to modify any protected fields\n if any(field in payload for field in protected_fields):\n raise ValueError(f\"Payload must not modify protected fields: {protected_fields}\")\n\n # Update record safely\n record.update(payload)\n\n return dict(record)\n```"}]}
{"task_id": "pg-train-unsafe_deser_eval-0093", "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_literal(raw: str) -> Any:\n \"\"\"Safely parse a Python literal expression from a string.\"\"\"\n import ast\n\n try:\n node = ast.parse(raw, mode=\"eval\")\n except SyntaxError as e:\n raise ValueError(f\"Invalid literal expression: {e}\") from e\n\n # Only allow literal expressions (no calls, attribute access, etc.)\n if not all(isinstance(n, (ast.Expression, ast.Str, ast.Bytes, ast.Num, ast.Tuple, ast.List, ast.Set,\n ast.Dict, ast.NameConstant, ast.Constant))\n for n in ast.walk(node)):\n raise ValueError(\"Expression contains unsafe or unsupported nodes\")\n\n return ast.literal_eval(node)\n\n\ndef parse_clinic_intake_payload(raw_payload: str) -> Dict[str, Any]:\n \"\"\"\n Decode an incoming serialized message dictionary safely.\n\n Supports JSON and a restricted subset of Python literals.\n Rejects pickle and eval to prevent unsafe deserialization and code execution.\n \"\"\"\n if raw_payload.startswith(\"pickle:\"):\n # Reject pickle-based payloads outright due to unsafe deserialization risk\n raise ValueError(\"Pickle-based payloads are not supported for security reasons\")\n\n # Try JSON first (most common and safe)\n try:\n data = json.loads(raw_payload)\n except json.JSONDecodeError:\n # Fall back to safe literal eval for Python literals (e.g., dict repr)\n data = _safe_eval_literal(raw_payload)\n\n if not isinstance(data, dict):\n raise ValueError(\"Payload must decode to a dict\")\n\n return data\n```"}]}
{"task_id": "pg-train-xss-0094", "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 `warehouse_ledger` 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_timesheets_badge(title: str, summary: str, link_url: str) -> str:\n \"\"\"Render an HTML card badge with title, summary, and external link.\"\"\"\n return f'<div class=\"badge\" title=\"{title}\"><a href=\"{link_url}\">{summary}</a></div>'\n```\n"}, {"role": "assistant", "content": "```python\nimport html\nfrom urllib.parse import urlparse\n\n# Allowed URL schemes for href attribute to prevent unsafe schemes (e.g. javascript:)\nALLOWED_HREF_SCHEMES = frozenset({\"http\", \"https\", \"mailto\", \"ftp\", \"tel\"})\n\ndef render_timesheets_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 # Parse and validate the link_url scheme\n parsed_url = urlparse(link_url)\n if parsed_url.scheme.lower() not in ALLOWED_HREF_SCHEMES:\n # If scheme is not allowed, render without href to avoid unsafe links\n return f'<div class=\"badge\" title=\"{safe_title}\">{safe_summary}</div>'\n\n # Escape the link_url for safe inclusion in href attribute\n safe_link_url = html.escape(link_url, quote=True)\n\n return f'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_link_url}\">{safe_summary}</a></div>'\n```"}]}
{"task_id": "pg-train-sqli-0096", "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 route_label and return sorted rows.\"\"\"\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, route_label, category_tag, unit_count \"\n f\"FROM shipments \"\n f\"WHERE route_label 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 route_label and return sorted rows.\"\"\"\n allowed_sort_columns = {\"id\", \"route_label\", \"category_tag\", \"unit_count\"}\n if sort_by not in allowed_sort_columns:\n raise ValueError(f\"Invalid sort_by value: {sort_by!r}\")\n\n try:\n limit_int = int(limit)\n except Exception as e:\n raise ValueError(f\"Invalid limit value: {limit}\") from e\n if limit_int <= 0:\n raise ValueError(\"limit must be a positive integer\")\n\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, route_label, category_tag, unit_count \"\n f\"FROM shipments \"\n f\"WHERE route_label LIKE ? \"\n f\"ORDER BY {sort_by} DESC \"\n f\"LIMIT ?\"\n )\n # Use parameterized query for user inputs\n rows = conn.execute(sql, (f\"%{query}%\", limit_int)).fetchall()\n return [dict(r) for r in rows]\n finally:\n conn.close()\n```"}]}
{"task_id": "pg-train-path_traversal-0097", "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 `warehouse_ledger` 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 lookup_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 \"\"\"\n Check if target_path is within base_dir after resolving symlinks and relative components.\n\n Args:\n base_dir: The base directory path.\n target_path: The target file path to check.\n\n Returns:\n True if target_path is inside base_dir, False otherwise.\n \"\"\"\n base_dir_abs = os.path.abspath(os.path.realpath(base_dir))\n target_abs = os.path.abspath(os.path.realpath(target_path))\n common_path = os.path.commonpath([base_dir_abs, target_abs])\n return common_path == base_dir_abs\n\n\ndef lookup_artifact_text(base_dir: str, rel_path: str) -> str:\n \"\"\"\n Read a UTF-8 text file located under base_dir, preventing path traversal attacks.\n\n Args:\n base_dir: The base directory under which the file must reside.\n rel_path: The relative path to the file from base_dir.\n\n Returns:\n The content of the file as a UTF-8 string.\n\n Raises:\n ValueError: If the resolved file path is outside the base_dir.\n FileNotFoundError, PermissionError, OSError: Propagated from open().\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 detected: file outside base_dir\")\n with open(target, \"r\", encoding=\"utf-8\") as fh:\n return fh.read()\n```"}]}
{"task_id": "pg-train-cmd_injection-0098", "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 `payroll_portal` 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_payroll_portal_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\nALLOWED_MODES = frozenset({\"summary\", \"verify\"})\n\ndef run_payroll_portal_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: {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-0099", "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 `warehouse_ledger` 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 query_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 query_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 cheaply\n parsed = urllib.parse.urlparse(url)\n if parsed.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 # This includes localhost, 127.0.0.1, ::1, and any loopback IP ranges\n # Also block link-local and other special-use IPs to reduce SSRF risk\n def is_disallowed_ip(ip_str: str) -> bool:\n try:\n ip = ipaddress.ip_address(ip_str)\n # Block loopback, link-local, multicast, unspecified, and reserved addresses\n if ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_unspecified or ip.is_reserved:\n return True\n return False\n except ValueError:\n # Not an IP address string\n return False\n\n # Block common localhost names explicitly\n localhost_names = {\"localhost\", \"localhost.localdomain\", \"ip6-localhost\"}\n if hostname.lower() in localhost_names:\n raise ValueError(\"Localhost blocked\")\n\n # Resolve hostname to IP addresses using resolver or system DNS\n if resolver is not None:\n try:\n ips = resolver(hostname)\n if not isinstance(ips, (list, tuple)) or not all(isinstance(ip, str) for ip in ips):\n raise ValueError(\"Resolver must return list of IP strings\")\n except Exception as e:\n raise ValueError(f\"Hostname resolution failed: {e}\")\n else:\n try:\n # getaddrinfo returns list of (family, type, proto, canonname, sockaddr)\n infos = socket.getaddrinfo(hostname, None)\n ips = []\n for info in infos:\n sockaddr = info[4]\n ip = sockaddr[0]\n ips.append(ip)\n except Exception as e:\n raise ValueError(f\"Hostname resolution failed: {e}\")\n\n # Check all resolved IPs for disallowed ranges\n for ip in ips:\n if is_disallowed_ip(ip):\n raise ValueError(f\"Resolved IP {ip} is disallowed\")\n\n # If a transport function is provided, use it (assumed safe)\n if transport is not None:\n return transport(url)\n\n # Otherwise, perform the HTTP request safely\n # Use urllib.request.urlopen with timeout, no shell or subprocess involved\n with urllib.request.urlopen(url, timeout=5) as resp:\n return resp.read().decode(\"utf-8\")\n```"}]}
{"task_id": "pg-train-idor_auth-0100", "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 `fleet_dispatch` 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_appointments_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_appointments_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 in store\")\n\n record = store[resource_id]\n\n user_id = session.get('user_id')\n user_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 user_role != 'admin' and record.get('owner_id') != user_id:\n raise PermissionError(\"User does not have permission to access this record\")\n\n if payload:\n protected_fields = {'id', 'owner_id', 'role', 'is_admin'}\n # Check if payload tries to alter protected fields\n if any(field in payload for field in protected_fields):\n raise PermissionError(f\"Payload must not alter protected fields: {protected_fields}\")\n\n # Update record safely\n record.update(payload)\n\n return dict(record)\n```"}]}
{"task_id": "pg-train-unsafe_deser_eval-0101", "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 `warehouse_ledger` 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_warehouse_ledger_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_literal(raw: str) -> Any:\n \"\"\"Safely parse a Python literal from a string using json.loads.\"\"\"\n # Using json.loads instead of eval to avoid code execution.\n # This restricts input to JSON-compatible types only.\n return json.loads(raw)\n\n\ndef parse_warehouse_ledger_payload(raw_payload: str) -> Dict:\n \"\"\"Decode an incoming serialized message dictionary safely.\"\"\"\n if raw_payload.startswith(\"pickle:\"):\n # Reject pickle deserialization due to unsafe code execution risk\n raise ValueError(\"Pickle deserialization is not allowed for security reasons\")\n else:\n data = _safe_eval_literal(raw_payload)\n if not isinstance(data, dict):\n raise ValueError(\"Payload must decode to a dict\")\n return data\n```"}]}
{"task_id": "pg-train-crypto_secrets-0103", "category": "crypto_secrets", "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 Weak Cryptography, Predictable RNG & Secret Exposure in Logs (CWE-327) 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 hashlib\nimport random\nimport string\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage.\"\"\"\n return hashlib.md5(password.encode(\"utf-8\")).hexdigest()\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n return hash_password(password) == stored_hash\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n alphabet = string.ascii_letters + string.digits\n return \"\".join(random.choices(alphabet, k=32))\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for clinic_intake.\"\"\"\n return f\"service=clinic_intake user={user_id} action={action} api_key={api_key}\"\n```\n"}, {"role": "assistant", "content": "```python\nimport hashlib\nimport secrets\nimport hmac\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage using salted SHA-256.\"\"\"\n salt = secrets.token_bytes(16) # 16 bytes salt\n pwd_bytes = password.encode(\"utf-8\")\n # Use HMAC with salt as key for hashing (better than simple hash)\n pwd_hash = hmac.new(salt, pwd_bytes, hashlib.sha256).digest()\n # Store salt + hash hex-encoded, separated by $\n return f\"{salt.hex()}${pwd_hash.hex()}\"\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored salted hash.\"\"\"\n try:\n salt_hex, hash_hex = stored_hash.split(\"$\", 1)\n salt = bytes.fromhex(salt_hex)\n pwd_bytes = password.encode(\"utf-8\")\n expected_hash = bytes.fromhex(hash_hex)\n computed_hash = hmac.new(salt, pwd_bytes, hashlib.sha256).digest()\n # Use hmac.compare_digest to prevent timing attacks\n return hmac.compare_digest(computed_hash, expected_hash)\n except (ValueError, TypeError):\n # Malformed stored_hash or hex decode error\n return False\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n # Use secrets.token_urlsafe to generate a secure token\n # token_urlsafe returns base64 encoded string, length varies, so generate 24 bytes (~32 chars)\n return secrets.token_urlsafe(24)\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for clinic_intake with redacted api_key.\"\"\"\n # Redact api_key except last 4 chars for security\n if len(api_key) > 4:\n redacted_key = \"*\" * (len(api_key) - 4) + api_key[-4:]\n else:\n redacted_key = \"*\" * len(api_key)\n return f\"service=clinic_intake user={user_id} action={action} api_key={redacted_key}\"\n```"}]}
{"task_id": "pg-train-sqli-0104", "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 `fleet_dispatch` 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_timesheets(db_path: str, query: str, sort_by: str = \"priority_rank\", limit: int = 10) -> list[dict]:\n \"\"\"Search timesheets matching query on project_code and return sorted rows.\"\"\"\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, project_code, category_tag, priority_rank \"\n f\"FROM timesheets \"\n f\"WHERE project_code 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_timesheets(db_path: str, query: str, sort_by: str = \"priority_rank\", limit: int = 10) -> list[dict]:\n \"\"\"Search timesheets matching query on project_code and return sorted rows.\"\"\"\n # Validate sort_by against an allowlist of column names to prevent SQL injection\n allowed_sort_columns = {\"id\", \"project_code\", \"category_tag\", \"priority_rank\"}\n if sort_by not in allowed_sort_columns:\n raise ValueError(f\"Invalid sort_by column: {sort_by}\")\n\n # Validate limit is a positive integer\n if not isinstance(limit, int) or limit <= 0:\n raise ValueError(\"limit must be a positive integer\")\n\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n # Use parameterized query for user input to prevent SQL injection\n sql = (\n f\"SELECT id, project_code, category_tag, priority_rank \"\n f\"FROM timesheets \"\n f\"WHERE project_code LIKE ? \"\n f\"ORDER BY {sort_by} DESC \"\n f\"LIMIT ?\"\n )\n # Use parameterized inputs; query wrapped with % for LIKE\n params = (f\"%{query}%\", limit)\n rows = conn.execute(sql, params).fetchall()\n return [dict(r) for r in rows]\n finally:\n conn.close()\n```"}]}
{"task_id": "pg-train-path_traversal-0105", "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 `warehouse_ledger` 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 retrieve_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 located within base_dir after resolving symlinks and relative components.\"\"\"\n base_dir = os.path.abspath(base_dir)\n target_path = os.path.abspath(target_path)\n return os.path.commonpath([base_dir]) == os.path.commonpath([base_dir, target_path])\n\n\ndef retrieve_artifact_text(base_dir: str, rel_path: str) -> str:\n \"\"\"\n Read a UTF-8 text file located under base_dir.\n\n Raises:\n ValueError: If the resolved file path is outside the base_dir.\n FileNotFoundError, IOError: If the file cannot be read.\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-0106", "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 `warehouse_ledger` 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_warehouse_ledger_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\nfrom pathlib import Path\n\n# Allowed modes for the warehouse ledger tool\nALLOWED_MODES = frozenset({\"summary\", \"verify\"})\n\ndef run_warehouse_ledger_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 # Validate mode against allow-list\n if mode not in ALLOWED_MODES:\n raise ValueError(f\"Invalid mode '{mode}'. Allowed modes: {ALLOWED_MODES}\")\n\n # Resolve and validate script_path to prevent directory traversal or unexpected scripts\n script_path_obj = Path(script_path).resolve()\n # Optionally, you could restrict script_path to a known directory, e.g.:\n # BASE_SCRIPT_DIR = Path(\"/opt/warehouse/scripts\").resolve()\n # if not script_path_obj.is_file() or BASE_SCRIPT_DIR not in script_path_obj.parents:\n # raise ValueError(\"Invalid script path\")\n\n if not script_path_obj.is_file():\n raise FileNotFoundError(f\"Script not found: {script_path_obj}\")\n\n # Construct argument vector without shell=True to avoid shell injection\n cmd = [\n sys.executable,\n str(script_path_obj),\n \"--mode\",\n mode,\n target_name,\n ]\n\n proc = subprocess.run(cmd, capture_output=True, text=True, check=True)\n return proc.stdout.strip()\n```"}]}
{"task_id": "pg-train-ssrf-0107", "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 `warehouse_ledger` 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 query_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 ipaddress\nimport socket\nfrom urllib.parse import urlparse\nimport urllib.request\n\n\ndef query_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 cheaply\n parsed = urlparse(url)\n if parsed.scheme not in (\"http\", \"https\"):\n raise ValueError(\"Unsupported URL scheme\")\n\n # Block localhost and local IPs by hostname and IP resolution\n hostname = parsed.hostname\n if not hostname:\n raise ValueError(\"URL must have a hostname\")\n\n # Reject explicit localhost names immediately\n if hostname.lower() in (\"localhost\", \"localhost.localdomain\", \"ip6-localhost\"):\n raise ValueError(\"Localhost blocked\")\n\n # Resolve hostname to IPs using provided resolver or default DNS resolver\n try:\n if resolver is not None:\n ips = resolver(hostname)\n if not isinstance(ips, (list, tuple)) or not all(isinstance(ip, str) for ip in ips):\n raise ValueError(\"Resolver must return list of IP strings\")\n else:\n # Use socket.getaddrinfo to get all IP addresses (IPv4/IPv6)\n addrinfos = socket.getaddrinfo(hostname, None)\n ips = list({ai[4][0] for ai in addrinfos})\n except Exception as e:\n raise ValueError(f\"Failed to resolve hostname: {e}\")\n\n # Check each resolved IP to ensure it is public (not private, loopback, link-local, multicast, or 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_link_local or ip.is_multicast or ip.is_reserved or ip.is_unspecified:\n raise ValueError(f\"Blocked IP address: {ip_str}\")\n\n # Use transport if provided (trusted caller responsibility)\n if transport is not None:\n return transport(url)\n\n # Perform the HTTP request with timeout and no redirects allowed (to avoid redirect SSRF)\n class NoRedirectHandler(urllib.request.HTTPRedirectHandler):\n def redirect_request(self, req, fp, code, msg, headers, newurl):\n raise ValueError(\"Redirects are not allowed\")\n\n opener = urllib.request.build_opener(NoRedirectHandler())\n with opener.open(url, timeout=5) as resp:\n return resp.read().decode(\"utf-8\")\n```"}]}
{"task_id": "pg-train-idor_auth-0108", "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 `payroll_portal` 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_vehicles_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_vehicles_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 not found\")\n record = store[resource_id]\n\n user_id = session.get('user_id')\n user_role = session.get('role')\n if user_id is None:\n raise PermissionError(\"Authentication required\")\n if not (user_id == record.get('owner_id') or user_role == 'admin'):\n raise PermissionError(\"Access denied\")\n\n if payload:\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 record.update(payload)\n\n return dict(record)\n```"}]}
{"task_id": "pg-train-crypto_secrets-0111", "category": "crypto_secrets", "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 Weak Cryptography, Predictable RNG & Secret Exposure in Logs (CWE-327) 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 hashlib\nimport random\nimport string\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage.\"\"\"\n return hashlib.md5(password.encode(\"utf-8\")).hexdigest()\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n return hash_password(password) == stored_hash\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n alphabet = string.ascii_letters + string.digits\n return \"\".join(random.choices(alphabet, k=32))\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for payroll_portal.\"\"\"\n return f\"service=payroll_portal user={user_id} action={action} api_key={api_key}\"\n```\n"}, {"role": "assistant", "content": "```python\nimport hashlib\nimport secrets\nimport hmac\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage using salted SHA-256.\"\"\"\n # Use a cryptographically secure random salt\n salt = secrets.token_bytes(16)\n # Derive the hash using SHA-256 with the salt\n pwd_hash = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100_000)\n # Store salt and hash together, hex-encoded, separated by $\n return f\"{salt.hex()}${pwd_hash.hex()}\"\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n try:\n salt_hex, hash_hex = stored_hash.split('$', 1)\n salt = bytes.fromhex(salt_hex)\n expected_hash = bytes.fromhex(hash_hex)\n except (ValueError, TypeError):\n # Malformed stored hash\n return False\n\n pwd_hash = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100_000)\n # Use hmac.compare_digest to prevent timing attacks\n return hmac.compare_digest(pwd_hash, expected_hash)\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n # Use secrets.token_urlsafe to generate a secure token\n # token_urlsafe(n) returns about 4/3*n bytes, so 24 bytes -> 32 chars approx\n return secrets.token_urlsafe(24)\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for payroll_portal.\"\"\"\n # Redact the api_key to avoid secret exposure in logs\n redacted_key = f\"{api_key[:4]}****{api_key[-4:]}\" if len(api_key) >= 8 else \"****\"\n return f\"service=payroll_portal user={user_id} action={action} api_key={redacted_key}\"\n```"}]}
{"task_id": "pg-train-sqli-0112", "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 `warehouse_ledger` 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 lookup_shipments(db_path: str, query: str, sort_by: str = \"priority_rank\", limit: int = 10) -> list[dict]:\n \"\"\"Search shipments matching query on manifest_note and return sorted rows.\"\"\"\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, manifest_note, category_tag, priority_rank \"\n f\"FROM shipments \"\n f\"WHERE manifest_note 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\ndef lookup_shipments(db_path: str, query: str, sort_by: str = \"priority_rank\", limit: int = 10) -> list[dict]:\n \"\"\"Search shipments matching query on manifest_note and return sorted rows.\"\"\"\n # Validate limit\n if not isinstance(limit, int) or limit <= 0:\n raise ValueError(\"limit must be a positive integer\")\n\n # Define allow-list of sortable columns to prevent SQL injection via sort_by\n allowed_sort_columns = {\"priority_rank\", \"id\", \"category_tag\", \"manifest_note\"}\n if sort_by not in allowed_sort_columns:\n raise ValueError(f\"Invalid sort_by column: {sort_by}\")\n\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, manifest_note, category_tag, priority_rank \"\n f\"FROM shipments \"\n f\"WHERE manifest_note LIKE ? \"\n f\"ORDER BY {sort_by} DESC \"\n f\"LIMIT ?\"\n )\n # Use parameterized queries for user inputs\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-0113", "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 `warehouse_ledger` 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 lookup_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 components.\"\"\"\n base_dir_real = os.path.realpath(base_dir)\n target_real = os.path.realpath(target_path)\n common_path = os.path.commonpath([base_dir_real, target_real])\n return common_path == base_dir_real\n\n\ndef lookup_artifact_text(base_dir: str, rel_path: str) -> str:\n \"\"\"\n Read a UTF-8 text file located under base_dir.\n\n Prevents path traversal by ensuring the resolved file path is within base_dir.\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-0114", "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 `warehouse_ledger` 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_warehouse_ledger_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\nfrom typing import Literal\n\n# Allowed modes for the warehouse ledger tool\nALLOWED_MODES: frozenset[Literal['summary', 'verify']] = frozenset({'summary', 'verify'})\n\ndef run_warehouse_ledger_tool(script_path: str, mode: str, target_name: str) -> str:\n \"\"\"\n Execute the local helper script with mode ('summary' or 'verify') and positional target_name.\n\n This function uses subprocess.run with argument vector to prevent OS command injection.\n It validates the mode against an allow-list and treats script_path and target_name as literal arguments.\n \"\"\"\n if mode not in ALLOWED_MODES:\n raise ValueError(f\"Invalid mode: {mode}. Allowed modes are {ALLOWED_MODES}\")\n\n # Construct argument list without shell=True to prevent injection\n cmd = [sys.executable, script_path, '--mode', mode, target_name]\n\n proc = subprocess.run(cmd, capture_output=True, text=True, check=True)\n return proc.stdout.strip()\n```"}]}
{"task_id": "pg-train-ssrf-0115", "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 `payroll_portal` 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 query_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 query_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 first (cheap)\n parsed = urllib.parse.urlparse(url)\n if parsed.scheme not in (\"http\", \"https\"):\n raise ValueError(\"Unsupported URL scheme\")\n\n hostname = parsed.hostname\n if not hostname:\n raise ValueError(\"Invalid URL: no hostname\")\n\n # Block localhost and loopback names explicitly\n # Normalize hostname to lowercase for comparison\n hostname_lower = hostname.lower()\n if hostname_lower in (\"localhost\", \"localhost.localdomain\", \"ip6-localhost\"):\n raise ValueError(\"Localhost blocked\")\n\n # Resolve hostname to IP addresses using resolver or system DNS\n if resolver is not None:\n try:\n resolved_ips = resolver(hostname)\n if not isinstance(resolved_ips, (list, tuple)) or not all(isinstance(ip, str) for ip in resolved_ips):\n raise ValueError(\"Resolver must return list of IP strings\")\n except Exception as e:\n raise ValueError(f\"Custom resolver failed: {e}\") from e\n else:\n try:\n # getaddrinfo returns (family, type, proto, canonname, sockaddr)\n infos = socket.getaddrinfo(hostname, None, proto=socket.IPPROTO_TCP)\n resolved_ips = []\n for info in infos:\n sockaddr = info[4]\n ip = sockaddr[0]\n resolved_ips.append(ip)\n except socket.gaierror as e:\n raise ValueError(f\"DNS resolution failed: {e}\") from e\n\n if not resolved_ips:\n raise ValueError(\"Hostname did not resolve to any IP\")\n\n # Check all resolved IPs are public routable (not private, loopback, link-local, multicast)\n for ip_str in resolved_ips:\n try:\n ip_obj = ipaddress.ip_address(ip_str)\n except ValueError:\n raise ValueError(f\"Invalid IP address resolved: {ip_str}\")\n if ip_obj.is_loopback or ip_obj.is_private or ip_obj.is_link_local or ip_obj.is_multicast or ip_obj.is_reserved:\n raise ValueError(f\"Resolved IP {ip_str} is not allowed (private, loopback, link-local, multicast, or reserved)\")\n\n # At this point, URL and resolved IPs are validated safe\n\n if transport is not None:\n # Use transport function (assumed safe)\n return transport(url)\n\n # Use urllib.request.urlopen with timeout and no redirects to localhost (already checked)\n with urllib.request.urlopen(url, timeout=5) as resp:\n return resp.read().decode(\"utf-8\")\n```"}]}
{"task_id": "pg-train-idor_auth-0116", "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 `fleet_dispatch` 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 user_role = session.get('role')\n\n # Authorization check: user must be owner or admin\n if user_id != record.get('owner_id') and user_role != 'admin':\n raise PermissionError(\"User not authorized to access this resource\")\n\n if payload is None:\n # Read-only access, return a copy of the record\n return dict(record)\n\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(f\"Modification of protected fields {protected_fields} is not allowed\")\n\n # Update the record with allowed fields only\n record.update(payload)\n\n return dict(record)\n```"}]}
{"task_id": "pg-train-xss-0118", "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 `payroll_portal` 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_appointments_badge(title: str, summary: str, link_url: str) -> str:\n \"\"\"Render an HTML card badge with title, summary, and external link.\"\"\"\n return f'<div class=\"badge\" title=\"{title}\"><a href=\"{link_url}\">{summary}</a></div>'\n```\n"}, {"role": "assistant", "content": "```python\nimport html\nfrom urllib.parse import urlparse\n\n# Allowed URL schemes for href attributes\nALLOWED_HREF_SCHEMES = frozenset({\"http\", \"https\", \"mailto\", \"tel\", \"\"})\n\ndef render_appointments_badge(title: str, summary: str, link_url: str) -> str:\n \"\"\"Render an HTML card badge with title, summary, and external link.\n\n Escapes HTML in title and summary to prevent XSS.\n Validates link_url scheme to prevent unsafe href schemes.\n \"\"\"\n # Escape title and summary to prevent XSS\n safe_title = html.escape(title, quote=True)\n safe_summary = html.escape(summary)\n\n # Parse and validate the URL scheme\n parsed_url = urlparse(link_url)\n scheme = parsed_url.scheme.lower()\n\n # If scheme is not allowed, neutralize the href to prevent unsafe links\n if scheme not in ALLOWED_HREF_SCHEMES:\n safe_href = \"#\"\n else:\n # Rebuild the URL to avoid any control characters or injections\n # Use the original link_url but escape quotes to be safe in attribute context\n # Since href is inside double quotes, escape double quotes if any\n # Although quotes in URLs are rare, this is defensive\n safe_href = html.escape(link_url, quote=True)\n\n return f'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_href}\">{safe_summary}</a></div>'\n```"}]}
{"task_id": "pg-train-crypto_secrets-0119", "category": "crypto_secrets", "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 Weak Cryptography, Predictable RNG & Secret Exposure in Logs (CWE-327) 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 hashlib\nimport random\nimport string\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage.\"\"\"\n return hashlib.md5(password.encode(\"utf-8\")).hexdigest()\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n return hash_password(password) == stored_hash\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n alphabet = string.ascii_letters + string.digits\n return \"\".join(random.choices(alphabet, k=32))\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for fleet_dispatch.\"\"\"\n return f\"service=fleet_dispatch user={user_id} action={action} api_key={api_key}\"\n```\n"}, {"role": "assistant", "content": "```python\nimport hashlib\nimport secrets\nimport hmac\nimport html\n\n\n# Use a strong, slow password hashing function with salt (PBKDF2-HMAC-SHA256)\ndef hash_password(password: str, salt: bytes = None) -> str:\n \"\"\"Hash a user password for storage using PBKDF2-HMAC-SHA256 with a random salt.\"\"\"\n if salt is None:\n salt = secrets.token_bytes(16)\n # 100,000 iterations is a reasonable minimum for PBKDF2\n dk = hashlib.pbkdf2_hmac(\"sha256\", password.encode(\"utf-8\"), salt, 100_000)\n # Store salt and hash hex-encoded, separated by $\n return f\"{salt.hex()}${dk.hex()}\"\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n try:\n salt_hex, hash_hex = stored_hash.split(\"$\", 1)\n salt = bytes.fromhex(salt_hex)\n expected_hash = bytes.fromhex(hash_hex)\n except (ValueError, TypeError):\n # Malformed stored_hash format\n return False\n\n # Derive hash from provided password and salt\n derived_hash = hashlib.pbkdf2_hmac(\"sha256\", password.encode(\"utf-8\"), salt, 100_000)\n # Use hmac.compare_digest to prevent timing attacks\n return hmac.compare_digest(derived_hash, expected_hash)\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n # Use secrets.token_urlsafe which returns a base64-url-encoded token\n # 24 bytes of randomness ~ 32 characters base64-url encoded\n return secrets.token_urlsafe(24)\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for fleet_dispatch with safe escaping.\"\"\"\n # Escape user inputs to prevent log injection or accidental control chars\n safe_user_id = html.escape(user_id, quote=True)\n safe_action = html.escape(action, quote=True)\n safe_api_key = \"[REDACTED]\"\n return f\"service=fleet_dispatch user={safe_user_id} action={safe_action} api_key={safe_api_key}\"\n```"}]}
{"task_id": "pg-train-sqli-0120", "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 `clinic_intake` 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 = \"created_at\", 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, created_at \"\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 = \"created_at\", 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\", \"created_at\"}\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 conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, visit_reason, category_tag, created_at \"\n f\"FROM shipments \"\n f\"WHERE visit_reason LIKE ? \"\n f\"ORDER BY {sort_by} DESC \"\n f\"LIMIT ?\"\n )\n # Use parameterized query for user inputs\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-0121", "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 retrieve_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 \"\"\"\n Check if the target_path is located within base_dir after canonicalization.\n \"\"\"\n base_dir = os.path.abspath(base_dir)\n target_path = os.path.abspath(target_path)\n return os.path.commonpath([base_dir]) == os.path.commonpath([base_dir, target_path])\n\n\ndef retrieve_artifact_text(base_dir: str, rel_path: str) -> str:\n \"\"\"Read a UTF-8 text file located under base_dir, preventing path traversal.\"\"\"\n target = os.path.join(base_dir, rel_path)\n if not _is_within_directory(base_dir, target):\n raise ValueError(\"Attempted Path Traversal detected\")\n with open(target, \"r\", encoding=\"utf-8\") as fh:\n return fh.read()\n```"}]}
{"task_id": "pg-train-cmd_injection-0122", "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 `warehouse_ledger` 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_warehouse_ledger_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 warehouse ledger tool\nALLOWED_MODES = frozenset({\"summary\", \"verify\"})\n\ndef run_warehouse_ledger_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 list to avoid shell injection vulnerabilities\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-0123", "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 retrieve_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 retrieve_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 # Validate scheme early\n parsed = urllib.parse.urlparse(url)\n if parsed.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 direct IPs that are loopback or link-local or private\n # Use resolver if provided, else use socket.getaddrinfo for DNS resolution\n def resolve(host: str) -> list[str]:\n if resolver:\n ips = resolver(host)\n if not isinstance(ips, (list, tuple)):\n raise ValueError(\"Resolver must return a list of IP strings\")\n return ips\n else:\n try:\n # getaddrinfo returns tuples with sockaddr as last element\n infos = socket.getaddrinfo(host, None)\n ips = []\n for info in infos:\n sockaddr = info[-1]\n ip = sockaddr[0]\n ips.append(ip)\n return ips\n except socket.gaierror as e:\n raise ValueError(f\"DNS resolution failed for host {host}\") from e\n\n ips = resolve(hostname)\n\n for ip_str in ips:\n try:\n ip_obj = ipaddress.ip_address(ip_str)\n except ValueError:\n raise ValueError(f\"Invalid IP address resolved: {ip_str}\")\n\n if ip_obj.is_loopback:\n raise ValueError(\"Access to loopback IPs is blocked\")\n if ip_obj.is_link_local:\n raise ValueError(\"Access to link-local IPs is blocked\")\n if ip_obj.is_private:\n raise ValueError(\"Access to private IPs is blocked\")\n if ip_obj.is_reserved:\n raise ValueError(\"Access to reserved IPs is blocked\")\n if ip_obj.is_multicast:\n raise ValueError(\"Access to multicast IPs is blocked\")\n\n # Also block localhost by hostname explicitly (case insensitive)\n if hostname.lower() == \"localhost\":\n raise ValueError(\"Localhost hostname is blocked\")\n\n # Use transport if provided\n if transport is not None:\n return transport(url)\n\n # Safe fetch with urllib.request.urlopen\n with urllib.request.urlopen(url, timeout=5) as resp:\n # Optionally check response content-type or size here if needed\n return resp.read().decode(\"utf-8\")\n```"}]}
{"task_id": "pg-train-idor_auth-0124", "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 `clinic_intake` 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_appointments_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_appointments_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 user_role = session.get('role')\n\n # Enforce access control: only owner or admin can access\n if user_id != record.get('owner_id') and user_role != 'admin':\n raise PermissionError(\"Access denied: user not authorized to access this record\")\n\n if payload is None:\n # Read-only access allowed\n return dict(record)\n\n # Prevent 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(f\"Modification of protected fields {protected_fields} is not allowed\")\n\n # Update allowed fields only\n record.update(payload)\n return dict(record)\n```"}]}
{"task_id": "pg-train-crypto_secrets-0127", "category": "crypto_secrets", "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 Weak Cryptography, Predictable RNG & Secret Exposure in Logs (CWE-327) 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 hashlib\nimport random\nimport string\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage.\"\"\"\n return hashlib.md5(password.encode(\"utf-8\")).hexdigest()\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n return hash_password(password) == stored_hash\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n alphabet = string.ascii_letters + string.digits\n return \"\".join(random.choices(alphabet, k=32))\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for payroll_portal.\"\"\"\n return f\"service=payroll_portal user={user_id} action={action} api_key={api_key}\"\n```\n"}, {"role": "assistant", "content": "```python\nimport hashlib\nimport secrets\nimport hmac\nimport html\n\n\n# Constants for PBKDF2\n_PBKDF2_ITERATIONS = 100_000\n_SALT_LENGTH = 16\n_HASH_NAME = \"sha256\"\n_KEY_LENGTH = 32 # bytes\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage using PBKDF2-HMAC-SHA256 with a salt.\"\"\"\n salt = secrets.token_bytes(_SALT_LENGTH)\n dk = hashlib.pbkdf2_hmac(_HASH_NAME, password.encode(\"utf-8\"), salt, _PBKDF2_ITERATIONS, dklen=_KEY_LENGTH)\n # Store as hex: iterations$salt$hash\n return f\"{_PBKDF2_ITERATIONS}${salt.hex()}${dk.hex()}\"\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n try:\n iterations_str, salt_hex, hash_hex = stored_hash.split(\"$\")\n iterations = int(iterations_str)\n salt = bytes.fromhex(salt_hex)\n stored_dk = bytes.fromhex(hash_hex)\n except (ValueError, TypeError):\n # Malformed stored_hash\n return False\n\n dk = hashlib.pbkdf2_hmac(_HASH_NAME, password.encode(\"utf-8\"), salt, iterations, dklen=len(stored_dk))\n # Use hmac.compare_digest to prevent timing attacks\n return hmac.compare_digest(dk, stored_dk)\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n # secrets.token_urlsafe returns a string with ~1.3 chars per byte, so 24 bytes ~ 32 chars\n return secrets.token_urlsafe(24)\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for payroll_portal with safe escaping to avoid secret exposure.\"\"\"\n # Escape user inputs to avoid log injection or accidental secret exposure\n safe_user_id = html.escape(user_id, quote=True)\n safe_action = html.escape(action, quote=True)\n # Redact api_key to avoid secret exposure in logs\n redacted_api_key = \"<redacted>\"\n return f\"service=payroll_portal user={safe_user_id} action={safe_action} api_key={redacted_api_key}\"\n```"}]}
{"task_id": "pg-train-sqli-0128", "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 retrieve_shipments(db_path: str, query: str, sort_by: str = \"unit_count\", limit: int = 10) -> list[dict]:\n \"\"\"Search shipments matching query on project_code and return sorted rows.\"\"\"\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, project_code, category_tag, unit_count \"\n f\"FROM shipments \"\n f\"WHERE project_code 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 retrieve_shipments(db_path: str, query: str, sort_by: str = \"unit_count\", limit: int = 10) -> list[dict]:\n \"\"\"Search shipments matching query on project_code and return sorted rows.\"\"\"\n # Allowed columns for sorting to prevent SQL injection via identifiers\n allowed_sort_columns = {\"id\", \"project_code\", \"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 query for the LIKE clause\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, project_code, category_tag, unit_count \"\n f\"FROM shipments \"\n f\"WHERE project_code LIKE ? \"\n f\"ORDER BY {sort_by} DESC \"\n f\"LIMIT ?\"\n )\n # Use parameterized query arguments\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-0129", "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 inside base_dir after resolving symlinks and relative parts.\"\"\"\n base_dir_abs = os.path.abspath(base_dir)\n target_abs = os.path.abspath(target_path)\n # Ensure trailing separator to avoid partial matching\n base_dir_abs_slash = base_dir_abs if base_dir_abs.endswith(os.sep) else base_dir_abs + os.sep\n return target_abs == base_dir_abs or target_abs.startswith(base_dir_abs_slash)\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 base_dir.\n FileNotFoundError, OSError: Propagated from open().\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 detected: file outside base_dir\")\n with open(target, \"r\", encoding=\"utf-8\") as fh:\n return fh.read()\n```"}]}
{"task_id": "pg-train-cmd_injection-0130", "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 `fleet_dispatch` 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_fleet_dispatch_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\nimport os\n\n# Allowed modes for the fleet dispatch tool\nALLOWED_MODES = frozenset({\"summary\", \"verify\"})\n\ndef run_fleet_dispatch_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\n Uses a safe subprocess invocation with argument vector to prevent command injection.\n Validates mode against an allowlist.\n \"\"\"\n if mode not in ALLOWED_MODES:\n raise ValueError(f\"Invalid mode: {mode!r}. Allowed modes: {sorted(ALLOWED_MODES)}\")\n\n # Resolve absolute path for script_path and ensure it exists and is a file\n script_path = os.path.abspath(script_path)\n if not os.path.isfile(script_path):\n raise FileNotFoundError(f\"Script path does not exist or is not a file: {script_path}\")\n\n # Defensive: ensure target_name is a non-empty string (optional, but good practice)\n if not isinstance(target_name, str) or not target_name.strip():\n raise ValueError(\"target_name must be a non-empty string\")\n\n # Construct the argument vector safely without shell=True\n cmd = [\n sys.executable,\n script_path,\n \"--mode\",\n mode,\n target_name,\n ]\n\n proc = subprocess.run(cmd, capture_output=True, text=True, check=True)\n return proc.stdout.strip()\n```"}]}
{"task_id": "pg-train-ssrf-0131", "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 query_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 ipaddress\nimport socket\n\n\ndef query_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 # Validate scheme\n parsed = urllib.parse.urlparse(url)\n if parsed.scheme not in (\"http\", \"https\"):\n raise ValueError(\"Unsupported URL scheme\")\n\n # Block localhost and private IPs by hostname and resolved IP\n hostname = parsed.hostname\n if hostname is None:\n raise ValueError(\"Invalid URL: missing hostname\")\n\n # Canonicalize hostname to lowercase\n hostname = hostname.lower()\n\n # Block localhost and loopback names explicitly\n if hostname in (\"localhost\", \"127.0.0.1\", \"::1\"):\n raise ValueError(\"Localhost blocked\")\n\n # Resolve hostname to IP addresses using provided resolver or socket.getaddrinfo\n def default_resolver(hostname):\n try:\n infos = socket.getaddrinfo(hostname, None)\n return [info[4][0] for info in infos]\n except socket.gaierror:\n return []\n\n resolver_func = resolver or default_resolver\n ips = resolver_func(hostname)\n if not ips:\n raise ValueError(\"Could not resolve hostname\")\n\n # Check each resolved IP to ensure it is not loopback, link-local, or private\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\n if ip.is_loopback or ip.is_link_local or ip.is_private:\n raise ValueError(f\"Blocked IP address: {ip_str}\")\n\n # If transport override is provided, use it\n if transport is not None:\n return transport(url)\n\n # Perform the actual HTTP(S) request\n with urllib.request.urlopen(url, timeout=5) as resp:\n return resp.read().decode(\"utf-8\")\n```"}]}
{"task_id": "pg-train-idor_auth-0132", "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 `fleet_dispatch` 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_timesheets_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_timesheets_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 user_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 user_role != 'admin':\n raise PermissionError(\"User not authorized to access this resource\")\n\n if payload:\n # Prevent 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(f\"Modification of protected fields {protected_fields} is not allowed\")\n\n # Update the record safely\n record.update(payload)\n\n return dict(record)\n```"}]}
{"task_id": "pg-train-xss-0134", "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'<div class=\"badge\" title=\"{title}\"><a href=\"{link_url}\">{summary}</a></div>'\n```\n"}, {"role": "assistant", "content": "```python\nimport html\nfrom urllib.parse import urlparse\n\n# Allowed URL schemes for href attributes\n_ALLOWED_HREF_SCHEMES = frozenset({\"http\", \"https\", \"mailto\", \"tel\", \"\"})\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 for safe HTML embedding\n safe_title = html.escape(title, quote=True)\n safe_summary = html.escape(summary)\n\n # Parse and validate the link_url scheme to prevent unsafe href schemes (e.g., javascript:)\n parsed_url = urlparse(link_url)\n if parsed_url.scheme not in _ALLOWED_HREF_SCHEMES:\n # If scheme is disallowed, render link_url as empty string to avoid unsafe href\n safe_link_url = \"\"\n else:\n # Escape the link_url for safe HTML attribute embedding\n safe_link_url = html.escape(link_url, quote=True)\n\n return f'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_link_url}\">{safe_summary}</a></div>'\n```"}]}
{"task_id": "pg-train-crypto_secrets-0135", "category": "crypto_secrets", "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 Weak Cryptography, Predictable RNG & Secret Exposure in Logs (CWE-327) 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 hashlib\nimport random\nimport string\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage.\"\"\"\n return hashlib.md5(password.encode(\"utf-8\")).hexdigest()\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n return hash_password(password) == stored_hash\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n alphabet = string.ascii_letters + string.digits\n return \"\".join(random.choices(alphabet, k=32))\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for fleet_dispatch.\"\"\"\n return f\"service=fleet_dispatch user={user_id} action={action} api_key={api_key}\"\n```\n"}, {"role": "assistant", "content": "```python\nimport hashlib\nimport secrets\nimport hmac\nimport logging\n\n# Configure logger for audit logs, redacting secrets\nlogger = logging.getLogger(\"fleet_dispatch\")\n# Example handler setup (in real deployment, configure handlers/formatters as needed)\nif not logger.hasHandlers():\n handler = logging.StreamHandler()\n formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')\n handler.setFormatter(formatter)\n logger.addHandler(handler)\nlogger.setLevel(logging.INFO)\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage using a salted, slow hash (PBKDF2-HMAC-SHA256).\"\"\"\n salt = secrets.token_bytes(16) # 128-bit salt\n # Use 100,000 iterations for PBKDF2 (recommended minimum)\n dk = hashlib.pbkdf2_hmac(\"sha256\", password.encode(\"utf-8\"), salt, 100_000)\n # Store salt and hash together, hex encoded, separated by $\n return f\"{salt.hex()}${dk.hex()}\"\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n try:\n salt_hex, hash_hex = stored_hash.split(\"$\", 1)\n salt = bytes.fromhex(salt_hex)\n expected_hash = bytes.fromhex(hash_hex)\n test_hash = hashlib.pbkdf2_hmac(\"sha256\", password.encode(\"utf-8\"), salt, 100_000)\n # Use hmac.compare_digest to prevent timing attacks\n return hmac.compare_digest(test_hash, expected_hash)\n except (ValueError, TypeError):\n # Malformed stored_hash\n return False\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n # Use secrets.token_urlsafe to generate a secure random token\n # token_urlsafe returns base64url-encoded bytes; length parameter is in bytes before encoding\n # 24 bytes -> 32 chars approx base64url encoded\n return secrets.token_urlsafe(24)\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for fleet_dispatch with api_key redacted.\"\"\"\n redacted_api_key = \"[REDACTED]\"\n log_entry = f\"service=fleet_dispatch user={user_id} action={action} api_key={redacted_api_key}\"\n # Log the audit entry securely without exposing secrets\n logger.info(log_entry)\n return log_entry\n```"}]}
{"task_id": "pg-train-sqli-0136", "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 `warehouse_ledger` 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 lookup_timesheets(db_path: str, query: str, sort_by: str = \"created_at\", limit: int = 10) -> list[dict]:\n \"\"\"Search timesheets 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, created_at \"\n f\"FROM timesheets \"\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 lookup_timesheets(db_path: str, query: str, sort_by: str = \"created_at\", limit: int = 10) -> list[dict]:\n \"\"\"Search timesheets matching query on visit_reason and return sorted rows.\"\"\"\n # Allow-list of valid sortable columns to prevent SQL injection via sort_by\n valid_sort_columns = {\"id\", \"visit_reason\", \"category_tag\", \"created_at\"}\n\n if sort_by not in valid_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 query for user input (query and limit)\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, visit_reason, category_tag, created_at \"\n f\"FROM timesheets \"\n f\"WHERE visit_reason LIKE ? \"\n f\"ORDER BY {sort_by} DESC \"\n f\"LIMIT ?\"\n )\n param_query = f\"%{query}%\"\n rows = conn.execute(sql, (param_query, limit)).fetchall()\n return [dict(r) for r in rows]\n finally:\n conn.close()\n```"}]}
{"task_id": "pg-train-path_traversal-0137", "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 `payroll_portal` 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 retrieve_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 canonicalization.\"\"\"\n base_dir_canon = os.path.abspath(base_dir)\n target_canon = os.path.abspath(target_path)\n # Ensure trailing separator on base_dir for strict prefix check\n base_dir_canon_slash = base_dir_canon if base_dir_canon.endswith(os.sep) else base_dir_canon + os.sep\n return target_canon == base_dir_canon or target_canon.startswith(base_dir_canon_slash)\n\n\ndef retrieve_artifact_text(base_dir: str, rel_path: str) -> str:\n \"\"\"\n Read a UTF-8 text file located under base_dir, preventing path traversal.\n\n Raises:\n ValueError: If the resolved path is outside the base_dir.\n FileNotFoundError, OSError: If the file cannot be read.\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 base_dir\")\n with open(target, \"r\", encoding=\"utf-8\") as fh:\n return fh.read()\n```"}]}
{"task_id": "pg-train-cmd_injection-0138", "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 `payroll_portal` 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_payroll_portal_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 payroll portal tool\nALLOWED_MODES = frozenset({\"summary\", \"verify\"})\n\ndef run_payroll_portal_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 # Construct argument vector safely without shell=True\n cmd = [sys.executable, script_path, \"--mode\", mode, target_name]\n\n proc = subprocess.run(cmd, capture_output=True, text=True, check=True)\n return proc.stdout.strip()\n```"}]}
{"task_id": "pg-train-ssrf-0139", "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 `fleet_dispatch` 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 lookup_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 lookup_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 # Validate scheme cheaply\n parsed = urllib.parse.urlparse(url)\n if parsed.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 common local network names\n blocked_hostnames = {\"localhost\", \"ip6-localhost\"}\n if hostname.lower() in blocked_hostnames:\n raise ValueError(\"Localhost blocked\")\n\n # Resolve hostname to IP addresses using provided resolver or system DNS\n if resolver is not None:\n try:\n ips = resolver(hostname)\n if not isinstance(ips, (list, tuple)) or not all(isinstance(ip, str) for ip in ips):\n raise ValueError(\"Resolver must return list of IP strings\")\n except Exception as e:\n raise ValueError(f\"Hostname resolution failed: {e}\")\n else:\n try:\n # getaddrinfo returns tuples with address info, extract IPs\n addrinfo = socket.getaddrinfo(hostname, None)\n ips = list({info[4][0] for info in addrinfo})\n except Exception as e:\n raise ValueError(f\"Hostname resolution failed: {e}\")\n\n # Validate resolved IPs: block private, loopback, link-local, multicast, unspecified\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\n if ip.is_loopback or ip.is_private or ip.is_link_local or ip.is_multicast or ip.is_unspecified:\n raise ValueError(f\"Blocked IP address resolved: {ip_str}\")\n\n # If transport override provided, use it (assumed safe)\n if transport is not None:\n return transport(url)\n\n # Otherwise, fetch using urllib with timeout\n with urllib.request.urlopen(url, timeout=5) as resp:\n return resp.read().decode(\"utf-8\")\n```"}]}
{"task_id": "pg-train-idor_auth-0140", "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 `payroll_portal` 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 \"\"\"\n Read or update a record in store. Caller must have session['user_id'] matching record['owner_id']\n (or session.get('role') == 'admin'); payload must not alter protected fields (id, owner_id, role, is_admin).\n\n Raises:\n KeyError: If resource_id not in store.\n PermissionError: If user is not authorized to access or modify the record.\n ValueError: If payload attempts to modify protected fields.\n \"\"\"\n if resource_id not in store:\n raise KeyError(f\"Resource ID {resource_id} not found\")\n\n record = store[resource_id]\n\n user_id = session.get('user_id')\n user_role = session.get('role')\n\n # Authorization: only owner or admin can access/update\n if user_id != record.get('owner_id') and user_role != 'admin':\n raise PermissionError(\"User not authorized to access this record\")\n\n if payload is None:\n # Read-only access allowed if authorized\n return dict(record)\n\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 ValueError(f\"Modification of protected fields {protected_fields} is not allowed\")\n\n # Update record with payload\n record.update(payload)\n\n return dict(record)\n```"}]}
{"task_id": "pg-train-unsafe_deser_eval-0141", "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 `payroll_portal` 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_payroll_portal_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_literal(raw: str) -> Any:\n \"\"\"\n Safely evaluate a string containing a Python literal structure.\n Only supports literals compatible with ast.literal_eval semantics.\n \"\"\"\n import ast\n\n try:\n # ast.literal_eval safely evaluates strings containing Python literals\n return ast.literal_eval(raw)\n except (ValueError, SyntaxError) as e:\n raise ValueError(f\"Payload is not a valid literal structure: {e}\") from e\n\n\ndef parse_payroll_portal_payload(raw_payload: str) -> Dict[str, Any]:\n \"\"\"\n Decode an incoming serialized message dictionary.\n\n Supports two formats:\n - 'pickle:' prefix followed by hex-encoded pickle bytes (only if explicitly trusted)\n - JSON string otherwise\n\n Raises ValueError if the payload cannot be safely decoded to a dict.\n \"\"\"\n if raw_payload.startswith(\"pickle:\"):\n # Reject pickle deserialization to eliminate unsafe deserialization vulnerability.\n # If pickle support is absolutely required, implement strict allowlisting or signature verification here.\n raise ValueError(\"Pickle deserialization is disabled for security reasons\")\n else:\n # Prefer JSON decoding over eval for safety\n try:\n data = json.loads(raw_payload)\n except json.JSONDecodeError:\n # Fallback: try safe literal evaluation for legacy support\n data = _safe_eval_literal(raw_payload)\n\n if not isinstance(data, dict):\n raise ValueError(\"Payload must decode to a dict\")\n return data\n```"}]}
{"task_id": "pg-train-xss-0142", "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 `warehouse_ledger` 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_timesheets_badge(title: str, summary: str, link_url: str) -> str:\n \"\"\"Render an HTML card badge with title, summary, and external link.\"\"\"\n return f'<div class=\"badge\" title=\"{title}\"><a href=\"{link_url}\">{summary}</a></div>'\n```\n"}, {"role": "assistant", "content": "```python\nimport html\nfrom urllib.parse import urlparse\n\n# Allow only safe URL schemes for href attributes\n_ALLOWED_HREF_SCHEMES = frozenset({'http', 'https', 'mailto', 'tel'})\n\ndef render_timesheets_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 # Parse and validate URL scheme to prevent unsafe href schemes (e.g., javascript:)\n parsed_url = urlparse(link_url)\n if parsed_url.scheme.lower() not in _ALLOWED_HREF_SCHEMES:\n # If scheme is missing or unsafe, render without href attribute (non-clickable)\n return f'<div class=\"badge\" title=\"{safe_title}\">{safe_summary}</div>'\n\n # Escape the URL to prevent injection in href attribute\n # We escape quotes and &, <, > to be safe in attribute context\n safe_link_url = html.escape(link_url, quote=True)\n\n return f'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_link_url}\">{safe_summary}</a></div>'\n```"}]}
{"task_id": "pg-train-sqli-0144", "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 `clinic_intake` 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 fetch_shipments(db_path: str, query: str, sort_by: str = \"priority_rank\", limit: int = 10) -> list[dict]:\n \"\"\"Search shipments matching query on project_code and return sorted rows.\"\"\"\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, project_code, category_tag, priority_rank \"\n f\"FROM shipments \"\n f\"WHERE project_code 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 fetch_shipments(db_path: str, query: str, sort_by: str = \"priority_rank\", limit: int = 10) -> list[dict]:\n \"\"\"Search shipments matching query on project_code and return sorted rows.\"\"\"\n allowed_sort_columns = {\"id\", \"project_code\", \"category_tag\", \"priority_rank\"}\n if sort_by not in allowed_sort_columns:\n raise ValueError(f\"Invalid sort_by value: {sort_by!r}\")\n\n if not isinstance(limit, int) or limit <= 0:\n raise ValueError(f\"Limit must be a positive integer, got {limit!r}\")\n\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n \"SELECT id, project_code, category_tag, priority_rank \"\n \"FROM shipments \"\n \"WHERE project_code LIKE ? \"\n f\"ORDER BY {sort_by} DESC \"\n \"LIMIT ?\"\n )\n # Use parameterized query for query and limit\n param_query = f\"%{query}%\"\n rows = conn.execute(sql, (param_query, limit)).fetchall()\n return [dict(r) for r in rows]\n finally:\n conn.close()\n```"}]}
{"task_id": "pg-train-path_traversal-0145", "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 `payroll_portal` 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 canonicalization.\"\"\"\n base_dir = os.path.abspath(base_dir)\n target_path = os.path.abspath(target_path)\n # Ensure the target path starts with the base directory path plus separator or equals base_dir\n return target_path == base_dir or target_path.startswith(base_dir + os.sep)\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, preventing path traversal.\n\n Raises:\n ValueError: If the resolved path is outside base_dir.\n FileNotFoundError, OSError: Propagated from open().\n \"\"\"\n target = os.path.abspath(os.path.join(base_dir, rel_path))\n if not _is_within_directory(base_dir, target):\n raise ValueError(\"Attempted Path Traversal outside base_dir\")\n with open(target, \"r\", encoding=\"utf-8\") as fh:\n return fh.read()\n```"}]}
{"task_id": "pg-train-cmd_injection-0146", "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 `warehouse_ledger` 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_warehouse_ledger_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\nALLOWED_MODES = frozenset({\"summary\", \"verify\"})\n\ndef run_warehouse_ledger_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: {sorted(ALLOWED_MODES)}\")\n # Use argument vector to avoid shell injection and argument splitting issues\n cmd = [sys.executable, script_path, \"--mode\", mode, target_name]\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-0147", "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 `payroll_portal` 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 ipaddress\nimport socket\nimport urllib.parse\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\n # Parse URL and validate scheme\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(\"Invalid URL: missing hostname\")\n\n # Block localhost and private IPs by checking hostname and resolved IPs\n # First, block explicit localhost names\n localhost_names = {\"localhost\", \"localhost.localdomain\", \"ip6-localhost\"}\n if hostname.lower() in localhost_names:\n raise ValueError(\"Localhost access is blocked\")\n\n # Resolve hostname to IP addresses using provided resolver or socket.getaddrinfo\n ips = []\n if resolver is not None:\n # resolver returns list[str] of IP addresses\n try:\n ips = resolver(hostname)\n except Exception as e:\n raise ValueError(f\"Hostname resolution failed: {e}\")\n else:\n try:\n # socket.getaddrinfo returns list of tuples, extract IPs\n addrinfos = socket.getaddrinfo(hostname, None)\n ips = [ai[4][0] for ai in addrinfos]\n except socket.gaierror as e:\n raise ValueError(f\"Hostname resolution failed: {e}\")\n\n if not ips:\n raise ValueError(\"Hostname resolution returned no IPs\")\n\n # Check that none of the resolved IPs are loopback, private, link-local, or unspecified\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\n if ip.is_loopback:\n raise ValueError(\"Resolved IP is loopback, access blocked\")\n if ip.is_private:\n raise ValueError(\"Resolved IP is private, access blocked\")\n if ip.is_link_local:\n raise ValueError(\"Resolved IP is link-local, access blocked\")\n if ip.is_unspecified:\n raise ValueError(\"Resolved IP is unspecified, access blocked\")\n\n # After all validations, perform the fetch\n if transport is not None:\n return transport(url)\n\n with urllib.request.urlopen(url, timeout=5) as resp:\n return resp.read().decode(\"utf-8\")\n```"}]}
{"task_id": "pg-train-idor_auth-0148", "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 `payroll_portal` 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_vehicles_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_vehicles_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 not found\")\n\n record = store[resource_id]\n\n user_id = session.get('user_id')\n user_role = session.get('role')\n\n if user_id is None:\n raise PermissionError(\"Unauthenticated session\")\n\n # Enforce ownership or admin role\n if user_role != 'admin' and record.get('owner_id') != user_id:\n raise PermissionError(\"Access denied: user does not own 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(f\"Modification of protected fields {protected_fields} is not allowed\")\n\n # Update only allowed fields\n record.update(payload)\n\n return dict(record)\n```"}]}
{"task_id": "pg-train-unsafe_deser_eval-0149", "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 `warehouse_ledger` 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_warehouse_ledger_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_literal(raw: str) -> Any:\n \"\"\"Safely parse a Python literal from a string using ast.literal_eval.\"\"\"\n import ast\n\n try:\n return ast.literal_eval(raw)\n except (ValueError, SyntaxError) as e:\n raise ValueError(f\"Invalid literal for safe evaluation: {e}\") from e\n\n\ndef parse_warehouse_ledger_payload(raw_payload: str) -> Dict:\n \"\"\"\n Decode an incoming serialized message dictionary.\n\n Supports JSON or hex-encoded pickle payloads with strict type checks.\n \"\"\"\n if raw_payload.startswith(\"pickle:\"):\n # Restrict pickle loading to a safe subset using a custom Unpickler\n import io\n import pickle\n\n class SafeUnpickler(pickle.Unpickler):\n # Allow only built-in safe types\n def find_class(self, module: str, name: str):\n # Only allow safe built-in types\n safe_builtins = {\n \"builtins\": {\n \"dict\",\n \"list\",\n \"set\",\n \"frozenset\",\n \"tuple\",\n \"str\",\n \"int\",\n \"float\",\n \"bool\",\n \"NoneType\",\n }\n }\n if module in safe_builtins and name in safe_builtins[module]:\n return super().find_class(module, name)\n raise ValueError(f\"Unsafe pickle class {module}.{name} blocked\")\n\n try:\n raw_bytes = bytes.fromhex(raw_payload[7:])\n data = SafeUnpickler(io.BytesIO(raw_bytes)).load()\n except Exception as e:\n raise ValueError(f\"Invalid pickle payload: {e}\") from e\n else:\n # Parse as JSON first for safer deserialization\n try:\n data = json.loads(raw_payload)\n except json.JSONDecodeError:\n # Fallback to safe literal eval for non-JSON literals (e.g. Python dict syntax)\n data = _safe_eval_literal(raw_payload)\n\n if not isinstance(data, dict):\n raise ValueError(\"Payload must decode to a dict\")\n return data\n```"}]}
{"task_id": "pg-train-xss-0150", "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 `fleet_dispatch` 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_shipments_badge(title: str, summary: str, link_url: str) -> str:\n \"\"\"Render an HTML card badge with title, summary, and external link.\"\"\"\n return f'<div class=\"badge\" title=\"{title}\"><a href=\"{link_url}\">{summary}</a></div>'\n```\n"}, {"role": "assistant", "content": "```python\nimport html\nfrom urllib.parse import urlparse\n\n# Allowed URL schemes for href to prevent unsafe href schemes (e.g. javascript:)\nALLOWED_HREF_SCHEMES = frozenset({\"http\", \"https\", \"mailto\", \"tel\", \"\"}) # \"\" allows relative URLs\n\ndef _is_safe_href(url: str) -> bool:\n \"\"\"\n Check if the href URL has a safe scheme.\n Allows relative URLs and http(s), mailto, tel schemes.\n \"\"\"\n parsed = urlparse(url)\n # urlparse returns scheme in lowercase\n return parsed.scheme in ALLOWED_HREF_SCHEMES\n\ndef render_shipments_badge(title: str, summary: str, link_url: str) -> str:\n \"\"\"Render an HTML card badge with title, summary, and external link.\"\"\"\n safe_title = html.escape(title, quote=True)\n safe_summary = html.escape(summary)\n if _is_safe_href(link_url):\n safe_link_url = html.escape(link_url, quote=True)\n else:\n # Unsafe scheme: render link_url as empty string to avoid XSS\n safe_link_url = \"\"\n return f'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_link_url}\">{safe_summary}</a></div>'\n```"}]}
{"task_id": "pg-train-crypto_secrets-0151", "category": "crypto_secrets", "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 Weak Cryptography, Predictable RNG & Secret Exposure in Logs (CWE-327) 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 hashlib\nimport random\nimport string\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage.\"\"\"\n return hashlib.md5(password.encode(\"utf-8\")).hexdigest()\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n return hash_password(password) == stored_hash\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n alphabet = string.ascii_letters + string.digits\n return \"\".join(random.choices(alphabet, k=32))\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for fleet_dispatch.\"\"\"\n return f\"service=fleet_dispatch user={user_id} action={action} api_key={api_key}\"\n```\n"}, {"role": "assistant", "content": "```python\nimport hashlib\nimport secrets\nimport hmac\n\n\ndef hash_password(password: str) -> str:\n \"\"\"Hash a user password for storage using PBKDF2-HMAC-SHA256 with a random salt.\"\"\"\n salt = secrets.token_bytes(16)\n # Use 100,000 iterations as recommended by OWASP for PBKDF2\n dk = hashlib.pbkdf2_hmac(\"sha256\", password.encode(\"utf-8\"), salt, 100_000)\n # Store salt and hash together, hex-encoded, separated by $\n return f\"{salt.hex()}${dk.hex()}\"\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n \"\"\"Verify a plaintext password against its stored hash.\"\"\"\n try:\n salt_hex, hash_hex = stored_hash.split(\"$\", 1)\n salt = bytes.fromhex(salt_hex)\n expected_hash = bytes.fromhex(hash_hex)\n test_hash = hashlib.pbkdf2_hmac(\"sha256\", password.encode(\"utf-8\"), salt, 100_000)\n # Use hmac.compare_digest to prevent timing attacks\n return hmac.compare_digest(test_hash, expected_hash)\n except (ValueError, TypeError):\n # Malformed stored_hash or decoding error\n return False\n\n\ndef issue_token() -> str:\n \"\"\"Issue a cryptographically secure authentication token (at least 32 characters).\"\"\"\n # secrets.token_urlsafe returns a string with ~1.3 chars per byte, so 24 bytes ~ 32 chars\n return secrets.token_urlsafe(24)\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n \"\"\"Format an audit log entry for fleet_dispatch with redacted api_key.\"\"\"\n redacted_key = (\n api_key[:4] + \"...\" + api_key[-4:] if len(api_key) > 8 else \"REDACTED\"\n )\n return f\"service=fleet_dispatch user={user_id} action={action} api_key={redacted_key}\"\n```"}]}
{"task_id": "pg-train-sqli-0152", "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 `warehouse_ledger` 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 lookup_vehicles(db_path: str, query: str, sort_by: str = \"unit_count\", limit: int = 10) -> list[dict]:\n \"\"\"Search vehicles matching query on manifest_note and return sorted rows.\"\"\"\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, manifest_note, category_tag, unit_count \"\n f\"FROM vehicles \"\n f\"WHERE manifest_note 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 lookup_vehicles(db_path: str, query: str, sort_by: str = \"unit_count\", limit: int = 10) -> list[dict]:\n \"\"\"Search vehicles matching query on manifest_note and return sorted rows.\"\"\"\n allowed_sort_columns = {\"id\", \"manifest_note\", \"category_tag\", \"unit_count\"}\n\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 conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, manifest_note, category_tag, unit_count \"\n f\"FROM vehicles \"\n f\"WHERE manifest_note LIKE ? \"\n f\"ORDER BY {sort_by} DESC \"\n f\"LIMIT ?\"\n )\n # Use parameterized queries for user inputs\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-0153", "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 lookup_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 \"\"\"\n Check if the target_path is located within the base_dir after resolving symlinks and relative parts.\n \"\"\"\n base_dir = os.path.abspath(os.path.realpath(base_dir))\n target_path = os.path.abspath(os.path.realpath(target_path))\n return os.path.commonpath([base_dir]) == os.path.commonpath([base_dir, target_path])\n\n\ndef lookup_artifact_text(base_dir: str, rel_path: str) -> str:\n \"\"\"\n Read a UTF-8 text file located under base_dir, preventing path traversal attacks by\n ensuring the resolved file path is within base_dir.\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 base_dir\")\n with open(target, \"r\", encoding=\"utf-8\") as fh:\n return fh.read()\n```"}]}
{"task_id": "pg-train-cmd_injection-0154", "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 `fleet_dispatch` 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_fleet_dispatch_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\nfrom pathlib import Path\n\n# Allowed modes for the fleet dispatch tool\nALLOWED_MODES = frozenset({\"summary\", \"verify\"})\n\ndef run_fleet_dispatch_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 # Validate mode against allowlist\n if mode not in ALLOWED_MODES:\n raise ValueError(f\"Invalid mode: {mode!r}. Allowed modes are: {ALLOWED_MODES}\")\n\n # Resolve script_path to an absolute path and ensure it is a file\n script_path_obj = Path(script_path).resolve(strict=True)\n if not script_path_obj.is_file():\n raise FileNotFoundError(f\"Script path not found or is not a file: {script_path_obj}\")\n\n # Construct argument vector without shell=True to avoid command injection\n cmd = [\n sys.executable,\n str(script_path_obj),\n \"--mode\",\n mode,\n target_name,\n ]\n\n proc = subprocess.run(cmd, capture_output=True, text=True, check=True)\n return proc.stdout.strip()\n```"}]}
{"task_id": "pg-train-ssrf-0155", "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 query_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 ipaddress\nimport socket\nfrom urllib.parse import urlparse\nimport urllib.request\n\n\ndef query_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 # Validate scheme cheaply\n parsed = urlparse(url)\n if parsed.scheme not in (\"http\", \"https\"):\n raise ValueError(\"Unsupported URL scheme\")\n\n hostname = parsed.hostname\n if not hostname:\n raise ValueError(\"Invalid URL: missing hostname\")\n\n # Block localhost and loopback names explicitly\n # Also block IP literals in loopback, private, link-local ranges\n # Use resolver if provided, else socket.getaddrinfo\n\n # Resolve hostname to IPs\n try:\n if resolver is not None:\n # Use custom resolver, expect list[str] of IPs\n resolved_ips = resolver(hostname)\n if not resolved_ips:\n raise ValueError(\"Hostname resolution returned no IPs\")\n else:\n # Use system resolver, get all IP addresses (IPv4 and IPv6)\n infos = socket.getaddrinfo(hostname, None)\n resolved_ips = list({info[4][0] for info in infos})\n except Exception as e:\n raise ValueError(f\"Hostname resolution failed: {e}\")\n\n # Validate each resolved IP is public and not loopback/private/link-local\n for ip_str in resolved_ips:\n try:\n ip = ipaddress.ip_address(ip_str)\n except ValueError:\n raise ValueError(f\"Invalid IP address resolved: {ip_str}\")\n\n if ip.is_loopback or ip.is_private or ip.is_link_local or ip.is_reserved or ip.is_multicast:\n raise ValueError(f\"Disallowed IP address resolved: {ip_str}\")\n\n # Passed all checks, perform fetch\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```"}]}
{"task_id": "pg-train-idor_auth-0156", "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 `clinic_intake` 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_vehicles_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_vehicles_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 user_role = session.get('role')\n\n if user_id is None:\n raise PermissionError(\"Authentication required\")\n\n if user_id != record.get('owner_id') and user_role != 'admin':\n raise PermissionError(\"Access denied: user does not own this resource\")\n\n if payload:\n # Disallow changes to 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 only allowed fields\n record.update(payload)\n\n return dict(record)\n```"}]}
{"task_id": "pg-train-unsafe_deser_eval-0157", "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 `fleet_dispatch` 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_fleet_dispatch_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\nimport pickle\nfrom typing import Any, Dict\n\n\ndef _safe_pickle_loads(data_bytes: bytes) -> Any:\n \"\"\"\n Safely load pickle data by restricting to built-in safe types only.\n Raises ValueError if disallowed types are encountered.\n \"\"\"\n import io\n import pickletools\n\n # Define a whitelist of allowed pickle opcodes for safe deserialization\n # This is a minimal approach; for production consider using a dedicated safe unpickler\n allowed_opcodes = {\n b'(', # MARK\n b'.', # STOP\n b'I', # INT\n b'J', # BININT\n b'K', # BININT1\n b'L', # LONG\n b'M', # BININT2\n b'F', # FLOAT\n b'G', # BINFLOAT\n b'S', # STRING\n b'T', # BINSTRING\n b'U', # SHORT_BINSTRING\n b'V', # UNICODE\n b'X', # BINUNICODE\n b']', # EMPTY_LIST\n b'a', # APPEND\n b'e', # APPENDS\n b'}', # EMPTY_DICT\n b'q', # BINPUT\n b'r', # LONG_BINPUT\n b'u', # SETITEM\n b't', # TUPLE\n b'c', # GLOBAL (used for builtins like 'builtins.dict')\n b'(', # MARK\n b'o', # OBJ\n b'R', # REDUCE\n b'b', # BUILD\n b'\\x85', # TUPLE1\n b'\\x86', # TUPLE2\n b'\\x87', # TUPLE3\n b'\\x88', # NEWTRUE\n b'\\x89', # NEWFALSE\n b'\\x94', # MEMOIZE\n }\n\n # Scan pickle bytecode for disallowed opcodes\n # This is a heuristic and not bulletproof; for full safety, use json or other safe formats.\n for opcode, _ in pickletools.genops(data_bytes):\n if opcode.name.encode() not in allowed_opcodes:\n raise ValueError(f\"Disallowed pickle opcode: {opcode.name}\")\n\n # Use restricted unpickler to only allow safe builtins\n class RestrictedUnpickler(pickle.Unpickler):\n def find_class(self, module: str, name: str) -> Any:\n # Only allow safe builtins\n if module == \"builtins\" and name in {\n \"dict\", \"list\", \"set\", \"frozenset\", \"tuple\",\n \"str\", \"int\", \"float\", \"bool\", \"complex\", \"bytes\",\n \"bytearray\", \"NoneType\"\n }:\n return getattr(__import__(module), name)\n raise ValueError(f\"Global '{module}.{name}' is not allowed\")\n\n file_like = io.BytesIO(data_bytes)\n return RestrictedUnpickler(file_like).load()\n\n\ndef parse_fleet_dispatch_payload(raw_payload: str) -> Dict[str, Any]:\n \"\"\"\n Decode an incoming serialized message dictionary safely.\n Supports JSON and restricted pickle formats only.\n Raises ValueError on invalid or unsafe payloads.\n \"\"\"\n if raw_payload.startswith(\"pickle:\"):\n hex_data = raw_payload[7:]\n try:\n data_bytes = bytes.fromhex(hex_data)\n except ValueError as e:\n raise ValueError(\"Invalid hex encoding in pickle payload\") from e\n data = _safe_pickle_loads(data_bytes)\n else:\n # Safely parse JSON instead of eval\n try:\n data = json.loads(raw_payload)\n except json.JSONDecodeError as e:\n raise ValueError(\"Payload must be valid JSON\") from e\n\n if not isinstance(data, dict):\n raise ValueError(\"Payload must decode to a dict\")\n return data\n```"}]}
{"task_id": "pg-train-xss-0158", "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'<div class=\"badge\" title=\"{title}\"><a href=\"{link_url}\">{summary}</a></div>'\n```\n"}, {"role": "assistant", "content": "```python\nimport html\nfrom urllib.parse import urlparse\n\n# Allowed URL schemes for href attribute to prevent unsafe href schemes (e.g., javascript:)\nALLOWED_HREF_SCHEMES = frozenset({\"http\", \"https\", \"mailto\", \"tel\", \"ftp\", \"ftps\"})\n\ndef _is_safe_href(href: str) -> bool:\n \"\"\"Check if the href URL has a safe scheme.\"\"\"\n parsed = urlparse(href)\n # Allow relative URLs (no scheme, no netloc) or URLs with allowed schemes\n if parsed.scheme == \"\" and parsed.netloc == \"\":\n return True\n return parsed.scheme.lower() in ALLOWED_HREF_SCHEMES\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 for HTML attribute and text content respectively\n escaped_title = html.escape(title, quote=True)\n escaped_summary = html.escape(summary)\n # Validate and escape link_url\n if _is_safe_href(link_url):\n escaped_link_url = html.escape(link_url, quote=True)\n else:\n # If not safe, render link as plain text without href to avoid XSS\n escaped_link_url = \"\"\n if escaped_link_url:\n return f'<div class=\"badge\" title=\"{escaped_title}\"><a href=\"{escaped_link_url}\">{escaped_summary}</a></div>'\n else:\n # Render without link if href is unsafe\n return f'<div class=\"badge\" title=\"{escaped_title}\">{escaped_summary}</div>'\n```"}]}
{"task_id": "pg-general-0000", "category": "gen_code", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "Write a Python function `merge_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]` that merges overlapping closed intervals."}, {"role": "assistant", "content": "```python\ndef merge_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:\n if not intervals:\n return []\n ordered = sorted(intervals, key=lambda x: (x[0], x[1]))\n merged = [ordered[0]]\n for start, end in ordered[1:]:\n prev_start, prev_end = merged[-1]\n if start <= prev_end:\n merged[-1] = (prev_start, max(prev_end, end))\n else:\n merged.append((start, end))\n return merged\n```"}]}
{"task_id": "pg-general-0001", "category": "gen_code", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "Write a Python function `lru_top_k(counts: dict[str, int], k: int) -> list[str]` returning the top k keys sorted by descending count, breaking ties alphabetically."}, {"role": "assistant", "content": "```python\ndef lru_top_k(counts: dict[str, int], k: int) -> list[str]:\n if k <= 0:\n return []\n return [key for key, _ in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:k]]\n```"}]}
{"task_id": "pg-general-0002", "category": "gen_code", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "Write a Python function `chunk_list(items: list, size: int) -> list[list]` that splits items into chunks of length `size`, raising ValueError if size <= 0."}, {"role": "assistant", "content": "```python\ndef chunk_list(items: list, size: int) -> list[list]:\n if size <= 0:\n raise ValueError('size must be positive')\n return [items[i : i + size] for i in range(0, len(items), size)]\n```"}]}
{"task_id": "pg-general-0003", "category": "gen_code", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "Write a Python function `is_balanced(s: str) -> bool` checking whether (), [], and {} brackets are properly nested."}, {"role": "assistant", "content": "```python\ndef is_balanced(s: str) -> bool:\n pairs = {')': '(', ']': '[', '}': '{'}\n stack: list[str] = []\n for ch in s:\n if ch in '([{':\n stack.append(ch)\n elif ch in pairs:\n if not stack or stack.pop() != pairs[ch]:\n return False\n return not stack\n```"}]}
{"task_id": "pg-general-0004", "category": "gen_code", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "Write a Python function `flatten_dict(d: dict, prefix: str = '') -> dict` flattening nested dicts with dot-separated keys."}, {"role": "assistant", "content": "```python\ndef flatten_dict(d: dict, prefix: str = '') -> dict:\n out = {}\n for k, v in d.items():\n full = f'{prefix}.{k}' if prefix else str(k)\n if isinstance(v, dict) and v:\n out.update(flatten_dict(v, full))\n else:\n out[full] = v\n return out\n```"}]}
{"task_id": "pg-general-0005", "category": "gen_code", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "Write a Python function `binary_search(nums: list[int], target: int) -> int` returning the index of target or -1 if absent."}, {"role": "assistant", "content": "```python\ndef binary_search(nums: list[int], target: int) -> int:\n lo, hi = 0, len(nums) - 1\n while lo <= hi:\n mid = (lo + hi) // 2\n if nums[mid] == target:\n return mid\n if nums[mid] < target:\n lo = mid + 1\n else:\n hi = mid - 1\n return -1\n```"}]}
{"task_id": "pg-general-0006", "category": "gen_code", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "Write a Python function `group_anagrams(words: list[str]) -> list[list[str]]` grouping anagrams together."}, {"role": "assistant", "content": "```python\nfrom collections import defaultdict\n\ndef group_anagrams(words: list[str]) -> list[list[str]]:\n buckets: dict[tuple[str, ...], list[str]] = defaultdict(list)\n for w in words:\n buckets[tuple(sorted(w))].append(w)\n return list(buckets.values())\n```"}]}
{"task_id": "pg-general-0007", "category": "gen_code", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "Write a Python function `running_mean(values: list[float]) -> list[float]` returning the cumulative arithmetic mean at each index."}, {"role": "assistant", "content": "```python\ndef running_mean(values: list[float]) -> list[float]:\n total = 0.0\n out: list[float] = []\n for idx, val in enumerate(values, start=1):\n total += val\n out.append(total / idx)\n return out\n```"}]}
{"task_id": "pg-general-0008", "category": "gen_math", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "A train travels 180 km at 60 km/h and returns 180 km at 90 km/h. What is its average speed for the whole round trip? Give the exact number and brief steps."}, {"role": "assistant", "content": "Total distance is 180 + 180 = 360 km. Outbound time is 180 / 60 = 3 hours, return time is 180 / 90 = 2 hours, so total time is 5 hours. Average speed = 360 / 5 = 72 km/h."}]}
{"task_id": "pg-general-0009", "category": "gen_math", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "If 3x - 7 = 2x + 11, what is x? Show one step."}, {"role": "assistant", "content": "Subtract 2x and add 7 to both sides: x = 18."}]}
{"task_id": "pg-general-0010", "category": "gen_math", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "What is the sum of the interior angles of a regular octagon in degrees?"}, {"role": "assistant", "content": "An n-gon has interior angle sum (n - 2) * 180 degrees. For n = 8: (8 - 2) * 180 = 1080 degrees."}]}
{"task_id": "pg-general-0011", "category": "gen_math", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "A fair six-sided die is rolled twice. What is the probability that the sum is 7? Express as a reduced fraction."}, {"role": "assistant", "content": "There are 6 * 6 = 36 equally likely outcomes. Six pairs sum to 7: (1,6), (2,5), (3,4), (4,3), (5,2), (6,1). Thus the probability is 6/36 = 1/6."}]}
{"task_id": "pg-general-0012", "category": "gen_math", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "How many subsets does a set with 5 distinct elements have, including the empty set and the set itself?"}, {"role": "assistant", "content": "A 5-element set has 2^5 = 32 subsets."}]}
{"task_id": "pg-general-0013", "category": "gen_math", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "Solve for the positive value of y: y^2 - 5y - 24 = 0."}, {"role": "assistant", "content": "Factoring gives (y - 8)(y + 3) = 0, so the positive solution is y = 8."}]}
{"task_id": "pg-general-0014", "category": "gen_math", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "A store applies a 20% discount to a $150 jacket, then adds 10% sales tax to the discounted price. What is the final price?"}, {"role": "assistant", "content": "Discounted price: 150 * 0.80 = $120. After 10% tax: 120 * 1.10 = $132."}]}
{"task_id": "pg-general-0015", "category": "gen_math", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "What is the greatest common divisor (GCD) of 84 and 126?"}, {"role": "assistant", "content": "Prime factorizations: 84 = 2^2 * 3 * 7 and 126 = 2 * 3^2 * 7. The GCD is 2 * 3 * 7 = 42."}]}
{"task_id": "pg-general-0016", "category": "gen_if", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "List exactly three primary additive colors of light, comma-separated on a single line, with no extra words."}, {"role": "assistant", "content": "Red, Green, Blue"}]}
{"task_id": "pg-general-0017", "category": "gen_if", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "Respond with valid JSON only, containing keys `status` set to `'ok'` and `retries` set to 3."}, {"role": "assistant", "content": "{\"status\": \"ok\", \"retries\": 3}"}]}
{"task_id": "pg-general-0018", "category": "gen_if", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "Summarize what HTTPS provides over HTTP in exactly two sentences."}, {"role": "assistant", "content": "HTTPS encrypts data in transit using TLS so third parties cannot read or tamper with network traffic. It also authenticates the server's identity through cryptographic certificates."}]}
{"task_id": "pg-general-0019", "category": "gen_if", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "Convert the ISO date 2026-12-02 into a JSON object with integer keys `year`, `month`, and `day`."}, {"role": "assistant", "content": "{\"year\": 2026, \"month\": 12, \"day\": 2}"}]}
{"task_id": "pg-general-0020", "category": "gen_if", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "Give three bullet points explaining why unit tests help catch regressions. Keep each bullet under 12 words."}, {"role": "assistant", "content": "- Unit tests verify expected outputs immediately after every code change.\n- Automated test suites catch edge-case breakages before deployment.\n- Small isolated tests pinpoint exactly which function introduced a bug."}]}
{"task_id": "pg-general-0021", "category": "gen_if", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "Reply with ONLY the uppercase word YES if 17 is a prime number, or NO otherwise."}, {"role": "assistant", "content": "YES"}]}
{"task_id": "pg-general-0022", "category": "gen_if", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "Write a 1-line bash command that counts lines in `app.log` using `wc`."}, {"role": "assistant", "content": "wc -l app.log"}]}
{"task_id": "pg-general-0023", "category": "gen_if", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "Return a YAML list of three HTTP status codes: 200, 404, and 500."}, {"role": "assistant", "content": "- 200\n- 404\n- 500"}]}
{"task_id": "pg-general-0024", "category": "gen_tool", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "You have a tool `search_docs(query: str, limit: int)`. Emit a JSON object with `tool` and `arguments` to search for 'sqlite3 bind parameters' with limit 5."}, {"role": "assistant", "content": "{\"tool\": \"search_docs\", \"arguments\": {\"query\": \"sqlite3 bind parameters\", \"limit\": 5}}"}]}
{"task_id": "pg-general-0025", "category": "gen_tool", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "You have a tool `read_file(path: str, start_line: int, end_line: int)`. Emit JSON to read lines 10 to 40 of `src/server.py`."}, {"role": "assistant", "content": "{\"tool\": \"read_file\", \"arguments\": {\"path\": \"src/server.py\", \"start_line\": 10, \"end_line\": 40}}"}]}
{"task_id": "pg-general-0026", "category": "gen_tool", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "You have a tool `run_tests(suite: str, fail_fast: bool)`. Emit JSON to run the `security` suite with fail_fast enabled."}, {"role": "assistant", "content": "{\"tool\": \"run_tests\", \"arguments\": {\"suite\": \"security\", \"fail_fast\": true}}"}]}
{"task_id": "pg-general-0027", "category": "gen_tool", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "You have a tool `create_ticket(title: str, severity: str, tags: list[str])`. Emit JSON for a high-severity SSRF bug tagged `security` and `network`."}, {"role": "assistant", "content": "{\"tool\": \"create_ticket\", \"arguments\": {\"title\": \"Fix SSRF validation in webhook fetcher\", \"severity\": \"high\", \"tags\": [\"security\", \"network\"]}}"}]}
{"task_id": "pg-general-0028", "category": "gen_tool", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "You have a tool `query_metrics(service: str, window_minutes: int)`. Emit JSON to inspect `auth-api` over the last 60 minutes."}, {"role": "assistant", "content": "{\"tool\": \"query_metrics\", \"arguments\": {\"service\": \"auth-api\", \"window_minutes\": 60}}"}]}
{"task_id": "pg-general-0029", "category": "gen_tool", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "You have a tool `check_dns(hostname: str, record_type: str)`. Emit JSON to look up A records for `example.com`."}, {"role": "assistant", "content": "{\"tool\": \"check_dns\", \"arguments\": {\"hostname\": \"example.com\", \"record_type\": \"A\"}}"}]}
{"task_id": "pg-general-0030", "category": "gen_tool", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "You have a tool `lint_file(path: str, fix: bool)`. Emit JSON to lint `app/routes.py` without modifying it."}, {"role": "assistant", "content": "{\"tool\": \"lint_file\", \"arguments\": {\"path\": \"app/routes.py\", \"fix\": false}}"}]}
{"task_id": "pg-general-0031", "category": "gen_tool", "source": "curated_general_preservation", "messages": [{"role": "system", "content": "You are a helpful, accurate assistant. Follow all formatting and constraints strictly."}, {"role": "user", "content": "You have a tool `rotate_secret(name: str, dry_run: bool)`. Emit JSON to dry-run rotating `WEBHOOK_SIGNING_KEY`."}, {"role": "assistant", "content": "{\"tool\": \"rotate_secret\", \"arguments\": {\"name\": \"WEBHOOK_SIGNING_KEY\", \"dry_run\": true}}"}]}
|