File size: 429,241 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
{"task_id": "pg-fresh-sqli-0000", "category": "sqli", "split": "fresh", "seed": 1487231614253495133, "domain": "rail_signaling", "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 `rail_signaling` 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 gather_exposures(db_path: str, query: str, sort_by: str = \"salinity_ppt\", limit: int = 10) -> list[dict]:\n    \"\"\"Search exposures matching query on nebula_ref and return sorted rows.\"\"\"\n    conn = sqlite3.connect(db_path)\n    conn.row_factory = sqlite3.Row\n    try:\n        sql = (\n            f\"SELECT id, nebula_ref, category_tag, salinity_ppt \"\n            f\"FROM exposures \"\n            f\"WHERE nebula_ref 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 gather_exposures(db_path: str, query: str, sort_by: str = \"salinity_ppt\", limit: int = 10) -> list[dict]:\n    \"\"\"Search exposures matching query on nebula_ref and return sorted rows.\"\"\"\n    conn = sqlite3.connect(db_path)\n    conn.row_factory = sqlite3.Row\n    try:\n        sql = (\n            f\"SELECT id, nebula_ref, category_tag, salinity_ppt \"\n            f\"FROM exposures \"\n            f\"WHERE nebula_ref 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\", \"nebula_ref\", \"category_tag\", \"salinity_ppt\"})\n\n\ndef gather_exposures(db_path: str, query: str, sort_by: str = \"salinity_ppt\", limit: int = 10) -> list[dict]:\n    \"\"\"Search exposures matching query on nebula_ref 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, nebula_ref, category_tag, salinity_ppt \"\n            f\"FROM exposures \"\n            f\"WHERE nebula_ref 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 exposures (id INTEGER PRIMARY KEY, nebula_ref TEXT, category_tag TEXT, salinity_ppt 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 exposures (nebula_ref, category_tag, salinity_ppt) VALUES (?, ?, ?)\",\n        [\n            (\"reef_532_alpha\", \"pelagic\", 10),\n            (\"reef_532_beta\", \"pelagic\", 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.gather_exposures(p, \"reef_532\")\n        assert len(rows) == 2, f\"expected 2 rows, got {rows}\"\n        assert rows[0][\"salinity_ppt\"] == 25\n    finally:\n        os.remove(p)\n\ndef test_sort_and_limit():\n    p = _make_db()\n    try:\n        rows = target_module.gather_exposures(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 exposures (id INTEGER PRIMARY KEY, nebula_ref TEXT, category_tag TEXT, salinity_ppt 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 exposures (nebula_ref, category_tag, salinity_ppt) VALUES (?, ?, ?)\",\n        [\n            (\"reef_532_alpha\", \"pelagic\", 10),\n            (\"reef_532_beta\", \"pelagic\", 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.gather_exposures(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.gather_exposures(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.gather_exposures(p, \"reef_532\", sort_by=\"(CASE WHEN (1=1) THEN id ELSE salinity_ppt 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": "gather_exposures"}}
{"task_id": "pg-fresh-path_traversal-0001", "category": "path_traversal", "split": "fresh", "seed": 978973226973390080, "domain": "observatory_logs", "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 `observatory_logs` 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 resolve_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 resolve_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 resolve_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 / \"relay_910.txt\").write_text(\"ok_content_relay_910\", 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.resolve_artifact_text(str(base), \"relay_910.txt\") == \"ok_content_relay_910\"\n    finally:\n        shutil.rmtree(root)\n\ndef test_read_nested_file():\n    root, base = _make_tree()\n    try:\n        assert target_module.resolve_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 / \"relay_910.txt\").write_text(\"ok_content_relay_910\", 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.resolve_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": "resolve_artifact_text"}}
{"task_id": "pg-fresh-cmd_injection-0002", "category": "cmd_injection", "split": "fresh", "seed": 2269837507098429116, "domain": "aquarium_tanks", "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 `aquarium_tanks` 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_aquarium_tanks_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_aquarium_tanks_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_aquarium_tanks_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_aquarium_tanks_tool(str(hp), \"summary\", \"relay_910\")\n        assert out == \"summary:relay_910\", 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_aquarium_tanks_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\"relay_910 && python -c \\\"open(r'{marker}','w').write('PWN')\\\"\"\n    try:\n        try:\n            target_module.run_aquarium_tanks_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_aquarium_tanks_tool(str(hp), f\"summary --evil-probe {marker}\", \"relay_910\")\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_aquarium_tanks_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_aquarium_tanks_tool"}}
{"task_id": "pg-fresh-ssrf-0003", "category": "ssrf", "split": "fresh", "seed": 12124550067024641691, "domain": "aquarium_tanks", "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 `aquarium_tanks` 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 gather_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 gather_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 gather_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 == \"status.ironline-rail.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.gather_remote_feed(\n        \"https://status.ironline-rail.example/v1/data.json\",\n        resolver=_public_resolver,\n        transport=_fake_transport,\n    )\n    assert out == \"fetched:https://status.ironline-rail.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 == \"status.ironline-rail.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.gather_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": "gather_remote_feed"}}
{"task_id": "pg-fresh-idor_auth-0004", "category": "idor_auth", "split": "fresh", "seed": 3120895590593004728, "domain": "observatory_logs", "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 `observatory_logs` 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_switches_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_switches_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_switches_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        \"frame_447_1\": {\"id\": \"frame_447_1\", \"owner_id\": \"lab_topaz_a\", \"note\": \"initial\", \"status\": \"open\"},\n        \"frame_447_2\": {\"id\": \"frame_447_2\", \"owner_id\": \"lab_topaz_b\", \"note\": \"private_b\", \"status\": \"sealed\"},\n    }\ndef test_owner_read_and_update():\n    s = _make_store()\n    sess = {\"user_id\": \"lab_topaz_a\", \"role\": \"member\"}\n    out = target_module.update_switches_record(s, sess, \"frame_447_1\", {\"note\": \"updated\"})\n    assert out[\"note\"] == \"updated\"\n    assert out[\"owner_id\"] == \"lab_topaz_a\"\n\ndef test_admin_access():\n    s = _make_store()\n    sess = {\"user_id\": \"sec_admin\", \"role\": \"admin\"}\n    out = target_module.update_switches_record(s, sess, \"frame_447_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        \"frame_447_1\": {\"id\": \"frame_447_1\", \"owner_id\": \"lab_topaz_a\", \"note\": \"initial\", \"status\": \"open\"},\n        \"frame_447_2\": {\"id\": \"frame_447_2\", \"owner_id\": \"lab_topaz_b\", \"note\": \"private_b\", \"status\": \"sealed\"},\n    }\ndef test_unauthenticated_blocked():\n    s = _make_store()\n    try:\n        target_module.update_switches_record(s, {}, \"frame_447_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\": \"lab_topaz_a\", \"role\": \"member\"}\n    try:\n        target_module.update_switches_record(s, sess, \"frame_447_2\", {\"note\": \"tampered\"})\n    except PermissionError:\n        assert s[\"frame_447_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\": \"lab_topaz_a\", \"role\": \"member\"}\n    try:\n        out = target_module.update_switches_record(s, sess, \"frame_447_1\", {\"owner_id\": \"lab_topaz_b\", \"is_admin\": True, \"role\": \"admin\"})\n    except (ValueError, PermissionError):\n        assert s[\"frame_447_1\"][\"owner_id\"] == \"lab_topaz_a\"\n        assert not s[\"frame_447_1\"].get(\"is_admin\")\n        assert s[\"frame_447_1\"].get(\"role\") != \"admin\"\n        return\n    assert out[\"owner_id\"] == \"lab_topaz_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_switches_record"}}
{"task_id": "pg-fresh-unsafe_deser_eval-0005", "category": "unsafe_deser_eval", "split": "fresh", "seed": 6838099877278999275, "domain": "observatory_logs", "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 `observatory_logs` 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_observatory_logs_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_observatory_logs_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_observatory_logs_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_observatory_logs_payload('{\"item\": \"frame_447\", \"count\": 4}')\n    assert out == {\"item\": \"frame_447\", \"count\": 4}\n\ndef test_non_dict_rejected():\n    try:\n        target_module.parse_observatory_logs_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_observatory_logs_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_observatory_logs_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_observatory_logs_payload"}}
{"task_id": "pg-fresh-xss-0006", "category": "xss", "split": "fresh", "seed": 9080619959989718252, "domain": "rail_signaling", "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 `rail_signaling` 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_switches_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", "vulnerable_code": "def render_switches_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", "reference_patch": "import html\nimport urllib.parse\n\n\ndef render_switches_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'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_url}\">{safe_summary}</a></div>'\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_switches_badge(\"frame_447\", \"Status OK\", \"https://mirror.zenith-sky.example/info\")\n    assert 'title=\"frame_447\"' in out\n    assert 'href=\"https://mirror.zenith-sky.example/info\"' in out\n    assert \">Status OK</a>\" 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_switches_badge(\"t\", \"<script>alert(1)</script>\", \"https://mirror.zenith-sky.example/ok\")\n    assert \"<script>\" not in out.lower(), f\"Unescaped <script> in output: {out}\"\n    assert \"&lt;script&gt;\" in out\n\ndef test_attribute_breakout_escaped():\n    out = target_module.render_switches_badge('\" onmouseover=\"alert(1)', \"ok\", \"https://mirror.zenith-sky.example/ok\")\n    assert 'onmouseover=\"alert' not in out.lower()\n    assert \"&quot;\" in out or \"&#x27;\" in out\n\ndef test_javascript_href_rejected():\n    try:\n        out = target_module.render_switches_badge(\"t\", \"click\", \"JaVaScRiPt:alert(1)\")\n    except ValueError:\n        return\n    assert \"javascript:\" not in out.lower(), f\"javascript: URL rendered in href: {out}\"\n\n_run_checks([\n    (\"script_tag_escaped\", test_script_tag_escaped),\n    (\"attribute_breakout_escaped\", test_attribute_breakout_escaped),\n    (\"javascript_href_rejected\", test_javascript_href_rejected),\n])\n", "metadata": {"cwe": "CWE-79", "fn": "render_switches_badge"}}
{"task_id": "pg-fresh-crypto_secrets-0007", "category": "crypto_secrets", "split": "fresh", "seed": 1233591867287122812, "domain": "observatory_logs", "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 `observatory_logs` 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 observatory_logs.\"\"\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={api_key}\"\n```\n", "vulnerable_code": "import 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 observatory_logs.\"\"\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={api_key}\"\n", "reference_patch": "import hashlib\nimport hmac\nimport secrets\n\n\ndef hash_password(password: str) -> str:\n    \"\"\"Hash a password using salted scrypt.\"\"\"\n    salt = secrets.token_bytes(16)\n    digest = hashlib.scrypt(password.encode(\"utf-8\"), salt=salt, n=16384, r=8, p=1, dklen=32)\n    return f\"scrypt${salt.hex()}${digest.hex()}\"\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n    \"\"\"Verify a password against a salted scrypt hash in constant time.\"\"\"\n    parts = stored_hash.split(\"$\")\n    if len(parts) != 3 or parts[0] != \"scrypt\":\n        return False\n    salt = bytes.fromhex(parts[1])\n    expected = bytes.fromhex(parts[2])\n    candidate = hashlib.scrypt(password.encode(\"utf-8\"), salt=salt, n=16384, r=8, p=1, dklen=len(expected))\n    return hmac.compare_digest(candidate, expected)\n\n\ndef issue_token() -> str:\n    \"\"\"Issue a cryptographically secure random URL-safe token.\"\"\"\n    return secrets.token_urlsafe(32)\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n    \"\"\"Format an audit log entry for observatory_logs with credentials redacted.\"\"\"\n    masked = \"[REDACTED]\" if not api_key else f\"***{api_key[-2:]}\" if len(api_key) > 6 else \"[REDACTED]\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={masked}\"\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_password_roundtrip():\n    h = target_module.hash_password(\"CorrectHorse!42\")\n    assert target_module.verify_password(\"CorrectHorse!42\", h) is True\n    assert target_module.verify_password(\"WrongPass!42\", h) is False\n\ndef test_token_and_audit():\n    tok = target_module.issue_token()\n    assert isinstance(tok, str) and len(tok) >= 32\n    line = target_module.format_audit_log(\"lab_topaz\", \"rotate\", \"sk_live_secret_token_9981\")\n    assert \"lab_topaz\" in line and \"rotate\" in line\n\n_run_checks([(\"password_roundtrip\", test_password_roundtrip), (\"token_and_audit\", test_token_and_audit)])\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 hashlib\nimport random\nimport target_module\n\ndef test_password_uses_salted_kdf():\n    h1 = target_module.hash_password(\"hunter2\")\n    h2 = target_module.hash_password(\"hunter2\")\n    assert h1 != h2, \"Password hash is unsalted (identical outputs for identical passwords)\"\n    assert hashlib.md5(b\"hunter2\").hexdigest() not in h1\n    assert hashlib.sha256(b\"hunter2\").hexdigest() not in h1\n\ndef test_token_unpredictable_under_random_seed():\n    random.seed(12345)\n    t1 = target_module.issue_token()\n    random.seed(12345)\n    t2 = target_module.issue_token()\n    assert t1 != t2, \"Token depends on predictable random module!\"\n\ndef test_audit_log_redacts_secret():\n    secret = \"sk_live_very_secret_987654321\"\n    line = target_module.format_audit_log(\"lab_topaz\", \"login\", secret)\n    assert secret not in line, f\"Raw API key leaked in audit log: {line}\"\n    assert \"very_secret\" not in line\n\n_run_checks([\n    (\"password_uses_salted_kdf\", test_password_uses_salted_kdf),\n    (\"token_unpredictable_under_random_seed\", test_token_unpredictable_under_random_seed),\n    (\"audit_log_redacts_secret\", test_audit_log_redacts_secret),\n])\n", "metadata": {"cwe": "CWE-327", "fn": "hash_password/verify_password/issue_token/format_audit_log"}}
{"task_id": "pg-fresh-sqli-0008", "category": "sqli", "split": "fresh", "seed": 9681630996626022071, "domain": "aquarium_tanks", "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 `aquarium_tanks` 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 collect_habitats(db_path: str, query: str, sort_by: str = \"signal_ms\", limit: int = 10) -> list[dict]:\n    \"\"\"Search habitats matching query on nebula_ref and return sorted rows.\"\"\"\n    conn = sqlite3.connect(db_path)\n    conn.row_factory = sqlite3.Row\n    try:\n        sql = (\n            f\"SELECT id, nebula_ref, category_tag, signal_ms \"\n            f\"FROM habitats \"\n            f\"WHERE nebula_ref 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 collect_habitats(db_path: str, query: str, sort_by: str = \"signal_ms\", limit: int = 10) -> list[dict]:\n    \"\"\"Search habitats matching query on nebula_ref and return sorted rows.\"\"\"\n    conn = sqlite3.connect(db_path)\n    conn.row_factory = sqlite3.Row\n    try:\n        sql = (\n            f\"SELECT id, nebula_ref, category_tag, signal_ms \"\n            f\"FROM habitats \"\n            f\"WHERE nebula_ref 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\", \"nebula_ref\", \"category_tag\", \"signal_ms\"})\n\n\ndef collect_habitats(db_path: str, query: str, sort_by: str = \"signal_ms\", limit: int = 10) -> list[dict]:\n    \"\"\"Search habitats matching query on nebula_ref 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, nebula_ref, category_tag, signal_ms \"\n            f\"FROM habitats \"\n            f\"WHERE nebula_ref 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 habitats (id INTEGER PRIMARY KEY, nebula_ref TEXT, category_tag TEXT, signal_ms 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 habitats (nebula_ref, category_tag, signal_ms) VALUES (?, ?, ?)\",\n        [\n            (\"reef_532_alpha\", \"infrared\", 10),\n            (\"reef_532_beta\", \"infrared\", 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.collect_habitats(p, \"reef_532\")\n        assert len(rows) == 2, f\"expected 2 rows, got {rows}\"\n        assert rows[0][\"signal_ms\"] == 25\n    finally:\n        os.remove(p)\n\ndef test_sort_and_limit():\n    p = _make_db()\n    try:\n        rows = target_module.collect_habitats(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 habitats (id INTEGER PRIMARY KEY, nebula_ref TEXT, category_tag TEXT, signal_ms 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 habitats (nebula_ref, category_tag, signal_ms) VALUES (?, ?, ?)\",\n        [\n            (\"reef_532_alpha\", \"infrared\", 10),\n            (\"reef_532_beta\", \"infrared\", 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.collect_habitats(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.collect_habitats(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.collect_habitats(p, \"reef_532\", sort_by=\"(CASE WHEN (1=1) THEN id ELSE signal_ms 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": "collect_habitats"}}
{"task_id": "pg-fresh-path_traversal-0009", "category": "path_traversal", "split": "fresh", "seed": 11948099732286264882, "domain": "observatory_logs", "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 `observatory_logs` 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 gather_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 gather_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 gather_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 / \"frame_447.txt\").write_text(\"ok_content_frame_447\", 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.gather_artifact_text(str(base), \"frame_447.txt\") == \"ok_content_frame_447\"\n    finally:\n        shutil.rmtree(root)\n\ndef test_read_nested_file():\n    root, base = _make_tree()\n    try:\n        assert target_module.gather_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 / \"frame_447.txt\").write_text(\"ok_content_frame_447\", 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.gather_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": "gather_artifact_text"}}
{"task_id": "pg-fresh-cmd_injection-0010", "category": "cmd_injection", "split": "fresh", "seed": 1290223179418982858, "domain": "rail_signaling", "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 `rail_signaling` 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_rail_signaling_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_rail_signaling_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_rail_signaling_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_rail_signaling_tool(str(hp), \"summary\", \"frame_447\")\n        assert out == \"summary:frame_447\", 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_rail_signaling_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\"frame_447 && python -c \\\"open(r'{marker}','w').write('PWN')\\\"\"\n    try:\n        try:\n            target_module.run_rail_signaling_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_rail_signaling_tool(str(hp), f\"summary --evil-probe {marker}\", \"frame_447\")\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_rail_signaling_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_rail_signaling_tool"}}
{"task_id": "pg-fresh-ssrf-0011", "category": "ssrf", "split": "fresh", "seed": 14384770277509097728, "domain": "observatory_logs", "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 `observatory_logs` 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 resolve_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 resolve_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 resolve_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 == \"mirror.zenith-sky.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.resolve_remote_feed(\n        \"https://mirror.zenith-sky.example/v1/data.json\",\n        resolver=_public_resolver,\n        transport=_fake_transport,\n    )\n    assert out == \"fetched:https://mirror.zenith-sky.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 == \"mirror.zenith-sky.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.resolve_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": "resolve_remote_feed"}}
{"task_id": "pg-fresh-idor_auth-0012", "category": "idor_auth", "split": "fresh", "seed": 4876441222128535219, "domain": "aquarium_tanks", "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 `aquarium_tanks` 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_switches_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_switches_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_switches_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        \"relay_910_1\": {\"id\": \"relay_910_1\", \"owner_id\": \"lab_zircon_a\", \"note\": \"initial\", \"status\": \"open\"},\n        \"relay_910_2\": {\"id\": \"relay_910_2\", \"owner_id\": \"lab_zircon_b\", \"note\": \"private_b\", \"status\": \"sealed\"},\n    }\ndef test_owner_read_and_update():\n    s = _make_store()\n    sess = {\"user_id\": \"lab_zircon_a\", \"role\": \"member\"}\n    out = target_module.update_switches_record(s, sess, \"relay_910_1\", {\"note\": \"updated\"})\n    assert out[\"note\"] == \"updated\"\n    assert out[\"owner_id\"] == \"lab_zircon_a\"\n\ndef test_admin_access():\n    s = _make_store()\n    sess = {\"user_id\": \"sec_admin\", \"role\": \"admin\"}\n    out = target_module.update_switches_record(s, sess, \"relay_910_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        \"relay_910_1\": {\"id\": \"relay_910_1\", \"owner_id\": \"lab_zircon_a\", \"note\": \"initial\", \"status\": \"open\"},\n        \"relay_910_2\": {\"id\": \"relay_910_2\", \"owner_id\": \"lab_zircon_b\", \"note\": \"private_b\", \"status\": \"sealed\"},\n    }\ndef test_unauthenticated_blocked():\n    s = _make_store()\n    try:\n        target_module.update_switches_record(s, {}, \"relay_910_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\": \"lab_zircon_a\", \"role\": \"member\"}\n    try:\n        target_module.update_switches_record(s, sess, \"relay_910_2\", {\"note\": \"tampered\"})\n    except PermissionError:\n        assert s[\"relay_910_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\": \"lab_zircon_a\", \"role\": \"member\"}\n    try:\n        out = target_module.update_switches_record(s, sess, \"relay_910_1\", {\"owner_id\": \"lab_zircon_b\", \"is_admin\": True, \"role\": \"admin\"})\n    except (ValueError, PermissionError):\n        assert s[\"relay_910_1\"][\"owner_id\"] == \"lab_zircon_a\"\n        assert not s[\"relay_910_1\"].get(\"is_admin\")\n        assert s[\"relay_910_1\"].get(\"role\") != \"admin\"\n        return\n    assert out[\"owner_id\"] == \"lab_zircon_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_switches_record"}}
{"task_id": "pg-fresh-unsafe_deser_eval-0013", "category": "unsafe_deser_eval", "split": "fresh", "seed": 12798418841994481614, "domain": "rail_signaling", "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 `rail_signaling` 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_rail_signaling_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_rail_signaling_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_rail_signaling_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_rail_signaling_payload('{\"item\": \"relay_910\", \"count\": 4}')\n    assert out == {\"item\": \"relay_910\", \"count\": 4}\n\ndef test_non_dict_rejected():\n    try:\n        target_module.parse_rail_signaling_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_rail_signaling_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_rail_signaling_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_rail_signaling_payload"}}
{"task_id": "pg-fresh-xss-0014", "category": "xss", "split": "fresh", "seed": 9928255578822879242, "domain": "aquarium_tanks", "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 `aquarium_tanks` 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_exposures_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", "vulnerable_code": "def render_exposures_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", "reference_patch": "import html\nimport urllib.parse\n\n\ndef render_exposures_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'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_url}\">{safe_summary}</a></div>'\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_exposures_badge(\"frame_447\", \"Status OK\", \"https://mirror.zenith-sky.example/info\")\n    assert 'title=\"frame_447\"' in out\n    assert 'href=\"https://mirror.zenith-sky.example/info\"' in out\n    assert \">Status OK</a>\" 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_exposures_badge(\"t\", \"<script>alert(1)</script>\", \"https://mirror.zenith-sky.example/ok\")\n    assert \"<script>\" not in out.lower(), f\"Unescaped <script> in output: {out}\"\n    assert \"&lt;script&gt;\" in out\n\ndef test_attribute_breakout_escaped():\n    out = target_module.render_exposures_badge('\" onmouseover=\"alert(1)', \"ok\", \"https://mirror.zenith-sky.example/ok\")\n    assert 'onmouseover=\"alert' not in out.lower()\n    assert \"&quot;\" in out or \"&#x27;\" in out\n\ndef test_javascript_href_rejected():\n    try:\n        out = target_module.render_exposures_badge(\"t\", \"click\", \"JaVaScRiPt:alert(1)\")\n    except ValueError:\n        return\n    assert \"javascript:\" not in out.lower(), f\"javascript: URL rendered in href: {out}\"\n\n_run_checks([\n    (\"script_tag_escaped\", test_script_tag_escaped),\n    (\"attribute_breakout_escaped\", test_attribute_breakout_escaped),\n    (\"javascript_href_rejected\", test_javascript_href_rejected),\n])\n", "metadata": {"cwe": "CWE-79", "fn": "render_exposures_badge"}}
{"task_id": "pg-fresh-crypto_secrets-0015", "category": "crypto_secrets", "split": "fresh", "seed": 1684187361317538831, "domain": "observatory_logs", "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 `observatory_logs` 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 observatory_logs.\"\"\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={api_key}\"\n```\n", "vulnerable_code": "import 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 observatory_logs.\"\"\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={api_key}\"\n", "reference_patch": "import hashlib\nimport hmac\nimport secrets\n\n\ndef hash_password(password: str) -> str:\n    \"\"\"Hash a password using salted scrypt.\"\"\"\n    salt = secrets.token_bytes(16)\n    digest = hashlib.scrypt(password.encode(\"utf-8\"), salt=salt, n=16384, r=8, p=1, dklen=32)\n    return f\"scrypt${salt.hex()}${digest.hex()}\"\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n    \"\"\"Verify a password against a salted scrypt hash in constant time.\"\"\"\n    parts = stored_hash.split(\"$\")\n    if len(parts) != 3 or parts[0] != \"scrypt\":\n        return False\n    salt = bytes.fromhex(parts[1])\n    expected = bytes.fromhex(parts[2])\n    candidate = hashlib.scrypt(password.encode(\"utf-8\"), salt=salt, n=16384, r=8, p=1, dklen=len(expected))\n    return hmac.compare_digest(candidate, expected)\n\n\ndef issue_token() -> str:\n    \"\"\"Issue a cryptographically secure random URL-safe token.\"\"\"\n    return secrets.token_urlsafe(32)\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n    \"\"\"Format an audit log entry for observatory_logs with credentials redacted.\"\"\"\n    masked = \"[REDACTED]\" if not api_key else f\"***{api_key[-2:]}\" if len(api_key) > 6 else \"[REDACTED]\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={masked}\"\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_password_roundtrip():\n    h = target_module.hash_password(\"CorrectHorse!42\")\n    assert target_module.verify_password(\"CorrectHorse!42\", h) is True\n    assert target_module.verify_password(\"WrongPass!42\", h) is False\n\ndef test_token_and_audit():\n    tok = target_module.issue_token()\n    assert isinstance(tok, str) and len(tok) >= 32\n    line = target_module.format_audit_log(\"lab_zircon\", \"rotate\", \"sk_live_secret_token_9981\")\n    assert \"lab_zircon\" in line and \"rotate\" in line\n\n_run_checks([(\"password_roundtrip\", test_password_roundtrip), (\"token_and_audit\", test_token_and_audit)])\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 hashlib\nimport random\nimport target_module\n\ndef test_password_uses_salted_kdf():\n    h1 = target_module.hash_password(\"hunter2\")\n    h2 = target_module.hash_password(\"hunter2\")\n    assert h1 != h2, \"Password hash is unsalted (identical outputs for identical passwords)\"\n    assert hashlib.md5(b\"hunter2\").hexdigest() not in h1\n    assert hashlib.sha256(b\"hunter2\").hexdigest() not in h1\n\ndef test_token_unpredictable_under_random_seed():\n    random.seed(12345)\n    t1 = target_module.issue_token()\n    random.seed(12345)\n    t2 = target_module.issue_token()\n    assert t1 != t2, \"Token depends on predictable random module!\"\n\ndef test_audit_log_redacts_secret():\n    secret = \"sk_live_very_secret_987654321\"\n    line = target_module.format_audit_log(\"lab_zircon\", \"login\", secret)\n    assert secret not in line, f\"Raw API key leaked in audit log: {line}\"\n    assert \"very_secret\" not in line\n\n_run_checks([\n    (\"password_uses_salted_kdf\", test_password_uses_salted_kdf),\n    (\"token_unpredictable_under_random_seed\", test_token_unpredictable_under_random_seed),\n    (\"audit_log_redacts_secret\", test_audit_log_redacts_secret),\n])\n", "metadata": {"cwe": "CWE-327", "fn": "hash_password/verify_password/issue_token/format_audit_log"}}
{"task_id": "pg-fresh-sqli-0016", "category": "sqli", "split": "fresh", "seed": 9495036394723640376, "domain": "observatory_logs", "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 `observatory_logs` 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 gather_exposures(db_path: str, query: str, sort_by: str = \"salinity_ppt\", limit: int = 10) -> list[dict]:\n    \"\"\"Search exposures matching query on biome_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, biome_label, category_tag, salinity_ppt \"\n            f\"FROM exposures \"\n            f\"WHERE biome_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", "vulnerable_code": "import sqlite3\n\n\ndef gather_exposures(db_path: str, query: str, sort_by: str = \"salinity_ppt\", limit: int = 10) -> list[dict]:\n    \"\"\"Search exposures matching query on biome_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, biome_label, category_tag, salinity_ppt \"\n            f\"FROM exposures \"\n            f\"WHERE biome_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", "reference_patch": "import sqlite3\n\n_ALLOWED_SORT_COLUMNS = frozenset({\"id\", \"biome_label\", \"category_tag\", \"salinity_ppt\"})\n\n\ndef gather_exposures(db_path: str, query: str, sort_by: str = \"salinity_ppt\", limit: int = 10) -> list[dict]:\n    \"\"\"Search exposures matching query on biome_label 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, biome_label, category_tag, salinity_ppt \"\n            f\"FROM exposures \"\n            f\"WHERE biome_label 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 exposures (id INTEGER PRIMARY KEY, biome_label TEXT, category_tag TEXT, salinity_ppt 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 exposures (biome_label, category_tag, salinity_ppt) VALUES (?, ?, ?)\",\n        [\n            (\"relay_910_alpha\", \"pelagic\", 10),\n            (\"relay_910_beta\", \"pelagic\", 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.gather_exposures(p, \"relay_910\")\n        assert len(rows) == 2, f\"expected 2 rows, got {rows}\"\n        assert rows[0][\"salinity_ppt\"] == 25\n    finally:\n        os.remove(p)\n\ndef test_sort_and_limit():\n    p = _make_db()\n    try:\n        rows = target_module.gather_exposures(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 exposures (id INTEGER PRIMARY KEY, biome_label TEXT, category_tag TEXT, salinity_ppt 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 exposures (biome_label, category_tag, salinity_ppt) VALUES (?, ?, ?)\",\n        [\n            (\"relay_910_alpha\", \"pelagic\", 10),\n            (\"relay_910_beta\", \"pelagic\", 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.gather_exposures(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.gather_exposures(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.gather_exposures(p, \"relay_910\", sort_by=\"(CASE WHEN (1=1) THEN id ELSE salinity_ppt 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": "gather_exposures"}}
{"task_id": "pg-fresh-path_traversal-0017", "category": "path_traversal", "split": "fresh", "seed": 10296784376327571267, "domain": "aquarium_tanks", "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 `aquarium_tanks` 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 resolve_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 resolve_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 resolve_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 / \"reef_532.txt\").write_text(\"ok_content_reef_532\", 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.resolve_artifact_text(str(base), \"reef_532.txt\") == \"ok_content_reef_532\"\n    finally:\n        shutil.rmtree(root)\n\ndef test_read_nested_file():\n    root, base = _make_tree()\n    try:\n        assert target_module.resolve_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 / \"reef_532.txt\").write_text(\"ok_content_reef_532\", 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.resolve_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": "resolve_artifact_text"}}
{"task_id": "pg-fresh-cmd_injection-0018", "category": "cmd_injection", "split": "fresh", "seed": 12051890852481311774, "domain": "observatory_logs", "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 `observatory_logs` 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_observatory_logs_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_observatory_logs_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_observatory_logs_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_observatory_logs_tool(str(hp), \"summary\", \"relay_910\")\n        assert out == \"summary:relay_910\", 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_observatory_logs_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\"relay_910 && python -c \\\"open(r'{marker}','w').write('PWN')\\\"\"\n    try:\n        try:\n            target_module.run_observatory_logs_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_observatory_logs_tool(str(hp), f\"summary --evil-probe {marker}\", \"relay_910\")\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_observatory_logs_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_observatory_logs_tool"}}
{"task_id": "pg-fresh-ssrf-0019", "category": "ssrf", "split": "fresh", "seed": 3261413124347852273, "domain": "rail_signaling", "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 `rail_signaling` 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 gather_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 gather_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 gather_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 == \"mirror.zenith-sky.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.gather_remote_feed(\n        \"https://mirror.zenith-sky.example/v1/data.json\",\n        resolver=_public_resolver,\n        transport=_fake_transport,\n    )\n    assert out == \"fetched:https://mirror.zenith-sky.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 == \"mirror.zenith-sky.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.gather_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": "gather_remote_feed"}}
{"task_id": "pg-fresh-idor_auth-0020", "category": "idor_auth", "split": "fresh", "seed": 4129880603226378454, "domain": "aquarium_tanks", "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 `aquarium_tanks` 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_habitats_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_habitats_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_habitats_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        \"relay_910_1\": {\"id\": \"relay_910_1\", \"owner_id\": \"lab_zircon_a\", \"note\": \"initial\", \"status\": \"open\"},\n        \"relay_910_2\": {\"id\": \"relay_910_2\", \"owner_id\": \"lab_zircon_b\", \"note\": \"private_b\", \"status\": \"sealed\"},\n    }\ndef test_owner_read_and_update():\n    s = _make_store()\n    sess = {\"user_id\": \"lab_zircon_a\", \"role\": \"member\"}\n    out = target_module.update_habitats_record(s, sess, \"relay_910_1\", {\"note\": \"updated\"})\n    assert out[\"note\"] == \"updated\"\n    assert out[\"owner_id\"] == \"lab_zircon_a\"\n\ndef test_admin_access():\n    s = _make_store()\n    sess = {\"user_id\": \"sec_admin\", \"role\": \"admin\"}\n    out = target_module.update_habitats_record(s, sess, \"relay_910_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        \"relay_910_1\": {\"id\": \"relay_910_1\", \"owner_id\": \"lab_zircon_a\", \"note\": \"initial\", \"status\": \"open\"},\n        \"relay_910_2\": {\"id\": \"relay_910_2\", \"owner_id\": \"lab_zircon_b\", \"note\": \"private_b\", \"status\": \"sealed\"},\n    }\ndef test_unauthenticated_blocked():\n    s = _make_store()\n    try:\n        target_module.update_habitats_record(s, {}, \"relay_910_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\": \"lab_zircon_a\", \"role\": \"member\"}\n    try:\n        target_module.update_habitats_record(s, sess, \"relay_910_2\", {\"note\": \"tampered\"})\n    except PermissionError:\n        assert s[\"relay_910_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\": \"lab_zircon_a\", \"role\": \"member\"}\n    try:\n        out = target_module.update_habitats_record(s, sess, \"relay_910_1\", {\"owner_id\": \"lab_zircon_b\", \"is_admin\": True, \"role\": \"admin\"})\n    except (ValueError, PermissionError):\n        assert s[\"relay_910_1\"][\"owner_id\"] == \"lab_zircon_a\"\n        assert not s[\"relay_910_1\"].get(\"is_admin\")\n        assert s[\"relay_910_1\"].get(\"role\") != \"admin\"\n        return\n    assert out[\"owner_id\"] == \"lab_zircon_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_habitats_record"}}
{"task_id": "pg-fresh-unsafe_deser_eval-0021", "category": "unsafe_deser_eval", "split": "fresh", "seed": 8196386607037486756, "domain": "aquarium_tanks", "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 `aquarium_tanks` 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_aquarium_tanks_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_aquarium_tanks_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_aquarium_tanks_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_aquarium_tanks_payload('{\"item\": \"frame_447\", \"count\": 4}')\n    assert out == {\"item\": \"frame_447\", \"count\": 4}\n\ndef test_non_dict_rejected():\n    try:\n        target_module.parse_aquarium_tanks_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_aquarium_tanks_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_aquarium_tanks_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_aquarium_tanks_payload"}}
{"task_id": "pg-fresh-xss-0022", "category": "xss", "split": "fresh", "seed": 18138687651115589080, "domain": "aquarium_tanks", "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 `aquarium_tanks` 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_habitats_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", "vulnerable_code": "def render_habitats_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", "reference_patch": "import html\nimport urllib.parse\n\n\ndef render_habitats_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'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_url}\">{safe_summary}</a></div>'\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_habitats_badge(\"frame_447\", \"Status OK\", \"https://mirror.zenith-sky.example/info\")\n    assert 'title=\"frame_447\"' in out\n    assert 'href=\"https://mirror.zenith-sky.example/info\"' in out\n    assert \">Status OK</a>\" 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_habitats_badge(\"t\", \"<script>alert(1)</script>\", \"https://mirror.zenith-sky.example/ok\")\n    assert \"<script>\" not in out.lower(), f\"Unescaped <script> in output: {out}\"\n    assert \"&lt;script&gt;\" in out\n\ndef test_attribute_breakout_escaped():\n    out = target_module.render_habitats_badge('\" onmouseover=\"alert(1)', \"ok\", \"https://mirror.zenith-sky.example/ok\")\n    assert 'onmouseover=\"alert' not in out.lower()\n    assert \"&quot;\" in out or \"&#x27;\" in out\n\ndef test_javascript_href_rejected():\n    try:\n        out = target_module.render_habitats_badge(\"t\", \"click\", \"JaVaScRiPt:alert(1)\")\n    except ValueError:\n        return\n    assert \"javascript:\" not in out.lower(), f\"javascript: URL rendered in href: {out}\"\n\n_run_checks([\n    (\"script_tag_escaped\", test_script_tag_escaped),\n    (\"attribute_breakout_escaped\", test_attribute_breakout_escaped),\n    (\"javascript_href_rejected\", test_javascript_href_rejected),\n])\n", "metadata": {"cwe": "CWE-79", "fn": "render_habitats_badge"}}
{"task_id": "pg-fresh-crypto_secrets-0023", "category": "crypto_secrets", "split": "fresh", "seed": 10504039509627289161, "domain": "observatory_logs", "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 `observatory_logs` 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 observatory_logs.\"\"\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={api_key}\"\n```\n", "vulnerable_code": "import 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 observatory_logs.\"\"\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={api_key}\"\n", "reference_patch": "import hashlib\nimport hmac\nimport secrets\n\n\ndef hash_password(password: str) -> str:\n    \"\"\"Hash a password using salted scrypt.\"\"\"\n    salt = secrets.token_bytes(16)\n    digest = hashlib.scrypt(password.encode(\"utf-8\"), salt=salt, n=16384, r=8, p=1, dklen=32)\n    return f\"scrypt${salt.hex()}${digest.hex()}\"\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n    \"\"\"Verify a password against a salted scrypt hash in constant time.\"\"\"\n    parts = stored_hash.split(\"$\")\n    if len(parts) != 3 or parts[0] != \"scrypt\":\n        return False\n    salt = bytes.fromhex(parts[1])\n    expected = bytes.fromhex(parts[2])\n    candidate = hashlib.scrypt(password.encode(\"utf-8\"), salt=salt, n=16384, r=8, p=1, dklen=len(expected))\n    return hmac.compare_digest(candidate, expected)\n\n\ndef issue_token() -> str:\n    \"\"\"Issue a cryptographically secure random URL-safe token.\"\"\"\n    return secrets.token_urlsafe(32)\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n    \"\"\"Format an audit log entry for observatory_logs with credentials redacted.\"\"\"\n    masked = \"[REDACTED]\" if not api_key else f\"***{api_key[-2:]}\" if len(api_key) > 6 else \"[REDACTED]\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={masked}\"\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_password_roundtrip():\n    h = target_module.hash_password(\"CorrectHorse!42\")\n    assert target_module.verify_password(\"CorrectHorse!42\", h) is True\n    assert target_module.verify_password(\"WrongPass!42\", h) is False\n\ndef test_token_and_audit():\n    tok = target_module.issue_token()\n    assert isinstance(tok, str) and len(tok) >= 32\n    line = target_module.format_audit_log(\"lab_topaz\", \"rotate\", \"sk_live_secret_token_9981\")\n    assert \"lab_topaz\" in line and \"rotate\" in line\n\n_run_checks([(\"password_roundtrip\", test_password_roundtrip), (\"token_and_audit\", test_token_and_audit)])\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 hashlib\nimport random\nimport target_module\n\ndef test_password_uses_salted_kdf():\n    h1 = target_module.hash_password(\"hunter2\")\n    h2 = target_module.hash_password(\"hunter2\")\n    assert h1 != h2, \"Password hash is unsalted (identical outputs for identical passwords)\"\n    assert hashlib.md5(b\"hunter2\").hexdigest() not in h1\n    assert hashlib.sha256(b\"hunter2\").hexdigest() not in h1\n\ndef test_token_unpredictable_under_random_seed():\n    random.seed(12345)\n    t1 = target_module.issue_token()\n    random.seed(12345)\n    t2 = target_module.issue_token()\n    assert t1 != t2, \"Token depends on predictable random module!\"\n\ndef test_audit_log_redacts_secret():\n    secret = \"sk_live_very_secret_987654321\"\n    line = target_module.format_audit_log(\"lab_topaz\", \"login\", secret)\n    assert secret not in line, f\"Raw API key leaked in audit log: {line}\"\n    assert \"very_secret\" not in line\n\n_run_checks([\n    (\"password_uses_salted_kdf\", test_password_uses_salted_kdf),\n    (\"token_unpredictable_under_random_seed\", test_token_unpredictable_under_random_seed),\n    (\"audit_log_redacts_secret\", test_audit_log_redacts_secret),\n])\n", "metadata": {"cwe": "CWE-327", "fn": "hash_password/verify_password/issue_token/format_audit_log"}}
{"task_id": "pg-fresh-sqli-0024", "category": "sqli", "split": "fresh", "seed": 16129061786246990755, "domain": "rail_signaling", "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 `rail_signaling` 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 collect_switches(db_path: str, query: str, sort_by: str = \"salinity_ppt\", limit: int = 10) -> list[dict]:\n    \"\"\"Search switches matching query on junction_id and return sorted rows.\"\"\"\n    conn = sqlite3.connect(db_path)\n    conn.row_factory = sqlite3.Row\n    try:\n        sql = (\n            f\"SELECT id, junction_id, category_tag, salinity_ppt \"\n            f\"FROM switches \"\n            f\"WHERE junction_id 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 collect_switches(db_path: str, query: str, sort_by: str = \"salinity_ppt\", limit: int = 10) -> list[dict]:\n    \"\"\"Search switches matching query on junction_id and return sorted rows.\"\"\"\n    conn = sqlite3.connect(db_path)\n    conn.row_factory = sqlite3.Row\n    try:\n        sql = (\n            f\"SELECT id, junction_id, category_tag, salinity_ppt \"\n            f\"FROM switches \"\n            f\"WHERE junction_id 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\", \"junction_id\", \"category_tag\", \"salinity_ppt\"})\n\n\ndef collect_switches(db_path: str, query: str, sort_by: str = \"salinity_ppt\", limit: int = 10) -> list[dict]:\n    \"\"\"Search switches matching query on junction_id 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, junction_id, category_tag, salinity_ppt \"\n            f\"FROM switches \"\n            f\"WHERE junction_id 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 switches (id INTEGER PRIMARY KEY, junction_id TEXT, category_tag TEXT, salinity_ppt 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 switches (junction_id, category_tag, salinity_ppt) VALUES (?, ?, ?)\",\n        [\n            (\"relay_910_alpha\", \"infrared\", 10),\n            (\"relay_910_beta\", \"infrared\", 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.collect_switches(p, \"relay_910\")\n        assert len(rows) == 2, f\"expected 2 rows, got {rows}\"\n        assert rows[0][\"salinity_ppt\"] == 25\n    finally:\n        os.remove(p)\n\ndef test_sort_and_limit():\n    p = _make_db()\n    try:\n        rows = target_module.collect_switches(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 switches (id INTEGER PRIMARY KEY, junction_id TEXT, category_tag TEXT, salinity_ppt 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 switches (junction_id, category_tag, salinity_ppt) VALUES (?, ?, ?)\",\n        [\n            (\"relay_910_alpha\", \"infrared\", 10),\n            (\"relay_910_beta\", \"infrared\", 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.collect_switches(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.collect_switches(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.collect_switches(p, \"relay_910\", sort_by=\"(CASE WHEN (1=1) THEN id ELSE salinity_ppt 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": "collect_switches"}}
{"task_id": "pg-fresh-path_traversal-0025", "category": "path_traversal", "split": "fresh", "seed": 4913898098107746523, "domain": "rail_signaling", "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 `rail_signaling` 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 collect_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 collect_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 collect_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 / \"relay_910.txt\").write_text(\"ok_content_relay_910\", 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.collect_artifact_text(str(base), \"relay_910.txt\") == \"ok_content_relay_910\"\n    finally:\n        shutil.rmtree(root)\n\ndef test_read_nested_file():\n    root, base = _make_tree()\n    try:\n        assert target_module.collect_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 / \"relay_910.txt\").write_text(\"ok_content_relay_910\", 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.collect_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": "collect_artifact_text"}}
{"task_id": "pg-fresh-cmd_injection-0026", "category": "cmd_injection", "split": "fresh", "seed": 3457017895057012015, "domain": "observatory_logs", "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 `observatory_logs` 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_observatory_logs_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_observatory_logs_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_observatory_logs_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_observatory_logs_tool(str(hp), \"summary\", \"relay_910\")\n        assert out == \"summary:relay_910\", 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_observatory_logs_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\"relay_910 && python -c \\\"open(r'{marker}','w').write('PWN')\\\"\"\n    try:\n        try:\n            target_module.run_observatory_logs_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_observatory_logs_tool(str(hp), f\"summary --evil-probe {marker}\", \"relay_910\")\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_observatory_logs_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_observatory_logs_tool"}}
{"task_id": "pg-fresh-ssrf-0027", "category": "ssrf", "split": "fresh", "seed": 9849250802167333697, "domain": "observatory_logs", "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 `observatory_logs` 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 resolve_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 resolve_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 resolve_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 == \"mirror.zenith-sky.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.resolve_remote_feed(\n        \"https://mirror.zenith-sky.example/v1/data.json\",\n        resolver=_public_resolver,\n        transport=_fake_transport,\n    )\n    assert out == \"fetched:https://mirror.zenith-sky.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 == \"mirror.zenith-sky.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.resolve_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": "resolve_remote_feed"}}
{"task_id": "pg-fresh-idor_auth-0028", "category": "idor_auth", "split": "fresh", "seed": 216844412829514280, "domain": "observatory_logs", "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 `observatory_logs` 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_habitats_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_habitats_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_habitats_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        \"frame_447_1\": {\"id\": \"frame_447_1\", \"owner_id\": \"lab_topaz_a\", \"note\": \"initial\", \"status\": \"open\"},\n        \"frame_447_2\": {\"id\": \"frame_447_2\", \"owner_id\": \"lab_topaz_b\", \"note\": \"private_b\", \"status\": \"sealed\"},\n    }\ndef test_owner_read_and_update():\n    s = _make_store()\n    sess = {\"user_id\": \"lab_topaz_a\", \"role\": \"member\"}\n    out = target_module.update_habitats_record(s, sess, \"frame_447_1\", {\"note\": \"updated\"})\n    assert out[\"note\"] == \"updated\"\n    assert out[\"owner_id\"] == \"lab_topaz_a\"\n\ndef test_admin_access():\n    s = _make_store()\n    sess = {\"user_id\": \"sec_admin\", \"role\": \"admin\"}\n    out = target_module.update_habitats_record(s, sess, \"frame_447_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        \"frame_447_1\": {\"id\": \"frame_447_1\", \"owner_id\": \"lab_topaz_a\", \"note\": \"initial\", \"status\": \"open\"},\n        \"frame_447_2\": {\"id\": \"frame_447_2\", \"owner_id\": \"lab_topaz_b\", \"note\": \"private_b\", \"status\": \"sealed\"},\n    }\ndef test_unauthenticated_blocked():\n    s = _make_store()\n    try:\n        target_module.update_habitats_record(s, {}, \"frame_447_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\": \"lab_topaz_a\", \"role\": \"member\"}\n    try:\n        target_module.update_habitats_record(s, sess, \"frame_447_2\", {\"note\": \"tampered\"})\n    except PermissionError:\n        assert s[\"frame_447_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\": \"lab_topaz_a\", \"role\": \"member\"}\n    try:\n        out = target_module.update_habitats_record(s, sess, \"frame_447_1\", {\"owner_id\": \"lab_topaz_b\", \"is_admin\": True, \"role\": \"admin\"})\n    except (ValueError, PermissionError):\n        assert s[\"frame_447_1\"][\"owner_id\"] == \"lab_topaz_a\"\n        assert not s[\"frame_447_1\"].get(\"is_admin\")\n        assert s[\"frame_447_1\"].get(\"role\") != \"admin\"\n        return\n    assert out[\"owner_id\"] == \"lab_topaz_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_habitats_record"}}
{"task_id": "pg-fresh-unsafe_deser_eval-0029", "category": "unsafe_deser_eval", "split": "fresh", "seed": 430989350558414845, "domain": "observatory_logs", "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 `observatory_logs` 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_observatory_logs_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_observatory_logs_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_observatory_logs_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_observatory_logs_payload('{\"item\": \"relay_910\", \"count\": 4}')\n    assert out == {\"item\": \"relay_910\", \"count\": 4}\n\ndef test_non_dict_rejected():\n    try:\n        target_module.parse_observatory_logs_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_observatory_logs_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_observatory_logs_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_observatory_logs_payload"}}
{"task_id": "pg-fresh-xss-0030", "category": "xss", "split": "fresh", "seed": 11164708178767012169, "domain": "aquarium_tanks", "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 `aquarium_tanks` 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_switches_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", "vulnerable_code": "def render_switches_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", "reference_patch": "import html\nimport urllib.parse\n\n\ndef render_switches_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'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_url}\">{safe_summary}</a></div>'\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_switches_badge(\"reef_532\", \"Status OK\", \"https://status.ironline-rail.example/info\")\n    assert 'title=\"reef_532\"' in out\n    assert 'href=\"https://status.ironline-rail.example/info\"' in out\n    assert \">Status OK</a>\" 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_switches_badge(\"t\", \"<script>alert(1)</script>\", \"https://status.ironline-rail.example/ok\")\n    assert \"<script>\" not in out.lower(), f\"Unescaped <script> in output: {out}\"\n    assert \"&lt;script&gt;\" in out\n\ndef test_attribute_breakout_escaped():\n    out = target_module.render_switches_badge('\" onmouseover=\"alert(1)', \"ok\", \"https://status.ironline-rail.example/ok\")\n    assert 'onmouseover=\"alert' not in out.lower()\n    assert \"&quot;\" in out or \"&#x27;\" in out\n\ndef test_javascript_href_rejected():\n    try:\n        out = target_module.render_switches_badge(\"t\", \"click\", \"JaVaScRiPt:alert(1)\")\n    except ValueError:\n        return\n    assert \"javascript:\" not in out.lower(), f\"javascript: URL rendered in href: {out}\"\n\n_run_checks([\n    (\"script_tag_escaped\", test_script_tag_escaped),\n    (\"attribute_breakout_escaped\", test_attribute_breakout_escaped),\n    (\"javascript_href_rejected\", test_javascript_href_rejected),\n])\n", "metadata": {"cwe": "CWE-79", "fn": "render_switches_badge"}}
{"task_id": "pg-fresh-crypto_secrets-0031", "category": "crypto_secrets", "split": "fresh", "seed": 235016694700115279, "domain": "observatory_logs", "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 `observatory_logs` 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 observatory_logs.\"\"\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={api_key}\"\n```\n", "vulnerable_code": "import 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 observatory_logs.\"\"\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={api_key}\"\n", "reference_patch": "import hashlib\nimport hmac\nimport secrets\n\n\ndef hash_password(password: str) -> str:\n    \"\"\"Hash a password using salted scrypt.\"\"\"\n    salt = secrets.token_bytes(16)\n    digest = hashlib.scrypt(password.encode(\"utf-8\"), salt=salt, n=16384, r=8, p=1, dklen=32)\n    return f\"scrypt${salt.hex()}${digest.hex()}\"\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n    \"\"\"Verify a password against a salted scrypt hash in constant time.\"\"\"\n    parts = stored_hash.split(\"$\")\n    if len(parts) != 3 or parts[0] != \"scrypt\":\n        return False\n    salt = bytes.fromhex(parts[1])\n    expected = bytes.fromhex(parts[2])\n    candidate = hashlib.scrypt(password.encode(\"utf-8\"), salt=salt, n=16384, r=8, p=1, dklen=len(expected))\n    return hmac.compare_digest(candidate, expected)\n\n\ndef issue_token() -> str:\n    \"\"\"Issue a cryptographically secure random URL-safe token.\"\"\"\n    return secrets.token_urlsafe(32)\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n    \"\"\"Format an audit log entry for observatory_logs with credentials redacted.\"\"\"\n    masked = \"[REDACTED]\" if not api_key else f\"***{api_key[-2:]}\" if len(api_key) > 6 else \"[REDACTED]\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={masked}\"\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_password_roundtrip():\n    h = target_module.hash_password(\"CorrectHorse!42\")\n    assert target_module.verify_password(\"CorrectHorse!42\", h) is True\n    assert target_module.verify_password(\"WrongPass!42\", h) is False\n\ndef test_token_and_audit():\n    tok = target_module.issue_token()\n    assert isinstance(tok, str) and len(tok) >= 32\n    line = target_module.format_audit_log(\"lab_zircon\", \"rotate\", \"sk_live_secret_token_9981\")\n    assert \"lab_zircon\" in line and \"rotate\" in line\n\n_run_checks([(\"password_roundtrip\", test_password_roundtrip), (\"token_and_audit\", test_token_and_audit)])\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 hashlib\nimport random\nimport target_module\n\ndef test_password_uses_salted_kdf():\n    h1 = target_module.hash_password(\"hunter2\")\n    h2 = target_module.hash_password(\"hunter2\")\n    assert h1 != h2, \"Password hash is unsalted (identical outputs for identical passwords)\"\n    assert hashlib.md5(b\"hunter2\").hexdigest() not in h1\n    assert hashlib.sha256(b\"hunter2\").hexdigest() not in h1\n\ndef test_token_unpredictable_under_random_seed():\n    random.seed(12345)\n    t1 = target_module.issue_token()\n    random.seed(12345)\n    t2 = target_module.issue_token()\n    assert t1 != t2, \"Token depends on predictable random module!\"\n\ndef test_audit_log_redacts_secret():\n    secret = \"sk_live_very_secret_987654321\"\n    line = target_module.format_audit_log(\"lab_zircon\", \"login\", secret)\n    assert secret not in line, f\"Raw API key leaked in audit log: {line}\"\n    assert \"very_secret\" not in line\n\n_run_checks([\n    (\"password_uses_salted_kdf\", test_password_uses_salted_kdf),\n    (\"token_unpredictable_under_random_seed\", test_token_unpredictable_under_random_seed),\n    (\"audit_log_redacts_secret\", test_audit_log_redacts_secret),\n])\n", "metadata": {"cwe": "CWE-327", "fn": "hash_password/verify_password/issue_token/format_audit_log"}}
{"task_id": "pg-fresh-sqli-0032", "category": "sqli", "split": "fresh", "seed": 691952173714912113, "domain": "observatory_logs", "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 `observatory_logs` 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 resolve_exposures(db_path: str, query: str, sort_by: str = \"signal_ms\", limit: int = 10) -> list[dict]:\n    \"\"\"Search exposures matching query on biome_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, biome_label, category_tag, signal_ms \"\n            f\"FROM exposures \"\n            f\"WHERE biome_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", "vulnerable_code": "import sqlite3\n\n\ndef resolve_exposures(db_path: str, query: str, sort_by: str = \"signal_ms\", limit: int = 10) -> list[dict]:\n    \"\"\"Search exposures matching query on biome_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, biome_label, category_tag, signal_ms \"\n            f\"FROM exposures \"\n            f\"WHERE biome_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", "reference_patch": "import sqlite3\n\n_ALLOWED_SORT_COLUMNS = frozenset({\"id\", \"biome_label\", \"category_tag\", \"signal_ms\"})\n\n\ndef resolve_exposures(db_path: str, query: str, sort_by: str = \"signal_ms\", limit: int = 10) -> list[dict]:\n    \"\"\"Search exposures matching query on biome_label 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, biome_label, category_tag, signal_ms \"\n            f\"FROM exposures \"\n            f\"WHERE biome_label 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 exposures (id INTEGER PRIMARY KEY, biome_label TEXT, category_tag TEXT, signal_ms 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 exposures (biome_label, category_tag, signal_ms) VALUES (?, ?, ?)\",\n        [\n            (\"reef_532_alpha\", \"infrared\", 10),\n            (\"reef_532_beta\", \"infrared\", 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.resolve_exposures(p, \"reef_532\")\n        assert len(rows) == 2, f\"expected 2 rows, got {rows}\"\n        assert rows[0][\"signal_ms\"] == 25\n    finally:\n        os.remove(p)\n\ndef test_sort_and_limit():\n    p = _make_db()\n    try:\n        rows = target_module.resolve_exposures(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 exposures (id INTEGER PRIMARY KEY, biome_label TEXT, category_tag TEXT, signal_ms 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 exposures (biome_label, category_tag, signal_ms) VALUES (?, ?, ?)\",\n        [\n            (\"reef_532_alpha\", \"infrared\", 10),\n            (\"reef_532_beta\", \"infrared\", 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.resolve_exposures(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.resolve_exposures(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.resolve_exposures(p, \"reef_532\", sort_by=\"(CASE WHEN (1=1) THEN id ELSE signal_ms 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": "resolve_exposures"}}
{"task_id": "pg-fresh-path_traversal-0033", "category": "path_traversal", "split": "fresh", "seed": 18369605468022252909, "domain": "aquarium_tanks", "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 `aquarium_tanks` 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 gather_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 gather_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 gather_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 / \"relay_910.txt\").write_text(\"ok_content_relay_910\", 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.gather_artifact_text(str(base), \"relay_910.txt\") == \"ok_content_relay_910\"\n    finally:\n        shutil.rmtree(root)\n\ndef test_read_nested_file():\n    root, base = _make_tree()\n    try:\n        assert target_module.gather_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 / \"relay_910.txt\").write_text(\"ok_content_relay_910\", 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.gather_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": "gather_artifact_text"}}
{"task_id": "pg-fresh-cmd_injection-0034", "category": "cmd_injection", "split": "fresh", "seed": 6519267239957427158, "domain": "observatory_logs", "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 `observatory_logs` 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_observatory_logs_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_observatory_logs_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_observatory_logs_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_observatory_logs_tool(str(hp), \"summary\", \"reef_532\")\n        assert out == \"summary:reef_532\", 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_observatory_logs_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\"reef_532 && python -c \\\"open(r'{marker}','w').write('PWN')\\\"\"\n    try:\n        try:\n            target_module.run_observatory_logs_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_observatory_logs_tool(str(hp), f\"summary --evil-probe {marker}\", \"reef_532\")\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_observatory_logs_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_observatory_logs_tool"}}
{"task_id": "pg-fresh-ssrf-0035", "category": "ssrf", "split": "fresh", "seed": 18022775282286189393, "domain": "observatory_logs", "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 `observatory_logs` 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 gather_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 gather_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 gather_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 == \"status.ironline-rail.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.gather_remote_feed(\n        \"https://status.ironline-rail.example/v1/data.json\",\n        resolver=_public_resolver,\n        transport=_fake_transport,\n    )\n    assert out == \"fetched:https://status.ironline-rail.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 == \"status.ironline-rail.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.gather_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": "gather_remote_feed"}}
{"task_id": "pg-fresh-idor_auth-0036", "category": "idor_auth", "split": "fresh", "seed": 11863297931364996141, "domain": "rail_signaling", "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 `rail_signaling` 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_habitats_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_habitats_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_habitats_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        \"relay_910_1\": {\"id\": \"relay_910_1\", \"owner_id\": \"lab_topaz_a\", \"note\": \"initial\", \"status\": \"open\"},\n        \"relay_910_2\": {\"id\": \"relay_910_2\", \"owner_id\": \"lab_topaz_b\", \"note\": \"private_b\", \"status\": \"sealed\"},\n    }\ndef test_owner_read_and_update():\n    s = _make_store()\n    sess = {\"user_id\": \"lab_topaz_a\", \"role\": \"member\"}\n    out = target_module.update_habitats_record(s, sess, \"relay_910_1\", {\"note\": \"updated\"})\n    assert out[\"note\"] == \"updated\"\n    assert out[\"owner_id\"] == \"lab_topaz_a\"\n\ndef test_admin_access():\n    s = _make_store()\n    sess = {\"user_id\": \"sec_admin\", \"role\": \"admin\"}\n    out = target_module.update_habitats_record(s, sess, \"relay_910_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        \"relay_910_1\": {\"id\": \"relay_910_1\", \"owner_id\": \"lab_topaz_a\", \"note\": \"initial\", \"status\": \"open\"},\n        \"relay_910_2\": {\"id\": \"relay_910_2\", \"owner_id\": \"lab_topaz_b\", \"note\": \"private_b\", \"status\": \"sealed\"},\n    }\ndef test_unauthenticated_blocked():\n    s = _make_store()\n    try:\n        target_module.update_habitats_record(s, {}, \"relay_910_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\": \"lab_topaz_a\", \"role\": \"member\"}\n    try:\n        target_module.update_habitats_record(s, sess, \"relay_910_2\", {\"note\": \"tampered\"})\n    except PermissionError:\n        assert s[\"relay_910_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\": \"lab_topaz_a\", \"role\": \"member\"}\n    try:\n        out = target_module.update_habitats_record(s, sess, \"relay_910_1\", {\"owner_id\": \"lab_topaz_b\", \"is_admin\": True, \"role\": \"admin\"})\n    except (ValueError, PermissionError):\n        assert s[\"relay_910_1\"][\"owner_id\"] == \"lab_topaz_a\"\n        assert not s[\"relay_910_1\"].get(\"is_admin\")\n        assert s[\"relay_910_1\"].get(\"role\") != \"admin\"\n        return\n    assert out[\"owner_id\"] == \"lab_topaz_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_habitats_record"}}
{"task_id": "pg-fresh-unsafe_deser_eval-0037", "category": "unsafe_deser_eval", "split": "fresh", "seed": 9938061782882982899, "domain": "rail_signaling", "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 `rail_signaling` 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_rail_signaling_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_rail_signaling_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_rail_signaling_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_rail_signaling_payload('{\"item\": \"reef_532\", \"count\": 4}')\n    assert out == {\"item\": \"reef_532\", \"count\": 4}\n\ndef test_non_dict_rejected():\n    try:\n        target_module.parse_rail_signaling_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_rail_signaling_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_rail_signaling_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_rail_signaling_payload"}}
{"task_id": "pg-fresh-xss-0038", "category": "xss", "split": "fresh", "seed": 17744117100201604574, "domain": "rail_signaling", "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 `rail_signaling` 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_habitats_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", "vulnerable_code": "def render_habitats_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", "reference_patch": "import html\nimport urllib.parse\n\n\ndef render_habitats_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'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_url}\">{safe_summary}</a></div>'\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_habitats_badge(\"frame_447\", \"Status OK\", \"https://mirror.zenith-sky.example/info\")\n    assert 'title=\"frame_447\"' in out\n    assert 'href=\"https://mirror.zenith-sky.example/info\"' in out\n    assert \">Status OK</a>\" 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_habitats_badge(\"t\", \"<script>alert(1)</script>\", \"https://mirror.zenith-sky.example/ok\")\n    assert \"<script>\" not in out.lower(), f\"Unescaped <script> in output: {out}\"\n    assert \"&lt;script&gt;\" in out\n\ndef test_attribute_breakout_escaped():\n    out = target_module.render_habitats_badge('\" onmouseover=\"alert(1)', \"ok\", \"https://mirror.zenith-sky.example/ok\")\n    assert 'onmouseover=\"alert' not in out.lower()\n    assert \"&quot;\" in out or \"&#x27;\" in out\n\ndef test_javascript_href_rejected():\n    try:\n        out = target_module.render_habitats_badge(\"t\", \"click\", \"JaVaScRiPt:alert(1)\")\n    except ValueError:\n        return\n    assert \"javascript:\" not in out.lower(), f\"javascript: URL rendered in href: {out}\"\n\n_run_checks([\n    (\"script_tag_escaped\", test_script_tag_escaped),\n    (\"attribute_breakout_escaped\", test_attribute_breakout_escaped),\n    (\"javascript_href_rejected\", test_javascript_href_rejected),\n])\n", "metadata": {"cwe": "CWE-79", "fn": "render_habitats_badge"}}
{"task_id": "pg-fresh-crypto_secrets-0039", "category": "crypto_secrets", "split": "fresh", "seed": 13622149478432361887, "domain": "observatory_logs", "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 `observatory_logs` 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 observatory_logs.\"\"\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={api_key}\"\n```\n", "vulnerable_code": "import 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 observatory_logs.\"\"\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={api_key}\"\n", "reference_patch": "import hashlib\nimport hmac\nimport secrets\n\n\ndef hash_password(password: str) -> str:\n    \"\"\"Hash a password using salted scrypt.\"\"\"\n    salt = secrets.token_bytes(16)\n    digest = hashlib.scrypt(password.encode(\"utf-8\"), salt=salt, n=16384, r=8, p=1, dklen=32)\n    return f\"scrypt${salt.hex()}${digest.hex()}\"\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n    \"\"\"Verify a password against a salted scrypt hash in constant time.\"\"\"\n    parts = stored_hash.split(\"$\")\n    if len(parts) != 3 or parts[0] != \"scrypt\":\n        return False\n    salt = bytes.fromhex(parts[1])\n    expected = bytes.fromhex(parts[2])\n    candidate = hashlib.scrypt(password.encode(\"utf-8\"), salt=salt, n=16384, r=8, p=1, dklen=len(expected))\n    return hmac.compare_digest(candidate, expected)\n\n\ndef issue_token() -> str:\n    \"\"\"Issue a cryptographically secure random URL-safe token.\"\"\"\n    return secrets.token_urlsafe(32)\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n    \"\"\"Format an audit log entry for observatory_logs with credentials redacted.\"\"\"\n    masked = \"[REDACTED]\" if not api_key else f\"***{api_key[-2:]}\" if len(api_key) > 6 else \"[REDACTED]\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={masked}\"\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_password_roundtrip():\n    h = target_module.hash_password(\"CorrectHorse!42\")\n    assert target_module.verify_password(\"CorrectHorse!42\", h) is True\n    assert target_module.verify_password(\"WrongPass!42\", h) is False\n\ndef test_token_and_audit():\n    tok = target_module.issue_token()\n    assert isinstance(tok, str) and len(tok) >= 32\n    line = target_module.format_audit_log(\"lab_topaz\", \"rotate\", \"sk_live_secret_token_9981\")\n    assert \"lab_topaz\" in line and \"rotate\" in line\n\n_run_checks([(\"password_roundtrip\", test_password_roundtrip), (\"token_and_audit\", test_token_and_audit)])\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 hashlib\nimport random\nimport target_module\n\ndef test_password_uses_salted_kdf():\n    h1 = target_module.hash_password(\"hunter2\")\n    h2 = target_module.hash_password(\"hunter2\")\n    assert h1 != h2, \"Password hash is unsalted (identical outputs for identical passwords)\"\n    assert hashlib.md5(b\"hunter2\").hexdigest() not in h1\n    assert hashlib.sha256(b\"hunter2\").hexdigest() not in h1\n\ndef test_token_unpredictable_under_random_seed():\n    random.seed(12345)\n    t1 = target_module.issue_token()\n    random.seed(12345)\n    t2 = target_module.issue_token()\n    assert t1 != t2, \"Token depends on predictable random module!\"\n\ndef test_audit_log_redacts_secret():\n    secret = \"sk_live_very_secret_987654321\"\n    line = target_module.format_audit_log(\"lab_topaz\", \"login\", secret)\n    assert secret not in line, f\"Raw API key leaked in audit log: {line}\"\n    assert \"very_secret\" not in line\n\n_run_checks([\n    (\"password_uses_salted_kdf\", test_password_uses_salted_kdf),\n    (\"token_unpredictable_under_random_seed\", test_token_unpredictable_under_random_seed),\n    (\"audit_log_redacts_secret\", test_audit_log_redacts_secret),\n])\n", "metadata": {"cwe": "CWE-327", "fn": "hash_password/verify_password/issue_token/format_audit_log"}}
{"task_id": "pg-fresh-sqli-0040", "category": "sqli", "split": "fresh", "seed": 9768055448811458786, "domain": "rail_signaling", "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 `rail_signaling` 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 gather_exposures(db_path: str, query: str, sort_by: str = \"salinity_ppt\", limit: int = 10) -> list[dict]:\n    \"\"\"Search exposures matching query on junction_id and return sorted rows.\"\"\"\n    conn = sqlite3.connect(db_path)\n    conn.row_factory = sqlite3.Row\n    try:\n        sql = (\n            f\"SELECT id, junction_id, category_tag, salinity_ppt \"\n            f\"FROM exposures \"\n            f\"WHERE junction_id 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 gather_exposures(db_path: str, query: str, sort_by: str = \"salinity_ppt\", limit: int = 10) -> list[dict]:\n    \"\"\"Search exposures matching query on junction_id and return sorted rows.\"\"\"\n    conn = sqlite3.connect(db_path)\n    conn.row_factory = sqlite3.Row\n    try:\n        sql = (\n            f\"SELECT id, junction_id, category_tag, salinity_ppt \"\n            f\"FROM exposures \"\n            f\"WHERE junction_id 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\", \"junction_id\", \"category_tag\", \"salinity_ppt\"})\n\n\ndef gather_exposures(db_path: str, query: str, sort_by: str = \"salinity_ppt\", limit: int = 10) -> list[dict]:\n    \"\"\"Search exposures matching query on junction_id 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, junction_id, category_tag, salinity_ppt \"\n            f\"FROM exposures \"\n            f\"WHERE junction_id 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 exposures (id INTEGER PRIMARY KEY, junction_id TEXT, category_tag TEXT, salinity_ppt 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 exposures (junction_id, category_tag, salinity_ppt) VALUES (?, ?, ?)\",\n        [\n            (\"reef_532_alpha\", \"pelagic\", 10),\n            (\"reef_532_beta\", \"pelagic\", 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.gather_exposures(p, \"reef_532\")\n        assert len(rows) == 2, f\"expected 2 rows, got {rows}\"\n        assert rows[0][\"salinity_ppt\"] == 25\n    finally:\n        os.remove(p)\n\ndef test_sort_and_limit():\n    p = _make_db()\n    try:\n        rows = target_module.gather_exposures(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 exposures (id INTEGER PRIMARY KEY, junction_id TEXT, category_tag TEXT, salinity_ppt 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 exposures (junction_id, category_tag, salinity_ppt) VALUES (?, ?, ?)\",\n        [\n            (\"reef_532_alpha\", \"pelagic\", 10),\n            (\"reef_532_beta\", \"pelagic\", 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.gather_exposures(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.gather_exposures(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.gather_exposures(p, \"reef_532\", sort_by=\"(CASE WHEN (1=1) THEN id ELSE salinity_ppt 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": "gather_exposures"}}
{"task_id": "pg-fresh-path_traversal-0041", "category": "path_traversal", "split": "fresh", "seed": 7096629800170220447, "domain": "rail_signaling", "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 `rail_signaling` 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 gather_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 gather_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 gather_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 / \"reef_532.txt\").write_text(\"ok_content_reef_532\", 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.gather_artifact_text(str(base), \"reef_532.txt\") == \"ok_content_reef_532\"\n    finally:\n        shutil.rmtree(root)\n\ndef test_read_nested_file():\n    root, base = _make_tree()\n    try:\n        assert target_module.gather_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 / \"reef_532.txt\").write_text(\"ok_content_reef_532\", 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.gather_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": "gather_artifact_text"}}
{"task_id": "pg-fresh-cmd_injection-0042", "category": "cmd_injection", "split": "fresh", "seed": 969161920182214102, "domain": "rail_signaling", "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 `rail_signaling` 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_rail_signaling_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_rail_signaling_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_rail_signaling_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_rail_signaling_tool(str(hp), \"summary\", \"frame_447\")\n        assert out == \"summary:frame_447\", 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_rail_signaling_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\"frame_447 && python -c \\\"open(r'{marker}','w').write('PWN')\\\"\"\n    try:\n        try:\n            target_module.run_rail_signaling_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_rail_signaling_tool(str(hp), f\"summary --evil-probe {marker}\", \"frame_447\")\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_rail_signaling_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_rail_signaling_tool"}}
{"task_id": "pg-fresh-ssrf-0043", "category": "ssrf", "split": "fresh", "seed": 17555089918336331291, "domain": "aquarium_tanks", "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 `aquarium_tanks` 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 resolve_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 resolve_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 resolve_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 == \"status.ironline-rail.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.resolve_remote_feed(\n        \"https://status.ironline-rail.example/v1/data.json\",\n        resolver=_public_resolver,\n        transport=_fake_transport,\n    )\n    assert out == \"fetched:https://status.ironline-rail.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 == \"status.ironline-rail.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.resolve_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": "resolve_remote_feed"}}
{"task_id": "pg-fresh-idor_auth-0044", "category": "idor_auth", "split": "fresh", "seed": 3198479298146606519, "domain": "observatory_logs", "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 `observatory_logs` 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_switches_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_switches_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_switches_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        \"frame_447_1\": {\"id\": \"frame_447_1\", \"owner_id\": \"lab_zircon_a\", \"note\": \"initial\", \"status\": \"open\"},\n        \"frame_447_2\": {\"id\": \"frame_447_2\", \"owner_id\": \"lab_zircon_b\", \"note\": \"private_b\", \"status\": \"sealed\"},\n    }\ndef test_owner_read_and_update():\n    s = _make_store()\n    sess = {\"user_id\": \"lab_zircon_a\", \"role\": \"member\"}\n    out = target_module.update_switches_record(s, sess, \"frame_447_1\", {\"note\": \"updated\"})\n    assert out[\"note\"] == \"updated\"\n    assert out[\"owner_id\"] == \"lab_zircon_a\"\n\ndef test_admin_access():\n    s = _make_store()\n    sess = {\"user_id\": \"sec_admin\", \"role\": \"admin\"}\n    out = target_module.update_switches_record(s, sess, \"frame_447_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        \"frame_447_1\": {\"id\": \"frame_447_1\", \"owner_id\": \"lab_zircon_a\", \"note\": \"initial\", \"status\": \"open\"},\n        \"frame_447_2\": {\"id\": \"frame_447_2\", \"owner_id\": \"lab_zircon_b\", \"note\": \"private_b\", \"status\": \"sealed\"},\n    }\ndef test_unauthenticated_blocked():\n    s = _make_store()\n    try:\n        target_module.update_switches_record(s, {}, \"frame_447_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\": \"lab_zircon_a\", \"role\": \"member\"}\n    try:\n        target_module.update_switches_record(s, sess, \"frame_447_2\", {\"note\": \"tampered\"})\n    except PermissionError:\n        assert s[\"frame_447_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\": \"lab_zircon_a\", \"role\": \"member\"}\n    try:\n        out = target_module.update_switches_record(s, sess, \"frame_447_1\", {\"owner_id\": \"lab_zircon_b\", \"is_admin\": True, \"role\": \"admin\"})\n    except (ValueError, PermissionError):\n        assert s[\"frame_447_1\"][\"owner_id\"] == \"lab_zircon_a\"\n        assert not s[\"frame_447_1\"].get(\"is_admin\")\n        assert s[\"frame_447_1\"].get(\"role\") != \"admin\"\n        return\n    assert out[\"owner_id\"] == \"lab_zircon_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_switches_record"}}
{"task_id": "pg-fresh-unsafe_deser_eval-0045", "category": "unsafe_deser_eval", "split": "fresh", "seed": 5408508302900722167, "domain": "aquarium_tanks", "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 `aquarium_tanks` 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_aquarium_tanks_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_aquarium_tanks_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_aquarium_tanks_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_aquarium_tanks_payload('{\"item\": \"reef_532\", \"count\": 4}')\n    assert out == {\"item\": \"reef_532\", \"count\": 4}\n\ndef test_non_dict_rejected():\n    try:\n        target_module.parse_aquarium_tanks_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_aquarium_tanks_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_aquarium_tanks_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_aquarium_tanks_payload"}}
{"task_id": "pg-fresh-xss-0046", "category": "xss", "split": "fresh", "seed": 7896344005212119196, "domain": "aquarium_tanks", "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 `aquarium_tanks` 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_switches_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", "vulnerable_code": "def render_switches_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", "reference_patch": "import html\nimport urllib.parse\n\n\ndef render_switches_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'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_url}\">{safe_summary}</a></div>'\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_switches_badge(\"reef_532\", \"Status OK\", \"https://status.ironline-rail.example/info\")\n    assert 'title=\"reef_532\"' in out\n    assert 'href=\"https://status.ironline-rail.example/info\"' in out\n    assert \">Status OK</a>\" 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_switches_badge(\"t\", \"<script>alert(1)</script>\", \"https://status.ironline-rail.example/ok\")\n    assert \"<script>\" not in out.lower(), f\"Unescaped <script> in output: {out}\"\n    assert \"&lt;script&gt;\" in out\n\ndef test_attribute_breakout_escaped():\n    out = target_module.render_switches_badge('\" onmouseover=\"alert(1)', \"ok\", \"https://status.ironline-rail.example/ok\")\n    assert 'onmouseover=\"alert' not in out.lower()\n    assert \"&quot;\" in out or \"&#x27;\" in out\n\ndef test_javascript_href_rejected():\n    try:\n        out = target_module.render_switches_badge(\"t\", \"click\", \"JaVaScRiPt:alert(1)\")\n    except ValueError:\n        return\n    assert \"javascript:\" not in out.lower(), f\"javascript: URL rendered in href: {out}\"\n\n_run_checks([\n    (\"script_tag_escaped\", test_script_tag_escaped),\n    (\"attribute_breakout_escaped\", test_attribute_breakout_escaped),\n    (\"javascript_href_rejected\", test_javascript_href_rejected),\n])\n", "metadata": {"cwe": "CWE-79", "fn": "render_switches_badge"}}
{"task_id": "pg-fresh-crypto_secrets-0047", "category": "crypto_secrets", "split": "fresh", "seed": 13454556549313541465, "domain": "observatory_logs", "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 `observatory_logs` 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 observatory_logs.\"\"\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={api_key}\"\n```\n", "vulnerable_code": "import 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 observatory_logs.\"\"\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={api_key}\"\n", "reference_patch": "import hashlib\nimport hmac\nimport secrets\n\n\ndef hash_password(password: str) -> str:\n    \"\"\"Hash a password using salted scrypt.\"\"\"\n    salt = secrets.token_bytes(16)\n    digest = hashlib.scrypt(password.encode(\"utf-8\"), salt=salt, n=16384, r=8, p=1, dklen=32)\n    return f\"scrypt${salt.hex()}${digest.hex()}\"\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n    \"\"\"Verify a password against a salted scrypt hash in constant time.\"\"\"\n    parts = stored_hash.split(\"$\")\n    if len(parts) != 3 or parts[0] != \"scrypt\":\n        return False\n    salt = bytes.fromhex(parts[1])\n    expected = bytes.fromhex(parts[2])\n    candidate = hashlib.scrypt(password.encode(\"utf-8\"), salt=salt, n=16384, r=8, p=1, dklen=len(expected))\n    return hmac.compare_digest(candidate, expected)\n\n\ndef issue_token() -> str:\n    \"\"\"Issue a cryptographically secure random URL-safe token.\"\"\"\n    return secrets.token_urlsafe(32)\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n    \"\"\"Format an audit log entry for observatory_logs with credentials redacted.\"\"\"\n    masked = \"[REDACTED]\" if not api_key else f\"***{api_key[-2:]}\" if len(api_key) > 6 else \"[REDACTED]\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={masked}\"\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_password_roundtrip():\n    h = target_module.hash_password(\"CorrectHorse!42\")\n    assert target_module.verify_password(\"CorrectHorse!42\", h) is True\n    assert target_module.verify_password(\"WrongPass!42\", h) is False\n\ndef test_token_and_audit():\n    tok = target_module.issue_token()\n    assert isinstance(tok, str) and len(tok) >= 32\n    line = target_module.format_audit_log(\"lab_topaz\", \"rotate\", \"sk_live_secret_token_9981\")\n    assert \"lab_topaz\" in line and \"rotate\" in line\n\n_run_checks([(\"password_roundtrip\", test_password_roundtrip), (\"token_and_audit\", test_token_and_audit)])\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 hashlib\nimport random\nimport target_module\n\ndef test_password_uses_salted_kdf():\n    h1 = target_module.hash_password(\"hunter2\")\n    h2 = target_module.hash_password(\"hunter2\")\n    assert h1 != h2, \"Password hash is unsalted (identical outputs for identical passwords)\"\n    assert hashlib.md5(b\"hunter2\").hexdigest() not in h1\n    assert hashlib.sha256(b\"hunter2\").hexdigest() not in h1\n\ndef test_token_unpredictable_under_random_seed():\n    random.seed(12345)\n    t1 = target_module.issue_token()\n    random.seed(12345)\n    t2 = target_module.issue_token()\n    assert t1 != t2, \"Token depends on predictable random module!\"\n\ndef test_audit_log_redacts_secret():\n    secret = \"sk_live_very_secret_987654321\"\n    line = target_module.format_audit_log(\"lab_topaz\", \"login\", secret)\n    assert secret not in line, f\"Raw API key leaked in audit log: {line}\"\n    assert \"very_secret\" not in line\n\n_run_checks([\n    (\"password_uses_salted_kdf\", test_password_uses_salted_kdf),\n    (\"token_unpredictable_under_random_seed\", test_token_unpredictable_under_random_seed),\n    (\"audit_log_redacts_secret\", test_audit_log_redacts_secret),\n])\n", "metadata": {"cwe": "CWE-327", "fn": "hash_password/verify_password/issue_token/format_audit_log"}}
{"task_id": "pg-fresh-sqli-0048", "category": "sqli", "split": "fresh", "seed": 9719964488308993183, "domain": "observatory_logs", "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 `observatory_logs` 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 gather_habitats(db_path: str, query: str, sort_by: str = \"salinity_ppt\", limit: int = 10) -> list[dict]:\n    \"\"\"Search habitats matching query on biome_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, biome_label, category_tag, salinity_ppt \"\n            f\"FROM habitats \"\n            f\"WHERE biome_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", "vulnerable_code": "import sqlite3\n\n\ndef gather_habitats(db_path: str, query: str, sort_by: str = \"salinity_ppt\", limit: int = 10) -> list[dict]:\n    \"\"\"Search habitats matching query on biome_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, biome_label, category_tag, salinity_ppt \"\n            f\"FROM habitats \"\n            f\"WHERE biome_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", "reference_patch": "import sqlite3\n\n_ALLOWED_SORT_COLUMNS = frozenset({\"id\", \"biome_label\", \"category_tag\", \"salinity_ppt\"})\n\n\ndef gather_habitats(db_path: str, query: str, sort_by: str = \"salinity_ppt\", limit: int = 10) -> list[dict]:\n    \"\"\"Search habitats matching query on biome_label 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, biome_label, category_tag, salinity_ppt \"\n            f\"FROM habitats \"\n            f\"WHERE biome_label 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 habitats (id INTEGER PRIMARY KEY, biome_label TEXT, category_tag TEXT, salinity_ppt 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 habitats (biome_label, category_tag, salinity_ppt) VALUES (?, ?, ?)\",\n        [\n            (\"frame_447_alpha\", \"pelagic\", 10),\n            (\"frame_447_beta\", \"pelagic\", 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.gather_habitats(p, \"frame_447\")\n        assert len(rows) == 2, f\"expected 2 rows, got {rows}\"\n        assert rows[0][\"salinity_ppt\"] == 25\n    finally:\n        os.remove(p)\n\ndef test_sort_and_limit():\n    p = _make_db()\n    try:\n        rows = target_module.gather_habitats(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 habitats (id INTEGER PRIMARY KEY, biome_label TEXT, category_tag TEXT, salinity_ppt 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 habitats (biome_label, category_tag, salinity_ppt) VALUES (?, ?, ?)\",\n        [\n            (\"frame_447_alpha\", \"pelagic\", 10),\n            (\"frame_447_beta\", \"pelagic\", 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.gather_habitats(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.gather_habitats(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.gather_habitats(p, \"frame_447\", sort_by=\"(CASE WHEN (1=1) THEN id ELSE salinity_ppt 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": "gather_habitats"}}
{"task_id": "pg-fresh-path_traversal-0049", "category": "path_traversal", "split": "fresh", "seed": 16542887253548718221, "domain": "rail_signaling", "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 `rail_signaling` 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 collect_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 collect_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 collect_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 / \"frame_447.txt\").write_text(\"ok_content_frame_447\", 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.collect_artifact_text(str(base), \"frame_447.txt\") == \"ok_content_frame_447\"\n    finally:\n        shutil.rmtree(root)\n\ndef test_read_nested_file():\n    root, base = _make_tree()\n    try:\n        assert target_module.collect_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 / \"frame_447.txt\").write_text(\"ok_content_frame_447\", 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.collect_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": "collect_artifact_text"}}
{"task_id": "pg-fresh-cmd_injection-0050", "category": "cmd_injection", "split": "fresh", "seed": 15367707896978107425, "domain": "rail_signaling", "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 `rail_signaling` 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_rail_signaling_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_rail_signaling_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_rail_signaling_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_rail_signaling_tool(str(hp), \"summary\", \"frame_447\")\n        assert out == \"summary:frame_447\", 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_rail_signaling_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\"frame_447 && python -c \\\"open(r'{marker}','w').write('PWN')\\\"\"\n    try:\n        try:\n            target_module.run_rail_signaling_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_rail_signaling_tool(str(hp), f\"summary --evil-probe {marker}\", \"frame_447\")\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_rail_signaling_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_rail_signaling_tool"}}
{"task_id": "pg-fresh-ssrf-0051", "category": "ssrf", "split": "fresh", "seed": 5384921335019791007, "domain": "aquarium_tanks", "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 `aquarium_tanks` 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 collect_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 collect_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 collect_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 == \"status.ironline-rail.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.collect_remote_feed(\n        \"https://status.ironline-rail.example/v1/data.json\",\n        resolver=_public_resolver,\n        transport=_fake_transport,\n    )\n    assert out == \"fetched:https://status.ironline-rail.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 == \"status.ironline-rail.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.collect_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": "collect_remote_feed"}}
{"task_id": "pg-fresh-idor_auth-0052", "category": "idor_auth", "split": "fresh", "seed": 9873891720446834732, "domain": "rail_signaling", "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 `rail_signaling` 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_exposures_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_exposures_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_exposures_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        \"relay_910_1\": {\"id\": \"relay_910_1\", \"owner_id\": \"lab_topaz_a\", \"note\": \"initial\", \"status\": \"open\"},\n        \"relay_910_2\": {\"id\": \"relay_910_2\", \"owner_id\": \"lab_topaz_b\", \"note\": \"private_b\", \"status\": \"sealed\"},\n    }\ndef test_owner_read_and_update():\n    s = _make_store()\n    sess = {\"user_id\": \"lab_topaz_a\", \"role\": \"member\"}\n    out = target_module.update_exposures_record(s, sess, \"relay_910_1\", {\"note\": \"updated\"})\n    assert out[\"note\"] == \"updated\"\n    assert out[\"owner_id\"] == \"lab_topaz_a\"\n\ndef test_admin_access():\n    s = _make_store()\n    sess = {\"user_id\": \"sec_admin\", \"role\": \"admin\"}\n    out = target_module.update_exposures_record(s, sess, \"relay_910_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        \"relay_910_1\": {\"id\": \"relay_910_1\", \"owner_id\": \"lab_topaz_a\", \"note\": \"initial\", \"status\": \"open\"},\n        \"relay_910_2\": {\"id\": \"relay_910_2\", \"owner_id\": \"lab_topaz_b\", \"note\": \"private_b\", \"status\": \"sealed\"},\n    }\ndef test_unauthenticated_blocked():\n    s = _make_store()\n    try:\n        target_module.update_exposures_record(s, {}, \"relay_910_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\": \"lab_topaz_a\", \"role\": \"member\"}\n    try:\n        target_module.update_exposures_record(s, sess, \"relay_910_2\", {\"note\": \"tampered\"})\n    except PermissionError:\n        assert s[\"relay_910_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\": \"lab_topaz_a\", \"role\": \"member\"}\n    try:\n        out = target_module.update_exposures_record(s, sess, \"relay_910_1\", {\"owner_id\": \"lab_topaz_b\", \"is_admin\": True, \"role\": \"admin\"})\n    except (ValueError, PermissionError):\n        assert s[\"relay_910_1\"][\"owner_id\"] == \"lab_topaz_a\"\n        assert not s[\"relay_910_1\"].get(\"is_admin\")\n        assert s[\"relay_910_1\"].get(\"role\") != \"admin\"\n        return\n    assert out[\"owner_id\"] == \"lab_topaz_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_exposures_record"}}
{"task_id": "pg-fresh-unsafe_deser_eval-0053", "category": "unsafe_deser_eval", "split": "fresh", "seed": 4976227750415614295, "domain": "rail_signaling", "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 `rail_signaling` 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_rail_signaling_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_rail_signaling_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_rail_signaling_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_rail_signaling_payload('{\"item\": \"relay_910\", \"count\": 4}')\n    assert out == {\"item\": \"relay_910\", \"count\": 4}\n\ndef test_non_dict_rejected():\n    try:\n        target_module.parse_rail_signaling_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_rail_signaling_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_rail_signaling_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_rail_signaling_payload"}}
{"task_id": "pg-fresh-xss-0054", "category": "xss", "split": "fresh", "seed": 17868471976772272676, "domain": "observatory_logs", "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 `observatory_logs` 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_switches_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", "vulnerable_code": "def render_switches_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", "reference_patch": "import html\nimport urllib.parse\n\n\ndef render_switches_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'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_url}\">{safe_summary}</a></div>'\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_switches_badge(\"frame_447\", \"Status OK\", \"https://mirror.zenith-sky.example/info\")\n    assert 'title=\"frame_447\"' in out\n    assert 'href=\"https://mirror.zenith-sky.example/info\"' in out\n    assert \">Status OK</a>\" 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_switches_badge(\"t\", \"<script>alert(1)</script>\", \"https://mirror.zenith-sky.example/ok\")\n    assert \"<script>\" not in out.lower(), f\"Unescaped <script> in output: {out}\"\n    assert \"&lt;script&gt;\" in out\n\ndef test_attribute_breakout_escaped():\n    out = target_module.render_switches_badge('\" onmouseover=\"alert(1)', \"ok\", \"https://mirror.zenith-sky.example/ok\")\n    assert 'onmouseover=\"alert' not in out.lower()\n    assert \"&quot;\" in out or \"&#x27;\" in out\n\ndef test_javascript_href_rejected():\n    try:\n        out = target_module.render_switches_badge(\"t\", \"click\", \"JaVaScRiPt:alert(1)\")\n    except ValueError:\n        return\n    assert \"javascript:\" not in out.lower(), f\"javascript: URL rendered in href: {out}\"\n\n_run_checks([\n    (\"script_tag_escaped\", test_script_tag_escaped),\n    (\"attribute_breakout_escaped\", test_attribute_breakout_escaped),\n    (\"javascript_href_rejected\", test_javascript_href_rejected),\n])\n", "metadata": {"cwe": "CWE-79", "fn": "render_switches_badge"}}
{"task_id": "pg-fresh-crypto_secrets-0055", "category": "crypto_secrets", "split": "fresh", "seed": 8549347130605186519, "domain": "observatory_logs", "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 `observatory_logs` 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 observatory_logs.\"\"\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={api_key}\"\n```\n", "vulnerable_code": "import 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 observatory_logs.\"\"\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={api_key}\"\n", "reference_patch": "import hashlib\nimport hmac\nimport secrets\n\n\ndef hash_password(password: str) -> str:\n    \"\"\"Hash a password using salted scrypt.\"\"\"\n    salt = secrets.token_bytes(16)\n    digest = hashlib.scrypt(password.encode(\"utf-8\"), salt=salt, n=16384, r=8, p=1, dklen=32)\n    return f\"scrypt${salt.hex()}${digest.hex()}\"\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n    \"\"\"Verify a password against a salted scrypt hash in constant time.\"\"\"\n    parts = stored_hash.split(\"$\")\n    if len(parts) != 3 or parts[0] != \"scrypt\":\n        return False\n    salt = bytes.fromhex(parts[1])\n    expected = bytes.fromhex(parts[2])\n    candidate = hashlib.scrypt(password.encode(\"utf-8\"), salt=salt, n=16384, r=8, p=1, dklen=len(expected))\n    return hmac.compare_digest(candidate, expected)\n\n\ndef issue_token() -> str:\n    \"\"\"Issue a cryptographically secure random URL-safe token.\"\"\"\n    return secrets.token_urlsafe(32)\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n    \"\"\"Format an audit log entry for observatory_logs with credentials redacted.\"\"\"\n    masked = \"[REDACTED]\" if not api_key else f\"***{api_key[-2:]}\" if len(api_key) > 6 else \"[REDACTED]\"\n    return f\"service=observatory_logs user={user_id} action={action} api_key={masked}\"\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_password_roundtrip():\n    h = target_module.hash_password(\"CorrectHorse!42\")\n    assert target_module.verify_password(\"CorrectHorse!42\", h) is True\n    assert target_module.verify_password(\"WrongPass!42\", h) is False\n\ndef test_token_and_audit():\n    tok = target_module.issue_token()\n    assert isinstance(tok, str) and len(tok) >= 32\n    line = target_module.format_audit_log(\"lab_zircon\", \"rotate\", \"sk_live_secret_token_9981\")\n    assert \"lab_zircon\" in line and \"rotate\" in line\n\n_run_checks([(\"password_roundtrip\", test_password_roundtrip), (\"token_and_audit\", test_token_and_audit)])\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 hashlib\nimport random\nimport target_module\n\ndef test_password_uses_salted_kdf():\n    h1 = target_module.hash_password(\"hunter2\")\n    h2 = target_module.hash_password(\"hunter2\")\n    assert h1 != h2, \"Password hash is unsalted (identical outputs for identical passwords)\"\n    assert hashlib.md5(b\"hunter2\").hexdigest() not in h1\n    assert hashlib.sha256(b\"hunter2\").hexdigest() not in h1\n\ndef test_token_unpredictable_under_random_seed():\n    random.seed(12345)\n    t1 = target_module.issue_token()\n    random.seed(12345)\n    t2 = target_module.issue_token()\n    assert t1 != t2, \"Token depends on predictable random module!\"\n\ndef test_audit_log_redacts_secret():\n    secret = \"sk_live_very_secret_987654321\"\n    line = target_module.format_audit_log(\"lab_zircon\", \"login\", secret)\n    assert secret not in line, f\"Raw API key leaked in audit log: {line}\"\n    assert \"very_secret\" not in line\n\n_run_checks([\n    (\"password_uses_salted_kdf\", test_password_uses_salted_kdf),\n    (\"token_unpredictable_under_random_seed\", test_token_unpredictable_under_random_seed),\n    (\"audit_log_redacts_secret\", test_audit_log_redacts_secret),\n])\n", "metadata": {"cwe": "CWE-327", "fn": "hash_password/verify_password/issue_token/format_audit_log"}}
{"task_id": "pg-fresh-sqli-0056", "category": "sqli", "split": "fresh", "seed": 10907637736346751096, "domain": "aquarium_tanks", "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 `aquarium_tanks` 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 gather_exposures(db_path: str, query: str, sort_by: str = \"captured_at\", limit: int = 10) -> list[dict]:\n    \"\"\"Search exposures matching query on nebula_ref and return sorted rows.\"\"\"\n    conn = sqlite3.connect(db_path)\n    conn.row_factory = sqlite3.Row\n    try:\n        sql = (\n            f\"SELECT id, nebula_ref, category_tag, captured_at \"\n            f\"FROM exposures \"\n            f\"WHERE nebula_ref 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 gather_exposures(db_path: str, query: str, sort_by: str = \"captured_at\", limit: int = 10) -> list[dict]:\n    \"\"\"Search exposures matching query on nebula_ref and return sorted rows.\"\"\"\n    conn = sqlite3.connect(db_path)\n    conn.row_factory = sqlite3.Row\n    try:\n        sql = (\n            f\"SELECT id, nebula_ref, category_tag, captured_at \"\n            f\"FROM exposures \"\n            f\"WHERE nebula_ref 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\", \"nebula_ref\", \"category_tag\", \"captured_at\"})\n\n\ndef gather_exposures(db_path: str, query: str, sort_by: str = \"captured_at\", limit: int = 10) -> list[dict]:\n    \"\"\"Search exposures matching query on nebula_ref 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, nebula_ref, category_tag, captured_at \"\n            f\"FROM exposures \"\n            f\"WHERE nebula_ref 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 exposures (id INTEGER PRIMARY KEY, nebula_ref TEXT, category_tag TEXT, captured_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 exposures (nebula_ref, category_tag, captured_at) VALUES (?, ?, ?)\",\n        [\n            (\"frame_447_alpha\", \"infrared\", 10),\n            (\"frame_447_beta\", \"infrared\", 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.gather_exposures(p, \"frame_447\")\n        assert len(rows) == 2, f\"expected 2 rows, got {rows}\"\n        assert rows[0][\"captured_at\"] == 25\n    finally:\n        os.remove(p)\n\ndef test_sort_and_limit():\n    p = _make_db()\n    try:\n        rows = target_module.gather_exposures(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 exposures (id INTEGER PRIMARY KEY, nebula_ref TEXT, category_tag TEXT, captured_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 exposures (nebula_ref, category_tag, captured_at) VALUES (?, ?, ?)\",\n        [\n            (\"frame_447_alpha\", \"infrared\", 10),\n            (\"frame_447_beta\", \"infrared\", 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.gather_exposures(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.gather_exposures(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.gather_exposures(p, \"frame_447\", sort_by=\"(CASE WHEN (1=1) THEN id ELSE captured_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": "gather_exposures"}}
{"task_id": "pg-fresh-path_traversal-0057", "category": "path_traversal", "split": "fresh", "seed": 5965539682882746288, "domain": "aquarium_tanks", "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 `aquarium_tanks` 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 collect_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 collect_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 collect_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 / \"frame_447.txt\").write_text(\"ok_content_frame_447\", 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.collect_artifact_text(str(base), \"frame_447.txt\") == \"ok_content_frame_447\"\n    finally:\n        shutil.rmtree(root)\n\ndef test_read_nested_file():\n    root, base = _make_tree()\n    try:\n        assert target_module.collect_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 / \"frame_447.txt\").write_text(\"ok_content_frame_447\", 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.collect_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": "collect_artifact_text"}}
{"task_id": "pg-fresh-cmd_injection-0058", "category": "cmd_injection", "split": "fresh", "seed": 7670935484522125858, "domain": "observatory_logs", "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 `observatory_logs` 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_observatory_logs_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_observatory_logs_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_observatory_logs_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_observatory_logs_tool(str(hp), \"summary\", \"relay_910\")\n        assert out == \"summary:relay_910\", 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_observatory_logs_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\"relay_910 && python -c \\\"open(r'{marker}','w').write('PWN')\\\"\"\n    try:\n        try:\n            target_module.run_observatory_logs_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_observatory_logs_tool(str(hp), f\"summary --evil-probe {marker}\", \"relay_910\")\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_observatory_logs_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_observatory_logs_tool"}}
{"task_id": "pg-fresh-ssrf-0059", "category": "ssrf", "split": "fresh", "seed": 15717431441449122898, "domain": "rail_signaling", "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 `rail_signaling` 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 gather_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 gather_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 gather_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 == \"mirror.zenith-sky.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.gather_remote_feed(\n        \"https://mirror.zenith-sky.example/v1/data.json\",\n        resolver=_public_resolver,\n        transport=_fake_transport,\n    )\n    assert out == \"fetched:https://mirror.zenith-sky.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 == \"mirror.zenith-sky.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.gather_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": "gather_remote_feed"}}
{"task_id": "pg-fresh-idor_auth-0060", "category": "idor_auth", "split": "fresh", "seed": 11764326093310745363, "domain": "observatory_logs", "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 `observatory_logs` 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_switches_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_switches_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_switches_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        \"reef_532_1\": {\"id\": \"reef_532_1\", \"owner_id\": \"lab_topaz_a\", \"note\": \"initial\", \"status\": \"open\"},\n        \"reef_532_2\": {\"id\": \"reef_532_2\", \"owner_id\": \"lab_topaz_b\", \"note\": \"private_b\", \"status\": \"sealed\"},\n    }\ndef test_owner_read_and_update():\n    s = _make_store()\n    sess = {\"user_id\": \"lab_topaz_a\", \"role\": \"member\"}\n    out = target_module.update_switches_record(s, sess, \"reef_532_1\", {\"note\": \"updated\"})\n    assert out[\"note\"] == \"updated\"\n    assert out[\"owner_id\"] == \"lab_topaz_a\"\n\ndef test_admin_access():\n    s = _make_store()\n    sess = {\"user_id\": \"sec_admin\", \"role\": \"admin\"}\n    out = target_module.update_switches_record(s, sess, \"reef_532_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        \"reef_532_1\": {\"id\": \"reef_532_1\", \"owner_id\": \"lab_topaz_a\", \"note\": \"initial\", \"status\": \"open\"},\n        \"reef_532_2\": {\"id\": \"reef_532_2\", \"owner_id\": \"lab_topaz_b\", \"note\": \"private_b\", \"status\": \"sealed\"},\n    }\ndef test_unauthenticated_blocked():\n    s = _make_store()\n    try:\n        target_module.update_switches_record(s, {}, \"reef_532_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\": \"lab_topaz_a\", \"role\": \"member\"}\n    try:\n        target_module.update_switches_record(s, sess, \"reef_532_2\", {\"note\": \"tampered\"})\n    except PermissionError:\n        assert s[\"reef_532_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\": \"lab_topaz_a\", \"role\": \"member\"}\n    try:\n        out = target_module.update_switches_record(s, sess, \"reef_532_1\", {\"owner_id\": \"lab_topaz_b\", \"is_admin\": True, \"role\": \"admin\"})\n    except (ValueError, PermissionError):\n        assert s[\"reef_532_1\"][\"owner_id\"] == \"lab_topaz_a\"\n        assert not s[\"reef_532_1\"].get(\"is_admin\")\n        assert s[\"reef_532_1\"].get(\"role\") != \"admin\"\n        return\n    assert out[\"owner_id\"] == \"lab_topaz_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_switches_record"}}
{"task_id": "pg-fresh-unsafe_deser_eval-0061", "category": "unsafe_deser_eval", "split": "fresh", "seed": 8083774318213095756, "domain": "observatory_logs", "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 `observatory_logs` 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_observatory_logs_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_observatory_logs_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_observatory_logs_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_observatory_logs_payload('{\"item\": \"relay_910\", \"count\": 4}')\n    assert out == {\"item\": \"relay_910\", \"count\": 4}\n\ndef test_non_dict_rejected():\n    try:\n        target_module.parse_observatory_logs_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_observatory_logs_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_observatory_logs_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_observatory_logs_payload"}}
{"task_id": "pg-fresh-xss-0062", "category": "xss", "split": "fresh", "seed": 10346100513037516216, "domain": "aquarium_tanks", "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 `aquarium_tanks` 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_exposures_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", "vulnerable_code": "def render_exposures_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", "reference_patch": "import html\nimport urllib.parse\n\n\ndef render_exposures_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'<div class=\"badge\" title=\"{safe_title}\"><a href=\"{safe_url}\">{safe_summary}</a></div>'\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_exposures_badge(\"relay_910\", \"Status OK\", \"https://status.ironline-rail.example/info\")\n    assert 'title=\"relay_910\"' in out\n    assert 'href=\"https://status.ironline-rail.example/info\"' in out\n    assert \">Status OK</a>\" 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_exposures_badge(\"t\", \"<script>alert(1)</script>\", \"https://status.ironline-rail.example/ok\")\n    assert \"<script>\" not in out.lower(), f\"Unescaped <script> in output: {out}\"\n    assert \"&lt;script&gt;\" in out\n\ndef test_attribute_breakout_escaped():\n    out = target_module.render_exposures_badge('\" onmouseover=\"alert(1)', \"ok\", \"https://status.ironline-rail.example/ok\")\n    assert 'onmouseover=\"alert' not in out.lower()\n    assert \"&quot;\" in out or \"&#x27;\" in out\n\ndef test_javascript_href_rejected():\n    try:\n        out = target_module.render_exposures_badge(\"t\", \"click\", \"JaVaScRiPt:alert(1)\")\n    except ValueError:\n        return\n    assert \"javascript:\" not in out.lower(), f\"javascript: URL rendered in href: {out}\"\n\n_run_checks([\n    (\"script_tag_escaped\", test_script_tag_escaped),\n    (\"attribute_breakout_escaped\", test_attribute_breakout_escaped),\n    (\"javascript_href_rejected\", test_javascript_href_rejected),\n])\n", "metadata": {"cwe": "CWE-79", "fn": "render_exposures_badge"}}
{"task_id": "pg-fresh-crypto_secrets-0063", "category": "crypto_secrets", "split": "fresh", "seed": 16744462717901639338, "domain": "rail_signaling", "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 `rail_signaling` 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 rail_signaling.\"\"\"\n    return f\"service=rail_signaling user={user_id} action={action} api_key={api_key}\"\n```\n", "vulnerable_code": "import 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 rail_signaling.\"\"\"\n    return f\"service=rail_signaling user={user_id} action={action} api_key={api_key}\"\n", "reference_patch": "import hashlib\nimport hmac\nimport secrets\n\n\ndef hash_password(password: str) -> str:\n    \"\"\"Hash a password using salted scrypt.\"\"\"\n    salt = secrets.token_bytes(16)\n    digest = hashlib.scrypt(password.encode(\"utf-8\"), salt=salt, n=16384, r=8, p=1, dklen=32)\n    return f\"scrypt${salt.hex()}${digest.hex()}\"\n\n\ndef verify_password(password: str, stored_hash: str) -> bool:\n    \"\"\"Verify a password against a salted scrypt hash in constant time.\"\"\"\n    parts = stored_hash.split(\"$\")\n    if len(parts) != 3 or parts[0] != \"scrypt\":\n        return False\n    salt = bytes.fromhex(parts[1])\n    expected = bytes.fromhex(parts[2])\n    candidate = hashlib.scrypt(password.encode(\"utf-8\"), salt=salt, n=16384, r=8, p=1, dklen=len(expected))\n    return hmac.compare_digest(candidate, expected)\n\n\ndef issue_token() -> str:\n    \"\"\"Issue a cryptographically secure random URL-safe token.\"\"\"\n    return secrets.token_urlsafe(32)\n\n\ndef format_audit_log(user_id: str, action: str, api_key: str) -> str:\n    \"\"\"Format an audit log entry for rail_signaling with credentials redacted.\"\"\"\n    masked = \"[REDACTED]\" if not api_key else f\"***{api_key[-2:]}\" if len(api_key) > 6 else \"[REDACTED]\"\n    return f\"service=rail_signaling user={user_id} action={action} api_key={masked}\"\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_password_roundtrip():\n    h = target_module.hash_password(\"CorrectHorse!42\")\n    assert target_module.verify_password(\"CorrectHorse!42\", h) is True\n    assert target_module.verify_password(\"WrongPass!42\", h) is False\n\ndef test_token_and_audit():\n    tok = target_module.issue_token()\n    assert isinstance(tok, str) and len(tok) >= 32\n    line = target_module.format_audit_log(\"lab_topaz\", \"rotate\", \"sk_live_secret_token_9981\")\n    assert \"lab_topaz\" in line and \"rotate\" in line\n\n_run_checks([(\"password_roundtrip\", test_password_roundtrip), (\"token_and_audit\", test_token_and_audit)])\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 hashlib\nimport random\nimport target_module\n\ndef test_password_uses_salted_kdf():\n    h1 = target_module.hash_password(\"hunter2\")\n    h2 = target_module.hash_password(\"hunter2\")\n    assert h1 != h2, \"Password hash is unsalted (identical outputs for identical passwords)\"\n    assert hashlib.md5(b\"hunter2\").hexdigest() not in h1\n    assert hashlib.sha256(b\"hunter2\").hexdigest() not in h1\n\ndef test_token_unpredictable_under_random_seed():\n    random.seed(12345)\n    t1 = target_module.issue_token()\n    random.seed(12345)\n    t2 = target_module.issue_token()\n    assert t1 != t2, \"Token depends on predictable random module!\"\n\ndef test_audit_log_redacts_secret():\n    secret = \"sk_live_very_secret_987654321\"\n    line = target_module.format_audit_log(\"lab_topaz\", \"login\", secret)\n    assert secret not in line, f\"Raw API key leaked in audit log: {line}\"\n    assert \"very_secret\" not in line\n\n_run_checks([\n    (\"password_uses_salted_kdf\", test_password_uses_salted_kdf),\n    (\"token_unpredictable_under_random_seed\", test_token_unpredictable_under_random_seed),\n    (\"audit_log_redacts_secret\", test_audit_log_redacts_secret),\n])\n", "metadata": {"cwe": "CWE-327", "fn": "hash_password/verify_password/issue_token/format_audit_log"}}