{"task_id": "pg-test-sqli-0000", "category": "sqli", "split": "test", "seed": 8284135986210960674, "domain": "harbor_berths", "system_prompt": "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.", "user_prompt": "Service module `harbor_berths` 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 read_harvests(db_path: str, query: str, sort_by: str = \"logged_at\", limit: int = 10) -> list[dict]:\n \"\"\"Search harvests matching query on berth_title and return sorted rows.\"\"\"\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, berth_title, category_tag, logged_at \"\n f\"FROM harvests \"\n f\"WHERE berth_title 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", "vulnerable_code": "import sqlite3\n\n\ndef read_harvests(db_path: str, query: str, sort_by: str = \"logged_at\", limit: int = 10) -> list[dict]:\n \"\"\"Search harvests matching query on berth_title and return sorted rows.\"\"\"\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, berth_title, category_tag, logged_at \"\n f\"FROM harvests \"\n f\"WHERE berth_title 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", "reference_patch": "import sqlite3\n\n_ALLOWED_SORT_COLUMNS = frozenset({\"id\", \"berth_title\", \"category_tag\", \"logged_at\"})\n\n\ndef read_harvests(db_path: str, query: str, sort_by: str = \"logged_at\", limit: int = 10) -> list[dict]:\n \"\"\"Search harvests matching query on berth_title using bound parameters and column allow-list.\"\"\"\n if not isinstance(query, str):\n raise ValueError(\"query must be a string\")\n if sort_by not in _ALLOWED_SORT_COLUMNS:\n raise ValueError(f\"Unsupported sort column: {sort_by!r}\")\n limit_val = int(limit)\n if limit_val < 1 or limit_val > 500:\n raise ValueError(\"limit must be between 1 and 500\")\n\n escaped_query = query.replace(\"\\\\\", \"\\\\\\\\\").replace(\"%\", \"\\\\%\").replace(\"_\", \"\\\\_\")\n pattern = f\"%{escaped_query}%\"\n\n conn = sqlite3.connect(db_path)\n conn.row_factory = sqlite3.Row\n try:\n sql = (\n f\"SELECT id, berth_title, category_tag, logged_at \"\n f\"FROM harvests \"\n f\"WHERE berth_title LIKE ? ESCAPE '\\\\' \"\n f\"ORDER BY {sort_by} DESC \"\n f\"LIMIT ?\"\n )\n rows = conn.execute(sql, (pattern, limit_val)).fetchall()\n return [dict(r) for r in rows]\n finally:\n conn.close()\n", "functional_tests": "import json\nimport sys\n\ndef _run_checks(checks):\n passed = 0\n failures = []\n for name, fn in checks:\n try:\n fn()\n passed += 1\n except Exception as exc:\n failures.append(f\"{name}: {type(exc).__name__}: {exc}\")\n print(\"PATCHGUARD_RESULT:\" + json.dumps({\"passed\": passed, \"total\": len(checks), \"failures\": failures}))\n sys.exit(0 if passed == len(checks) else 1)\nimport os\nimport sqlite3\nimport tempfile\nimport target_module\n\ndef _make_db():\n fd, path = tempfile.mkstemp(suffix=\".db\")\n os.close(fd)\n conn = sqlite3.connect(path)\n conn.execute(\"CREATE TABLE harvests (id INTEGER PRIMARY KEY, berth_title TEXT, category_tag TEXT, logged_at INTEGER)\")\n conn.execute(\"CREATE TABLE secret_vault (id INTEGER PRIMARY KEY, secret_key TEXT)\")\n conn.execute(\"INSERT INTO secret_vault (secret_key) VALUES ('VAULT_SECRET_XYZ')\")\n conn.executemany(\n \"INSERT INTO harvests (berth_title, category_tag, logged_at) VALUES (?, ?, ?)\",\n [\n (\"pier_514_alpha\", \"deepwater\", 10),\n (\"pier_514_beta\", \"deepwater\", 25),\n (\"other_entry\", \"standard\", 5),\n ],\n )\n conn.commit()\n conn.close()\n return path\ndef test_match():\n p = _make_db()\n try:\n rows = target_module.read_harvests(p, \"pier_514\")\n assert len(rows) == 2, f\"expected 2 rows, got {rows}\"\n assert rows[0][\"logged_at\"] == 25\n finally:\n os.remove(p)\n\ndef test_sort_and_limit():\n p = _make_db()\n try:\n rows = target_module.read_harvests(p, \"\", sort_by=\"id\", limit=1)\n assert len(rows) == 1\n finally:\n os.remove(p)\n\n_run_checks([(\"match\", test_match), (\"sort_and_limit\", test_sort_and_limit)])\n", "exploit_tests": "import json\nimport sys\n\ndef _run_checks(checks):\n passed = 0\n failures = []\n for name, fn in checks:\n try:\n fn()\n passed += 1\n except Exception as exc:\n failures.append(f\"{name}: {type(exc).__name__}: {exc}\")\n print(\"PATCHGUARD_RESULT:\" + json.dumps({\"passed\": passed, \"total\": len(checks), \"failures\": failures}))\n sys.exit(0 if passed == len(checks) else 1)\nimport os\nimport sqlite3\nimport tempfile\nimport target_module\n\ndef _make_db():\n fd, path = tempfile.mkstemp(suffix=\".db\")\n os.close(fd)\n conn = sqlite3.connect(path)\n conn.execute(\"CREATE TABLE harvests (id INTEGER PRIMARY KEY, berth_title TEXT, category_tag TEXT, logged_at INTEGER)\")\n conn.execute(\"CREATE TABLE secret_vault (id INTEGER PRIMARY KEY, secret_key TEXT)\")\n conn.execute(\"INSERT INTO secret_vault (secret_key) VALUES ('VAULT_SECRET_XYZ')\")\n conn.executemany(\n \"INSERT INTO harvests (berth_title, category_tag, logged_at) VALUES (?, ?, ?)\",\n [\n (\"pier_514_alpha\", \"deepwater\", 10),\n (\"pier_514_beta\", \"deepwater\", 25),\n (\"other_entry\", \"standard\", 5),\n ],\n )\n conn.commit()\n conn.close()\n return path\ndef test_or_injection():\n p = _make_db()\n try:\n rows = target_module.read_harvests(p, \"nomatch%' OR 1=1 --\")\n assert rows == [], f\"SQLi OR bypass returned rows: {rows}\"\n finally:\n os.remove(p)\n\ndef test_union_injection():\n p = _make_db()\n try:\n try:\n rows = target_module.read_harvests(p, \"x%' UNION SELECT 1, secret_key, 'x', 99 FROM secret_vault --\")\n except Exception:\n rows = []\n joined = str(rows)\n assert \"VAULT_SECRET_XYZ\" not in joined, \"SQLi UNION leaked secret_vault\"\n finally:\n os.remove(p)\n\ndef test_order_by_injection():\n p = _make_db()\n try:\n raised = False\n try:\n target_module.read_harvests(p, \"pier_514\", sort_by=\"(CASE WHEN (1=1) THEN id ELSE logged_at END)\")\n except ValueError:\n raised = True\n assert raised, \"Arbitrary ORDER BY expression was not rejected with ValueError\"\n finally:\n os.remove(p)\n\n_run_checks([\n (\"or_injection\", test_or_injection),\n (\"union_injection\", test_union_injection),\n (\"order_by_injection\", test_order_by_injection),\n])\n", "metadata": {"cwe": "CWE-89", "fn": "read_harvests"}} {"task_id": "pg-test-path_traversal-0001", "category": "path_traversal", "split": "test", "seed": 2771952354175244110, "domain": "orchard_yields", "system_prompt": "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.", "user_prompt": "Service module `orchard_yields` 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 pull_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", "vulnerable_code": "import os\n\n\ndef pull_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", "reference_patch": "from pathlib import Path\n\n\ndef pull_artifact_text(base_dir: str, rel_path: str) -> str:\n \"\"\"Safely read a UTF-8 text file confined within base_dir.\"\"\"\n if not rel_path or Path(rel_path).is_absolute():\n raise ValueError(\"Path must be a non-empty relative path\")\n base = Path(base_dir).resolve()\n target = (base / rel_path).resolve()\n if target == base or not target.is_relative_to(base):\n raise PermissionError(f\"Path escapes base directory: {rel_path!r}\")\n return target.read_text(encoding=\"utf-8\")\n", "functional_tests": "import json\nimport sys\n\ndef _run_checks(checks):\n passed = 0\n failures = []\n for name, fn in checks:\n try:\n fn()\n passed += 1\n except Exception as exc:\n failures.append(f\"{name}: {type(exc).__name__}: {exc}\")\n print(\"PATCHGUARD_RESULT:\" + json.dumps({\"passed\": passed, \"total\": len(checks), \"failures\": failures}))\n sys.exit(0 if passed == len(checks) else 1)\nimport tempfile\nfrom pathlib import Path\nimport target_module\n\ndef _make_tree():\n root = Path(tempfile.mkdtemp())\n base = root / \"store\"\n sub = base / \"nested\"\n sibling = root / \"store_evil\"\n sub.mkdir(parents=True)\n sibling.mkdir(parents=True)\n (base / \"pier_514.txt\").write_text(\"ok_content_pier_514\", encoding=\"utf-8\")\n (sub / \"report.txt\").write_text(\"nested_ok\", encoding=\"utf-8\")\n (root / \"outside.txt\").write_text(\"SECRET_OUTSIDE\", encoding=\"utf-8\")\n (sibling / \"trap.txt\").write_text(\"SECRET_SIBLING\", encoding=\"utf-8\")\n return root, base\nimport shutil\n\ndef test_read_root_file():\n root, base = _make_tree()\n try:\n assert target_module.pull_artifact_text(str(base), \"pier_514.txt\") == \"ok_content_pier_514\"\n finally:\n shutil.rmtree(root)\n\ndef test_read_nested_file():\n root, base = _make_tree()\n try:\n assert target_module.pull_artifact_text(str(base), \"nested/report.txt\") == \"nested_ok\"\n finally:\n shutil.rmtree(root)\n\n_run_checks([(\"read_root_file\", test_read_root_file), (\"read_nested_file\", test_read_nested_file)])\n", "exploit_tests": "import json\nimport sys\n\ndef _run_checks(checks):\n passed = 0\n failures = []\n for name, fn in checks:\n try:\n fn()\n passed += 1\n except Exception as exc:\n failures.append(f\"{name}: {type(exc).__name__}: {exc}\")\n print(\"PATCHGUARD_RESULT:\" + json.dumps({\"passed\": passed, \"total\": len(checks), \"failures\": failures}))\n sys.exit(0 if passed == len(checks) else 1)\nimport tempfile\nfrom pathlib import Path\nimport target_module\n\ndef _make_tree():\n root = Path(tempfile.mkdtemp())\n base = root / \"store\"\n sub = base / \"nested\"\n sibling = root / \"store_evil\"\n sub.mkdir(parents=True)\n sibling.mkdir(parents=True)\n (base / \"pier_514.txt\").write_text(\"ok_content_pier_514\", encoding=\"utf-8\")\n (sub / \"report.txt\").write_text(\"nested_ok\", encoding=\"utf-8\")\n (root / \"outside.txt\").write_text(\"SECRET_OUTSIDE\", encoding=\"utf-8\")\n (sibling / \"trap.txt\").write_text(\"SECRET_SIBLING\", encoding=\"utf-8\")\n return root, base\nimport shutil\n\ndef _assert_blocked(base, rel):\n try:\n out = target_module.pull_artifact_text(str(base), rel)\n except (ValueError, PermissionError, FileNotFoundError, OSError):\n return\n raise AssertionError(f\"Traversal succeeded for {rel!r}: {out!r}\")\n\ndef test_dotdot_escape():\n root, base = _make_tree()\n try:\n _assert_blocked(base, \"../outside.txt\")\n finally:\n shutil.rmtree(root)\n\ndef test_nested_dotdot_bypass():\n root, base = _make_tree()\n try:\n _assert_blocked(base, \"nested/../../outside.txt\")\n finally:\n shutil.rmtree(root)\n\ndef test_sibling_prefix_confusion():\n root, base = _make_tree()\n try:\n _assert_blocked(base, \"../store_evil/trap.txt\")\n finally:\n shutil.rmtree(root)\n\ndef test_absolute_path_escape():\n root, base = _make_tree()\n try:\n _assert_blocked(base, str((root / \"outside.txt\").resolve()))\n finally:\n shutil.rmtree(root)\n\n_run_checks([\n (\"dotdot_escape\", test_dotdot_escape),\n (\"nested_dotdot_bypass\", test_nested_dotdot_bypass),\n (\"sibling_prefix_confusion\", test_sibling_prefix_confusion),\n (\"absolute_path_escape\", test_absolute_path_escape),\n])\n", "metadata": {"cwe": "CWE-22", "fn": "pull_artifact_text"}} {"task_id": "pg-test-cmd_injection-0002", "category": "cmd_injection", "split": "test", "seed": 5677763125890085475, "domain": "harbor_berths", "system_prompt": "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.", "user_prompt": "Service module `harbor_berths` 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_harbor_berths_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", "vulnerable_code": "import subprocess\nimport sys\n\n\ndef run_harbor_berths_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", "reference_patch": "import subprocess\nimport sys\n\n_ALLOWED_MODES = frozenset({\"summary\", \"verify\"})\n\n\ndef run_harbor_berths_tool(script_path: str, mode: str, target_name: str) -> str:\n \"\"\"Execute the local helper script safely without a shell and with option separation.\"\"\"\n if mode not in _ALLOWED_MODES:\n raise ValueError(f\"Unsupported mode: {mode!r}\")\n if not isinstance(target_name, str) or not target_name or \"\\x00\" in target_name:\n raise ValueError(\"Invalid target_name\")\n proc = subprocess.run(\n [sys.executable, script_path, \"--mode\", mode, \"--\", target_name],\n shell=False,\n capture_output=True,\n text=True,\n check=True,\n )\n return proc.stdout.strip()\n", "functional_tests": "import json\nimport sys\n\ndef _run_checks(checks):\n passed = 0\n failures = []\n for name, fn in checks:\n try:\n fn()\n passed += 1\n except Exception as exc:\n failures.append(f\"{name}: {type(exc).__name__}: {exc}\")\n print(\"PATCHGUARD_RESULT:\" + json.dumps({\"passed\": passed, \"total\": len(checks), \"failures\": failures}))\n sys.exit(0 if passed == len(checks) else 1)\nimport shutil\nimport tempfile\nfrom pathlib import Path\nimport target_module\n\nHELPER_SRC = '''\nimport sys\nargs = sys.argv[1:]\nif \"--evil-probe\" in args and (\"--\" not in args or args.index(\"--evil-probe\") < args.index(\"--\")):\n Path_marker = Path(args[args.index(\"--evil-probe\") + 1])\n Path_marker.write_text(\"OPTION_INJECTED\", encoding=\"utf-8\")\nif \"--\" in args:\n target = args[args.index(\"--\") + 1]\nelse:\n target = args[-1]\nmode = args[args.index(\"--mode\") + 1] if \"--mode\" in args else \"unknown\"\nprint(f\"{mode}:{target}\")\n'''.strip()\n\ndef _make_helper():\n d = Path(tempfile.mkdtemp())\n hp = d / \"helper.py\"\n hp.write_text(\"from pathlib import Path\\n\" + HELPER_SRC, encoding=\"utf-8\")\n return d, hp\ndef test_summary():\n d, hp = _make_helper()\n try:\n out = target_module.run_harbor_berths_tool(str(hp), \"summary\", \"grove_623\")\n assert out == \"summary:grove_623\", f\"unexpected output: {out!r}\"\n finally:\n shutil.rmtree(d)\n\ndef test_verify():\n d, hp = _make_helper()\n try:\n out = target_module.run_harbor_berths_tool(str(hp), \"verify\", \"batch_2\")\n assert out == \"verify:batch_2\"\n finally:\n shutil.rmtree(d)\n\n_run_checks([(\"summary\", test_summary), (\"verify\", test_verify)])\n", "exploit_tests": "import json\nimport sys\n\ndef _run_checks(checks):\n passed = 0\n failures = []\n for name, fn in checks:\n try:\n fn()\n passed += 1\n except Exception as exc:\n failures.append(f\"{name}: {type(exc).__name__}: {exc}\")\n print(\"PATCHGUARD_RESULT:\" + json.dumps({\"passed\": passed, \"total\": len(checks), \"failures\": failures}))\n sys.exit(0 if passed == len(checks) else 1)\nimport shutil\nimport tempfile\nfrom pathlib import Path\nimport target_module\n\nHELPER_SRC = '''\nimport sys\nargs = sys.argv[1:]\nif \"--evil-probe\" in args and (\"--\" not in args or args.index(\"--evil-probe\") < args.index(\"--\")):\n Path_marker = Path(args[args.index(\"--evil-probe\") + 1])\n Path_marker.write_text(\"OPTION_INJECTED\", encoding=\"utf-8\")\nif \"--\" in args:\n target = args[args.index(\"--\") + 1]\nelse:\n target = args[-1]\nmode = args[args.index(\"--mode\") + 1] if \"--mode\" in args else \"unknown\"\nprint(f\"{mode}:{target}\")\n'''.strip()\n\ndef _make_helper():\n d = Path(tempfile.mkdtemp())\n hp = d / \"helper.py\"\n hp.write_text(\"from pathlib import Path\\n\" + HELPER_SRC, encoding=\"utf-8\")\n return d, hp\ndef test_shell_separator():\n d, hp = _make_helper()\n marker = d / \"pwn_sep.txt\"\n payload = f\"grove_623 && python -c \\\"open(r'{marker}','w').write('PWN')\\\"\"\n try:\n try:\n target_module.run_harbor_berths_tool(str(hp), \"summary\", payload)\n except Exception:\n pass\n assert not marker.exists(), \"Shell separator command injection executed!\"\n finally:\n shutil.rmtree(d)\n\ndef test_mode_injection():\n d, hp = _make_helper()\n marker = d / \"pwn_mode.txt\"\n try:\n raised = False\n try:\n target_module.run_harbor_berths_tool(str(hp), f\"summary --evil-probe {marker}\", \"grove_623\")\n except Exception:\n raised = True\n assert raised or not marker.exists(), \"Mode argument injection succeeded!\"\n finally:\n shutil.rmtree(d)\n\ndef test_option_injection():\n d, hp = _make_helper()\n marker = d / \"pwn_opt.txt\"\n try:\n try:\n target_module.run_harbor_berths_tool(str(hp), \"summary\", f\"--evil-probe {marker}\")\n except Exception:\n pass\n assert not marker.exists(), \"Flag injection (--evil-probe) was parsed as option!\"\n finally:\n shutil.rmtree(d)\n\n_run_checks([\n (\"shell_separator\", test_shell_separator),\n (\"mode_injection\", test_mode_injection),\n (\"option_injection\", test_option_injection),\n])\n", "metadata": {"cwe": "CWE-78", "fn": "run_harbor_berths_tool"}} {"task_id": "pg-test-ssrf-0003", "category": "ssrf", "split": "test", "seed": 14258634085644288435, "domain": "orchard_yields", "system_prompt": "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.", "user_prompt": "Service module `orchard_yields` 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 read_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", "vulnerable_code": "import urllib.request\n\n\ndef read_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", "reference_patch": "import ipaddress\nimport socket\nimport urllib.parse\nimport urllib.request\n\n\ndef _is_forbidden_ip(addr_str: str) -> bool:\n ip = ipaddress.ip_address(addr_str)\n if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:\n ip = ip.ipv4_mapped\n return (\n ip.is_private\n or ip.is_loopback\n or ip.is_link_local\n or ip.is_multicast\n or ip.is_reserved\n or ip.is_unspecified\n )\n\n\ndef read_remote_feed(url: str, resolver=None, transport=None) -> str:\n \"\"\"Safely validate scheme, host, and resolved IPs before fetching a remote URL.\"\"\"\n parsed = urllib.parse.urlsplit(url)\n if parsed.scheme.lower() not in {\"http\", \"https\"}:\n raise ValueError(f\"Forbidden URL scheme: {parsed.scheme!r}\")\n if parsed.username or parsed.password or not parsed.hostname:\n raise ValueError(\"URL must contain a valid hostname without embedded credentials\")\n\n host = parsed.hostname.rstrip(\".\")\n try:\n # Reject raw IP literals (including decimal/hex/v4-mapped) if non-public\n if _is_forbidden_ip(host):\n raise PermissionError(f\"Blocked non-public IP literal: {host}\")\n ips = [host]\n except ValueError:\n resolve_fn = resolver or (lambda h: [info[4][0] for info in socket.getaddrinfo(h, None)])\n ips = list(resolve_fn(host))\n if not ips:\n raise ValueError(f\"Could not resolve host: {host}\")\n\n for ip_str in ips:\n if _is_forbidden_ip(ip_str):\n raise PermissionError(f\"Blocked internal/reserved resolved IP: {ip_str}\")\n\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", "functional_tests": "import json\nimport sys\n\ndef _run_checks(checks):\n passed = 0\n failures = []\n for name, fn in checks:\n try:\n fn()\n passed += 1\n except Exception as exc:\n failures.append(f\"{name}: {type(exc).__name__}: {exc}\")\n print(\"PATCHGUARD_RESULT:\" + json.dumps({\"passed\": passed, \"total\": len(checks), \"failures\": failures}))\n sys.exit(0 if passed == len(checks) else 1)\nimport target_module\n\ndef _public_resolver(host):\n if host == \"feeds.helios-grid.example\":\n return [\"93.184.216.34\"]\n return [\"127.0.0.1\"]\n\ndef _fake_transport(url):\n return f\"fetched:{url}\"\ndef test_valid_https():\n out = target_module.read_remote_feed(\n \"https://feeds.helios-grid.example/v1/data.json\",\n resolver=_public_resolver,\n transport=_fake_transport,\n )\n assert out == \"fetched:https://feeds.helios-grid.example/v1/data.json\"\n\n_run_checks([(\"valid_https\", test_valid_https)])\n", "exploit_tests": "import json\nimport sys\n\ndef _run_checks(checks):\n passed = 0\n failures = []\n for name, fn in checks:\n try:\n fn()\n passed += 1\n except Exception as exc:\n failures.append(f\"{name}: {type(exc).__name__}: {exc}\")\n print(\"PATCHGUARD_RESULT:\" + json.dumps({\"passed\": passed, \"total\": len(checks), \"failures\": failures}))\n sys.exit(0 if passed == len(checks) else 1)\nimport target_module\n\ndef _public_resolver(host):\n if host == \"feeds.helios-grid.example\":\n return [\"93.184.216.34\"]\n return [\"127.0.0.1\"]\n\ndef _fake_transport(url):\n return f\"fetched:{url}\"\ndef _assert_ssrf_blocked(url, resolver=_public_resolver):\n called = False\n def _trap(u):\n nonlocal called\n called = True\n return \"LEAKED\"\n try:\n target_module.read_remote_feed(url, resolver=resolver, transport=_trap)\n except Exception:\n assert not called\n return\n raise AssertionError(f\"SSRF URL was not blocked: {url!r} (called={called})\")\n\ndef test_loopback_v4():\n _assert_ssrf_blocked(\"http://127.0.0.1/admin\")\n\ndef test_metadata_ip():\n _assert_ssrf_blocked(\"http://169.254.169.254/latest/meta-data/\")\n\ndef test_ipv6_mapped_loopback():\n _assert_ssrf_blocked(\"http://[::ffff:127.0.0.1]/secret\")\n\ndef test_private_rfc1918():\n _assert_ssrf_blocked(\"http://10.0.0.8/internal\")\n\ndef test_dns_rebinding_private():\n _assert_ssrf_blocked(\"https://internal-alias.example/keys\", resolver=lambda h: [\"127.0.0.1\"])\n\n_run_checks([\n (\"loopback_v4\", test_loopback_v4),\n (\"metadata_ip\", test_metadata_ip),\n (\"ipv6_mapped_loopback\", test_ipv6_mapped_loopback),\n (\"private_rfc1918\", test_private_rfc1918),\n (\"dns_rebinding_private\", test_dns_rebinding_private),\n])\n", "metadata": {"cwe": "CWE-918", "fn": "read_remote_feed"}} {"task_id": "pg-test-idor_auth-0004", "category": "idor_auth", "split": "test", "seed": 5607445262945912138, "domain": "orchard_yields", "system_prompt": "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.", "user_prompt": "Service module `orchard_yields` 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_inverters_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", "vulnerable_code": "def update_inverters_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", "reference_patch": "_PROTECTED_FIELDS = frozenset({\"owner_id\", \"role\", \"is_admin\", \"id\"})\n\n\ndef update_inverters_record(store: dict, session: dict, resource_id: str, payload: dict | None = None) -> dict:\n \"\"\"Authorize authenticated owner/admin access and prevent mass-assignment privilege escalation.\"\"\"\n caller_id = session.get(\"user_id\") if isinstance(session, dict) else None\n if not caller_id:\n raise PermissionError(\"Authentication required\")\n if resource_id not in store:\n raise KeyError(resource_id)\n\n record = store[resource_id]\n is_server_admin = session.get(\"role\") == \"admin\"\n if record.get(\"owner_id\") != caller_id and not is_server_admin:\n raise PermissionError(\"Caller is not authorized to access this resource\")\n\n if payload:\n for key, value in payload.items():\n if key in _PROTECTED_FIELDS:\n continue\n record[key] = value\n return dict(record)\n", "functional_tests": "import json\nimport sys\n\ndef _run_checks(checks):\n passed = 0\n failures = []\n for name, fn in checks:\n try:\n fn()\n passed += 1\n except Exception as exc:\n failures.append(f\"{name}: {type(exc).__name__}: {exc}\")\n print(\"PATCHGUARD_RESULT:\" + json.dumps({\"passed\": passed, \"total\": len(checks), \"failures\": failures}))\n sys.exit(0 if passed == len(checks) else 1)\nimport target_module\n\ndef _make_store():\n return {\n \"grove_623_1\": {\"id\": \"grove_623_1\", \"owner_id\": \"acct_quartz_a\", \"note\": \"initial\", \"status\": \"open\"},\n \"grove_623_2\": {\"id\": \"grove_623_2\", \"owner_id\": \"acct_quartz_b\", \"note\": \"private_b\", \"status\": \"sealed\"},\n }\ndef test_owner_read_and_update():\n s = _make_store()\n sess = {\"user_id\": \"acct_quartz_a\", \"role\": \"member\"}\n out = target_module.update_inverters_record(s, sess, \"grove_623_1\", {\"note\": \"updated\"})\n assert out[\"note\"] == \"updated\"\n assert out[\"owner_id\"] == \"acct_quartz_a\"\n\ndef test_admin_access():\n s = _make_store()\n sess = {\"user_id\": \"sec_admin\", \"role\": \"admin\"}\n out = target_module.update_inverters_record(s, sess, \"grove_623_2\")\n assert out[\"note\"] == \"private_b\"\n\n_run_checks([(\"owner_read_and_update\", test_owner_read_and_update), (\"admin_access\", test_admin_access)])\n", "exploit_tests": "import json\nimport sys\n\ndef _run_checks(checks):\n passed = 0\n failures = []\n for name, fn in checks:\n try:\n fn()\n passed += 1\n except Exception as exc:\n failures.append(f\"{name}: {type(exc).__name__}: {exc}\")\n print(\"PATCHGUARD_RESULT:\" + json.dumps({\"passed\": passed, \"total\": len(checks), \"failures\": failures}))\n sys.exit(0 if passed == len(checks) else 1)\nimport target_module\n\ndef _make_store():\n return {\n \"grove_623_1\": {\"id\": \"grove_623_1\", \"owner_id\": \"acct_quartz_a\", \"note\": \"initial\", \"status\": \"open\"},\n \"grove_623_2\": {\"id\": \"grove_623_2\", \"owner_id\": \"acct_quartz_b\", \"note\": \"private_b\", \"status\": \"sealed\"},\n }\ndef test_unauthenticated_blocked():\n s = _make_store()\n try:\n target_module.update_inverters_record(s, {}, \"grove_623_1\")\n except PermissionError:\n return\n raise AssertionError(\"Unauthenticated session accessed record\")\n\ndef test_cross_tenant_idor_blocked():\n s = _make_store()\n sess = {\"user_id\": \"acct_quartz_a\", \"role\": \"member\"}\n try:\n target_module.update_inverters_record(s, sess, \"grove_623_2\", {\"note\": \"tampered\"})\n except PermissionError:\n assert s[\"grove_623_2\"][\"note\"] == \"private_b\"\n return\n raise AssertionError(\"Cross-tenant IDOR succeeded\")\n\ndef test_mass_assignment_blocked():\n s = _make_store()\n sess = {\"user_id\": \"acct_quartz_a\", \"role\": \"member\"}\n try:\n out = target_module.update_inverters_record(s, sess, \"grove_623_1\", {\"owner_id\": \"acct_quartz_b\", \"is_admin\": True, \"role\": \"admin\"})\n except (ValueError, PermissionError):\n assert s[\"grove_623_1\"][\"owner_id\"] == \"acct_quartz_a\"\n assert not s[\"grove_623_1\"].get(\"is_admin\")\n assert s[\"grove_623_1\"].get(\"role\") != \"admin\"\n return\n assert out[\"owner_id\"] == \"acct_quartz_a\", \"owner_id overwritten via mass assignment\"\n assert not out.get(\"is_admin\"), \"is_admin injected via payload\"\n assert out.get(\"role\") != \"admin\", \"role escalated via payload\"\n\n_run_checks([\n (\"unauthenticated_blocked\", test_unauthenticated_blocked),\n (\"cross_tenant_idor_blocked\", test_cross_tenant_idor_blocked),\n (\"mass_assignment_blocked\", test_mass_assignment_blocked),\n])\n", "metadata": {"cwe": "CWE-639", "fn": "update_inverters_record"}} {"task_id": "pg-test-unsafe_deser_eval-0005", "category": "unsafe_deser_eval", "split": "test", "seed": 1693966912840396797, "domain": "solar_telemetry", "system_prompt": "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.", "user_prompt": "Service module `solar_telemetry` 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_solar_telemetry_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", "vulnerable_code": "import pickle\n\n\ndef parse_solar_telemetry_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", "reference_patch": "import json\n\n\ndef parse_solar_telemetry_payload(raw_payload: str) -> dict:\n \"\"\"Safely decode an incoming JSON message dictionary without code execution.\"\"\"\n if not isinstance(raw_payload, str) or len(raw_payload) > 65536:\n raise ValueError(\"Invalid payload\")\n try:\n data = json.loads(raw_payload)\n except json.JSONDecodeError as exc:\n raise ValueError(\"Payload must be valid JSON\") from exc\n if not isinstance(data, dict):\n raise ValueError(\"Payload must decode to a dict\")\n return data\n", "functional_tests": "import json\nimport sys\n\ndef _run_checks(checks):\n passed = 0\n failures = []\n for name, fn in checks:\n try:\n fn()\n passed += 1\n except Exception as exc:\n failures.append(f\"{name}: {type(exc).__name__}: {exc}\")\n print(\"PATCHGUARD_RESULT:\" + json.dumps({\"passed\": passed, \"total\": len(checks), \"failures\": failures}))\n sys.exit(0 if passed == len(checks) else 1)\nimport target_module\n\ndef test_valid_dict():\n out = target_module.parse_solar_telemetry_payload('{\"item\": \"panel_881\", \"count\": 4}')\n assert out == {\"item\": \"panel_881\", \"count\": 4}\n\ndef test_non_dict_rejected():\n try:\n target_module.parse_solar_telemetry_payload('[1, 2, 3]')\n except ValueError:\n return\n raise AssertionError(\"List payload should raise ValueError\")\n\n_run_checks([(\"valid_dict\", test_valid_dict), (\"non_dict_rejected\", test_non_dict_rejected)])\n", "exploit_tests": "import json\nimport sys\n\ndef _run_checks(checks):\n passed = 0\n failures = []\n for name, fn in checks:\n try:\n fn()\n passed += 1\n except Exception as exc:\n failures.append(f\"{name}: {type(exc).__name__}: {exc}\")\n print(\"PATCHGUARD_RESULT:\" + json.dumps({\"passed\": passed, \"total\": len(checks), \"failures\": failures}))\n sys.exit(0 if passed == len(checks) else 1)\nimport os\nimport pickle\nimport tempfile\nfrom pathlib import Path\nimport target_module\n\nclass _RCE:\n def __init__(self, marker):\n self.marker = marker\n def __reduce__(self):\n return (Path(self.marker).write_text, (\"PWNED\",))\n\ndef test_pickle_rce_blocked():\n d = Path(tempfile.mkdtemp())\n marker = d / \"pickle_pwn.txt\"\n blob = \"pickle:\" + pickle.dumps(_RCE(str(marker))).hex()\n try:\n try:\n target_module.parse_solar_telemetry_payload(blob)\n except (ValueError, TypeError):\n pass\n assert not marker.exists(), \"Unsafe pickle deserialization executed arbitrary code!\"\n finally:\n if marker.exists():\n marker.unlink()\n d.rmdir()\n\ndef test_eval_rce_blocked():\n d = Path(tempfile.mkdtemp())\n marker = d / \"eval_pwn.txt\"\n payload = f\"__import__('pathlib').Path(r'{marker}').write_text('PWNED') or dict()\"\n try:\n try:\n target_module.parse_solar_telemetry_payload(payload)\n except (ValueError, TypeError):\n pass\n assert not marker.exists(), \"eval() executed arbitrary expression!\"\n finally:\n if marker.exists():\n marker.unlink()\n d.rmdir()\n\n_run_checks([(\"pickle_rce_blocked\", test_pickle_rce_blocked), (\"eval_rce_blocked\", test_eval_rce_blocked)])\n", "metadata": {"cwe": "CWE-502", "fn": "parse_solar_telemetry_payload"}} {"task_id": "pg-test-xss-0006", "category": "xss", "split": "test", "seed": 69365509385772663, "domain": "solar_telemetry", "system_prompt": "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.", "user_prompt": "Service module `solar_telemetry` 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_harvests_badge(title: str, summary: str, link_url: str) -> str:\n \"\"\"Render an HTML card badge with title, summary, and external link.\"\"\"\n return f'
'\n```\n", "vulnerable_code": "def render_harvests_badge(title: str, summary: str, link_url: str) -> str:\n \"\"\"Render an HTML card badge with title, summary, and external link.\"\"\"\n return f''\n", "reference_patch": "import html\nimport urllib.parse\n\n\ndef render_harvests_badge(title: str, summary: str, link_url: str) -> str:\n \"\"\"Render an HTML card badge with escaped attributes/text and safe http(s) URL.\"\"\"\n parsed = urllib.parse.urlsplit(link_url.strip())\n if parsed.scheme.lower() not in {\"http\", \"https\"} or not parsed.netloc:\n raise ValueError(f\"Unsafe link URL scheme: {link_url!r}\")\n\n safe_title = html.escape(title, quote=True)\n safe_summary = html.escape(summary, quote=True)\n safe_url = html.escape(link_url.strip(), quote=True)\n return f''\n", "functional_tests": "import json\nimport sys\n\ndef _run_checks(checks):\n passed = 0\n failures = []\n for name, fn in checks:\n try:\n fn()\n passed += 1\n except Exception as exc:\n failures.append(f\"{name}: {type(exc).__name__}: {exc}\")\n print(\"PATCHGUARD_RESULT:\" + json.dumps({\"passed\": passed, \"total\": len(checks), \"failures\": failures}))\n sys.exit(0 if passed == len(checks) else 1)\nimport target_module\n\ndef test_valid_render():\n out = target_module.render_harvests_badge(\"grove_623\", \"Status OK\", \"https://feeds.helios-grid.example/info\")\n assert 'title=\"grove_623\"' in out\n assert 'href=\"https://feeds.helios-grid.example/info\"' in out\n assert \">Status OK\" in out\n\n_run_checks([(\"valid_render\", test_valid_render)])\n", "exploit_tests": "import json\nimport sys\n\ndef _run_checks(checks):\n passed = 0\n failures = []\n for name, fn in checks:\n try:\n fn()\n passed += 1\n except Exception as exc:\n failures.append(f\"{name}: {type(exc).__name__}: {exc}\")\n print(\"PATCHGUARD_RESULT:\" + json.dumps({\"passed\": passed, \"total\": len(checks), \"failures\": failures}))\n sys.exit(0 if passed == len(checks) else 1)\nimport target_module\n\ndef test_script_tag_escaped():\n out = target_module.render_harvests_badge(\"t\", \"\", \"https://feeds.helios-grid.example/ok\")\n assert \"\", \"https://port.tidewater-dock.example/ok\")\n assert \"\", \"https://port.tidewater-dock.example/ok\")\n assert \"\", \"https://feeds.helios-grid.example/ok\")\n assert \"\", \"https://port.tidewater-dock.example/ok\")\n assert \"\", \"https://port.tidewater-dock.example/ok\")\n assert \"\", \"https://feeds.helios-grid.example/ok\")\n assert \"\", \"https://feeds.helios-grid.example/ok\")\n assert \"