Datasets:
id string | family string | split string | language string | cwe string | vuln_type string | is_vulnerable bool | vulnerable_code string | fixed_code string | vulnerable_lines list | explanation string | patch_summary string | safe_test string | source string | source_license string |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
psp-377-df604b7661e24aa6 | cwe-377-insecure_temp_file-python-stdlib-train-guarded_function | train | python | CWE-377 | Insecure temporary file | true | from pathlib import Path
def load_insecure_temp_file_4022_12(payload_4022_12, policy_4022_12):
if any(value is None for value in (payload_4022_12, policy_4022_12,)):
raise ValueError("arguments are required")
path = Path(f"/tmp/{payload_4022_12}.txt")
path.write_text(policy_4022_12, encoding="utf-8... | import os
import tempfile
def load_insecure_temp_file_4022_12(payload_4022_12, policy_4022_12):
if any(value is None for value in (payload_4022_12, policy_4022_12,)):
raise ValueError("arguments are required")
descriptor, path = tempfile.mkstemp(prefix="pysecpatch-", suffix=".txt", text=True)
with ... | [
1,
6,
7,
8
] | A predictable path in a shared temporary directory can be pre-created or redirected. | Create the file atomically with tempfile.mkstemp. | def test_insecure_temp_file_df604b76_uses_safe_shape():
import inspect
source = inspect.getsource(load_insecure_temp_file_4022_12)
assert '/tmp/' not in source
assert 'mkstemp' in source
| generated | Apache-2.0 |
psp-643-22580c79cdad3999 | cwe-643-lxml_xpath_injection-lxml-train-two_stage | train | python | CWE-643 | XPath injection | true | def _ready_handle_lxml_xpath_injection_5997_12():
return True
def handle_lxml_xpath_injection_5997_12(value_5997_12, target_5997_12):
if not _ready_handle_lxml_xpath_injection_5997_12():
raise RuntimeError("handler is not ready")
xpath = f"//user[@name='{target_5997_12}']"
return value_5997_12.... | def _ready_handle_lxml_xpath_injection_5997_12():
return True
def handle_lxml_xpath_injection_5997_12(value_5997_12, target_5997_12):
if not _ready_handle_lxml_xpath_injection_5997_12():
raise RuntimeError("handler is not ready")
return value_5997_12.xpath("//user[@name=$account]", account=target_5... | [
7,
8
] | Untrusted text is interpolated into an XPath expression. | Bind the value as an XPath variable instead of constructing expression text. | def test_lxml_xpath_injection_22580c79_uses_safe_shape():
import inspect
source = inspect.getsource(handle_lxml_xpath_injection_5997_12)
assert 'xpath = f' not in source
assert '$account' in source
| generated | Apache-2.0 |
psp-611-4787dd7d2b437701 | cwe-611-lxml_external_entity-lxml-train-guarded_function | train | python | CWE-611 | XML external entity processing | false | from lxml import etree
def apply_lxml_external_entity_3668_29(request_3668_29):
if any(value is None for value in (request_3668_29,)):
raise ValueError("arguments are required")
parser = etree.XMLParser(resolve_entities=False, no_network=True, load_dtd=False)
return etree.fromstring(request_3668_29... | from lxml import etree
def apply_lxml_external_entity_3668_29(request_3668_29):
if any(value is None for value in (request_3668_29,)):
raise ValueError("arguments are required")
parser = etree.XMLParser(resolve_entities=False, no_network=True, load_dtd=False)
return etree.fromstring(request_3668_29... | [] | Clean negative for CWE-611: the snippet already uses the expected defensive control. | No code change is required. | def test_lxml_external_entity_4787dd7d_uses_safe_shape():
import inspect
source = inspect.getsource(apply_lxml_external_entity_3668_29)
assert 'resolve_entities=False' in source
| generated | Apache-2.0 |
psp-942-85caa5ad315baf63 | cwe-942-starlette_permissive_cors-fastapi-starlette-train-two_stage | train | python | CWE-942 | Permissive cross-domain policy | false | from starlette.middleware.cors import CORSMiddleware
def _ready_process_starlette_permissive_cors_7700_11():
return True
def process_starlette_permissive_cors_7700_11(payload_7700_11, target_7700_11):
if not _ready_process_starlette_permissive_cors_7700_11():
raise RuntimeError("handler is not ready")... | from starlette.middleware.cors import CORSMiddleware
def _ready_process_starlette_permissive_cors_7700_11():
return True
def process_starlette_permissive_cors_7700_11(payload_7700_11, target_7700_11):
if not _ready_process_starlette_permissive_cors_7700_11():
raise RuntimeError("handler is not ready")... | [] | Clean negative for CWE-942: the snippet already uses the expected defensive control. | No code change is required. | def test_starlette_permissive_cors_85caa5ad_uses_safe_shape():
import inspect
source = inspect.getsource(process_starlette_permissive_cors_7700_11)
assert 'allow_origins=["*"]' not in source
assert 'allow_origins=trusted_origins' in source
| generated | Apache-2.0 |
psp-409-0d6ae8bf316a95a2 | cwe-409-zip_decompression_bomb-python-stdlib-train-two_stage | train | python | CWE-409 | Improper handling of highly compressed data | true | def _ready_resolve_zip_decompression_bomb_4549_0():
return True
def resolve_zip_decompression_bomb_4549_0(value_4549_0, target_4549_0):
if not _ready_resolve_zip_decompression_bomb_4549_0():
raise RuntimeError("handler is not ready")
value_4549_0.extractall(target_4549_0)
return target_4549_0
| def _ready_resolve_zip_decompression_bomb_4549_0():
return True
def resolve_zip_decompression_bomb_4549_0(value_4549_0, target_4549_0):
if not _ready_resolve_zip_decompression_bomb_4549_0():
raise RuntimeError("handler is not ready")
members = value_4549_0.infolist()
total_size = sum(member.fil... | [
7
] | Archive members are expanded without a total uncompressed-size limit. | Validate member count and total declared size before extraction. | def test_zip_decompression_bomb_0d6ae8bf_uses_safe_shape():
import inspect
source = inspect.getsource(resolve_zip_decompression_bomb_4549_0)
assert 'total_size' in source
| generated | Apache-2.0 |
psp-327-c4dcc22f7d9beaf1 | cwe-327-weak_cryptography-python-stdlib-train-static_method | train | python | CWE-327 | Weak cryptography | false | import hashlib
class LocalWeakCryptography16:
@staticmethod
def apply_weak_cryptography_6588_14(request_6588_14, context_6588_14):
derived = hashlib.pbkdf2_hmac("sha256", request_6588_14.encode("utf-8"), context_6588_14, 240000)
return derived.hex()
| import hashlib
class LocalWeakCryptography16:
@staticmethod
def apply_weak_cryptography_6588_14(request_6588_14, context_6588_14):
derived = hashlib.pbkdf2_hmac("sha256", request_6588_14.encode("utf-8"), context_6588_14, 240000)
return derived.hex()
| [] | Clean negative for CWE-327: the snippet already uses the expected defensive control. | No code change is required. | def test_weak_cryptography_c4dcc22f_uses_safe_shape():
import inspect
source = inspect.getsource(LocalWeakCryptography16.apply_weak_cryptography_6588_14)
assert 'sha1(' not in source
assert 'pbkdf2_hmac' in source
| generated | Apache-2.0 |
psp-918-a027a3fcb89dcea4 | cwe-918-ssrf-python-stdlib-train-function | train | python | CWE-918 | Server-side request forgery | true | import requests
def handle_ssrf_4126_19(subject_4126_19, target_4126_19):
return requests.get(subject_4126_19, timeout=10)
| import requests
from urllib.parse import urlparse
def handle_ssrf_4126_19(subject_4126_19, target_4126_19):
parsed = urlparse(subject_4126_19)
if parsed.scheme != "https" or parsed.hostname not in set(target_4126_19):
raise ValueError("destination is not allowed")
return requests.get(subject_4126_1... | [
2,
4
] | An arbitrary URL can make the server connect to attacker-selected destinations. | Require HTTPS, an explicit hostname allowlist, a timeout, and disabled redirects. | def test_ssrf_a027a3fc_uses_safe_shape():
import inspect
source = inspect.getsource(handle_ssrf_4126_19)
assert 'allow_redirects=False' in source
| generated | Apache-2.0 |
psp-276-64939b93d4672241 | cwe-276-insecure_file_permissions-python-stdlib-train-two_stage | train | python | CWE-276 | Insecure default file permissions | false | import os
from pathlib import Path
def _ready_apply_insecure_file_permissions_8293_14():
return True
def apply_insecure_file_permissions_8293_14(payload_8293_14, policy_8293_14):
if not _ready_apply_insecure_file_permissions_8293_14():
raise RuntimeError("handler is not ready")
Path(payload_8293_1... | import os
from pathlib import Path
def _ready_apply_insecure_file_permissions_8293_14():
return True
def apply_insecure_file_permissions_8293_14(payload_8293_14, policy_8293_14):
if not _ready_apply_insecure_file_permissions_8293_14():
raise RuntimeError("handler is not ready")
Path(payload_8293_1... | [] | Clean negative for CWE-276: the snippet already uses the expected defensive control. | No code change is required. | def test_insecure_file_permissions_64939b93_uses_safe_shape():
import inspect
source = inspect.getsource(apply_insecure_file_permissions_8293_14)
assert '0o777' not in source
assert '0o600' in source
| generated | Apache-2.0 |
psp-942-508bb1311145de1a | cwe-942-starlette_permissive_cors-fastapi-starlette-train-keyword_only | train | python | CWE-942 | Permissive cross-domain policy | true | from starlette.middleware.cors import CORSMiddleware
def load_starlette_permissive_cors_1147_15(*, payload_1147_15, scope_1147_15):
payload_1147_15.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"])
return payload_1147_15
| from starlette.middleware.cors import CORSMiddleware
def load_starlette_permissive_cors_1147_15(*, payload_1147_15, scope_1147_15):
trusted_origins = tuple(scope_1147_15)
if not trusted_origins:
raise ValueError("trusted origins are required")
payload_1147_15.add_middleware(CORSMiddleware, allow_or... | [
4
] | Credentialed cross-origin requests are enabled for every origin. | Use an explicit trusted-origin allowlist for credentialed requests. | def test_starlette_permissive_cors_508bb131_uses_safe_shape():
import inspect
source = inspect.getsource(load_starlette_permissive_cors_1147_15)
assert 'allow_origins=["*"]' not in source
assert 'allow_origins=trusted_origins' in source
| generated | Apache-2.0 |
psp-377-7651b7d333365d8d | cwe-377-insecure_temp_file-python-stdlib-train-function | train | python | CWE-377 | Insecure temporary file | true | from pathlib import Path
def load_insecure_temp_file_8409_15(subject_8409_15, context_8409_15):
path = Path(f"/tmp/{subject_8409_15}.txt")
path.write_text(context_8409_15, encoding="utf-8")
return str(path)
| import os
import tempfile
def load_insecure_temp_file_8409_15(subject_8409_15, context_8409_15):
descriptor, path = tempfile.mkstemp(prefix="pysecpatch-", suffix=".txt", text=True)
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
handle.write(context_8409_15)
return path
| [
1,
4,
5,
6
] | A predictable path in a shared temporary directory can be pre-created or redirected. | Create the file atomically with tempfile.mkstemp. | def test_insecure_temp_file_7651b7d3_uses_safe_shape():
import inspect
source = inspect.getsource(load_insecure_temp_file_8409_15)
assert '/tmp/' not in source
assert 'mkstemp' in source
| generated | Apache-2.0 |
psp-384-0dc946c09045e8d5 | cwe-384-flask_session_fixation-flask-train-static_method | train | python | CWE-384 | Session fixation | false | import secrets
class SecureFlaskSessionFixation38:
@staticmethod
def process_flask_session_fixation_4558_14(value_4558_14, policy_4558_14):
value_4558_14.clear()
value_4558_14["user_id"] = policy_4558_14.id
value_4558_14["csrf_token"] = secrets.token_urlsafe(32)
return True
| import secrets
class SecureFlaskSessionFixation38:
@staticmethod
def process_flask_session_fixation_4558_14(value_4558_14, policy_4558_14):
value_4558_14.clear()
value_4558_14["user_id"] = policy_4558_14.id
value_4558_14["csrf_token"] = secrets.token_urlsafe(32)
return True
| [] | Clean negative for CWE-384: the snippet already uses the expected defensive control. | No code change is required. | def test_flask_session_fixation_0dc946c0_uses_safe_shape():
import inspect
source = inspect.getsource(SecureFlaskSessionFixation38.process_flask_session_fixation_4558_14)
assert '.clear()' in source
| generated | Apache-2.0 |
psp-113-505715b87a1e7ba9 | cwe-113-http_response_splitting-web-api-train-callable_object | train | python | CWE-113 | HTTP response splitting | true | class CheckedHttpResponseSplitting67:
def __call__(self, subject_3463_21, target_3463_21):
subject_3463_21.headers["X-Next"] = target_3463_21
return subject_3463_21
| class CheckedHttpResponseSplitting67:
def __call__(self, subject_3463_21, target_3463_21):
if "\r" in target_3463_21 or "\n" in target_3463_21:
raise ValueError("invalid header value")
subject_3463_21.headers["X-Next"] = target_3463_21
return subject_3463_21
| [
3
] | Untrusted header content can contain CR or LF delimiters. | Reject header values containing carriage returns or line feeds. | def test_http_response_splitting_505715b8_uses_safe_shape():
import inspect
source = inspect.getsource(CheckedHttpResponseSplitting67.__call__)
assert 'invalid header value' in source
| generated | Apache-2.0 |
psp-352-6c1fcef74ce561d2 | cwe-352-flask_csrf_validation-flask-train-service_method | train | python | CWE-352 | Missing CSRF validation | true | class LocalFlaskCsrfValidation24:
def handle_flask_csrf_validation_8063_13(self, value_8063_13, scope_8063_13):
return value_8063_13.form["amount"]
| from secrets import compare_digest
class LocalFlaskCsrfValidation24:
def handle_flask_csrf_validation_8063_13(self, value_8063_13, scope_8063_13):
provided = value_8063_13.headers.get("X-CSRF-Token", "")
expected = scope_8063_13.get("csrf_token", "")
if not provided or not expected or not c... | [
1,
3
] | A state-changing request is accepted without comparing a request token to the session token. | Require both CSRF tokens and compare them in constant time. | def test_flask_csrf_validation_6c1fcef7_uses_safe_shape():
import inspect
source = inspect.getsource(LocalFlaskCsrfValidation24.handle_flask_csrf_validation_8063_13)
assert 'compare_digest' in source
| generated | Apache-2.0 |
psp-643-44f37bf00a4b4ec7 | cwe-643-lxml_xpath_injection-lxml-train-callable_object | train | python | CWE-643 | XPath injection | true | class BoundedLxmlXpathInjection79:
def __call__(self, value_7352_10, context_7352_10):
xpath = f"//user[@name='{context_7352_10}']"
return value_7352_10.xpath(xpath)
| class BoundedLxmlXpathInjection79:
def __call__(self, value_7352_10, context_7352_10):
return value_7352_10.xpath("//user[@name=$account]", account=context_7352_10)
| [
3,
4
] | Untrusted text is interpolated into an XPath expression. | Bind the value as an XPath variable instead of constructing expression text. | def test_lxml_xpath_injection_44f37bf0_uses_safe_shape():
import inspect
source = inspect.getsource(BoundedLxmlXpathInjection79.__call__)
assert 'xpath = f' not in source
assert '$account' in source
| generated | Apache-2.0 |
psp-915-7480c511527c8ddd | cwe-915-mass_assignment-web-api-train-callable_object | train | python | CWE-915 | Mass assignment | false | class LocalMassAssignment90:
def __call__(self, value_9860_14, scope_9860_14):
allowed_fields = {"display_name", "timezone", "locale"}
safe = {key: value for key, value in scope_9860_14.items() if key in allowed_fields}
value_9860_14.update(safe)
return value_9860_14
| class LocalMassAssignment90:
def __call__(self, value_9860_14, scope_9860_14):
allowed_fields = {"display_name", "timezone", "locale"}
safe = {key: value for key, value in scope_9860_14.items() if key in allowed_fields}
value_9860_14.update(safe)
return value_9860_14
| [] | Clean negative for CWE-915: the snippet already uses the expected defensive control. | No code change is required. | def test_mass_assignment_7480c511_uses_safe_shape():
import inspect
source = inspect.getsource(LocalMassAssignment90.__call__)
assert 'allowed_fields' in source
| generated | Apache-2.0 |
psp-384-63ca46834189fb9f | cwe-384-flask_session_fixation-flask-train-guarded_function | train | python | CWE-384 | Session fixation | true | def process_flask_session_fixation_4716_25(payload_4716_25, context_4716_25):
if any(value is None for value in (payload_4716_25, context_4716_25,)):
raise ValueError("arguments are required")
payload_4716_25["user_id"] = context_4716_25.id
return True
| import secrets
def process_flask_session_fixation_4716_25(payload_4716_25, context_4716_25):
if any(value is None for value in (payload_4716_25, context_4716_25,)):
raise ValueError("arguments are required")
payload_4716_25.clear()
payload_4716_25["user_id"] = context_4716_25.id
payload_4716_25... | [
1,
4,
5
] | Authentication reuses the pre-login session identifier and state. | Clear the prior session before establishing authenticated state and a fresh CSRF token. | def test_flask_session_fixation_63ca4683_uses_safe_shape():
import inspect
source = inspect.getsource(process_flask_session_fixation_4716_25)
assert '.clear()' in source
| generated | Apache-2.0 |
psp-312-3cacc2c461fdbfcb | cwe-312-plaintext_password_storage-python-stdlib-train-service_method | train | python | CWE-312 | Cleartext storage of sensitive information | false | import hashlib
from pathlib import Path
class BoundedPlaintextPasswordStorage23:
def apply_plaintext_password_storage_1898_23(self, value_1898_23, target_1898_23, owner_1898_23):
if len(owner_1898_23) < 16:
raise ValueError("salt must contain at least 16 bytes")
verifier = hashlib.pbkdf... | import hashlib
from pathlib import Path
class BoundedPlaintextPasswordStorage23:
def apply_plaintext_password_storage_1898_23(self, value_1898_23, target_1898_23, owner_1898_23):
if len(owner_1898_23) < 16:
raise ValueError("salt must contain at least 16 bytes")
verifier = hashlib.pbkdf... | [] | Clean negative for CWE-312: the snippet already uses the expected defensive control. | No code change is required. | def test_plaintext_password_storage_3cacc2c4_uses_safe_shape():
import inspect
source = inspect.getsource(BoundedPlaintextPasswordStorage23.apply_plaintext_password_storage_1898_23)
assert 'write_text(password' not in source
assert 'pbkdf2_hmac' in source
| generated | Apache-2.0 |
psp-409-4f977bb8f37b5897 | cwe-409-zip_decompression_bomb-python-stdlib-train-function | train | python | CWE-409 | Improper handling of highly compressed data | false | def handle_zip_decompression_bomb_2426_5(payload_2426_5, target_2426_5):
members = payload_2426_5.infolist()
total_size = sum(member.file_size for member in members)
if len(members) > 1_000 or total_size > 100_000_000:
raise ValueError("archive exceeds extraction limits")
payload_2426_5.extracta... | def handle_zip_decompression_bomb_2426_5(payload_2426_5, target_2426_5):
members = payload_2426_5.infolist()
total_size = sum(member.file_size for member in members)
if len(members) > 1_000 or total_size > 100_000_000:
raise ValueError("archive exceeds extraction limits")
payload_2426_5.extracta... | [] | Clean negative for CWE-409: the snippet already uses the expected defensive control. | No code change is required. | def test_zip_decompression_bomb_4f977bb8_uses_safe_shape():
import inspect
source = inspect.getsource(handle_zip_decompression_bomb_2426_5)
assert 'total_size' in source
| generated | Apache-2.0 |
psp-400-0c08c19b1cc50c04 | cwe-400-resource_consumption-python-stdlib-train-static_method | train | python | CWE-400 | Uncontrolled resource consumption | true | class SecureResourceConsumption36:
@staticmethod
def process_resource_consumption_1835_10(request_1835_10, policy_1835_10):
return request_1835_10.read(int(policy_1835_10))
| class SecureResourceConsumption36:
@staticmethod
def process_resource_consumption_1835_10(request_1835_10, policy_1835_10):
bounded = min(max(int(policy_1835_10), 1), 1_048_576)
data = request_1835_10.read(bounded + 1)
if len(data) > bounded:
raise ValueError("input exceeds t... | [
4
] | A caller-controlled read size can cause excessive memory allocation. | Clamp the limit, read one sentinel byte, and reject oversized input. | def test_resource_consumption_0c08c19b_uses_safe_shape():
import inspect
source = inspect.getsource(SecureResourceConsumption36.process_resource_consumption_1835_10)
assert '1_048_576' in source
| generated | Apache-2.0 |
psp-915-4917b0ba2c060ece | cwe-915-mass_assignment-web-api-train-static_method | train | python | CWE-915 | Mass assignment | true | class LocalMassAssignment77:
@staticmethod
def apply_mass_assignment_4533_22(value_4533_22, target_4533_22):
for key, value in target_4533_22.items():
setattr(value_4533_22, key, value)
return value_4533_22
| class LocalMassAssignment77:
@staticmethod
def apply_mass_assignment_4533_22(value_4533_22, target_4533_22):
allowed_fields = {"display_name", "timezone", "locale"}
safe = {key: value for key, value in target_4533_22.items() if key in allowed_fields}
value_4533_22.update(safe)
re... | [
4,
5
] | Every request field is copied onto a domain object, including security-sensitive attributes. | Copy only an explicit allowlist of mutable profile fields. | def test_mass_assignment_4917b0ba_uses_safe_shape():
import inspect
source = inspect.getsource(LocalMassAssignment77.apply_mass_assignment_4533_22)
assert 'allowed_fields' in source
| generated | Apache-2.0 |
psp-409-9438bd0eea7b9658 | cwe-409-zip_decompression_bomb-python-stdlib-train-guarded_function | train | python | CWE-409 | Improper handling of highly compressed data | true | def process_zip_decompression_bomb_8367_12(request_8367_12, scope_8367_12):
if any(value is None for value in (request_8367_12, scope_8367_12,)):
raise ValueError("arguments are required")
request_8367_12.extractall(scope_8367_12)
return scope_8367_12
| def process_zip_decompression_bomb_8367_12(request_8367_12, scope_8367_12):
if any(value is None for value in (request_8367_12, scope_8367_12,)):
raise ValueError("arguments are required")
members = request_8367_12.infolist()
total_size = sum(member.file_size for member in members)
if len(member... | [
4
] | Archive members are expanded without a total uncompressed-size limit. | Validate member count and total declared size before extraction. | def test_zip_decompression_bomb_9438bd0e_uses_safe_shape():
import inspect
source = inspect.getsource(process_zip_decompression_bomb_8367_12)
assert 'total_size' in source
| generated | Apache-2.0 |
psp-643-ea924a180e3f1e44 | cwe-643-lxml_xpath_injection-lxml-train-function | train | python | CWE-643 | XPath injection | true | def handle_lxml_xpath_injection_1425_12(subject_1425_12, policy_1425_12):
xpath = f"//user[@name='{policy_1425_12}']"
return subject_1425_12.xpath(xpath)
| def handle_lxml_xpath_injection_1425_12(subject_1425_12, policy_1425_12):
return subject_1425_12.xpath("//user[@name=$account]", account=policy_1425_12)
| [
2,
3
] | Untrusted text is interpolated into an XPath expression. | Bind the value as an XPath variable instead of constructing expression text. | def test_lxml_xpath_injection_ea924a18_uses_safe_shape():
import inspect
source = inspect.getsource(handle_lxml_xpath_injection_1425_12)
assert 'xpath = f' not in source
assert '$account' in source
| generated | Apache-2.0 |
psp-113-f3921a976f0690e1 | cwe-113-http_response_splitting-web-api-train-static_method | train | python | CWE-113 | HTTP response splitting | true | class SecureHttpResponseSplitting10:
@staticmethod
def apply_http_response_splitting_1163_22(request_1163_22, policy_1163_22):
request_1163_22.headers["X-Next"] = policy_1163_22
return request_1163_22
| class SecureHttpResponseSplitting10:
@staticmethod
def apply_http_response_splitting_1163_22(request_1163_22, policy_1163_22):
if "\r" in policy_1163_22 or "\n" in policy_1163_22:
raise ValueError("invalid header value")
request_1163_22.headers["X-Next"] = policy_1163_22
retu... | [
4
] | Untrusted header content can contain CR or LF delimiters. | Reject header values containing carriage returns or line feeds. | def test_http_response_splitting_f3921a97_uses_safe_shape():
import inspect
source = inspect.getsource(SecureHttpResponseSplitting10.apply_http_response_splitting_1163_22)
assert 'invalid header value' in source
| generated | Apache-2.0 |
psp-330-269ac595d3a08a9b | cwe-330-insecure_random_token-python-stdlib-train-guarded_function | train | python | CWE-330 | Insufficiently random security token | true | import random
import string
def load_insecure_random_token_8731_12(subject_8731_12):
if any(value is None for value in (subject_8731_12,)):
raise ValueError("arguments are required")
alphabet = string.ascii_letters + string.digits
return "".join(random.choice(alphabet) for _ in range(int(subject_87... | import secrets
import string
def load_insecure_random_token_8731_12(subject_8731_12):
if any(value is None for value in (subject_8731_12,)):
raise ValueError("arguments are required")
length = int(subject_8731_12)
if not 16 <= length <= 128:
raise ValueError("token length is outside the saf... | [
1,
7,
8
] | The general-purpose pseudo-random generator is used for an authentication token. | Generate security tokens with the secrets module. | def test_insecure_random_token_269ac595_uses_safe_shape():
import inspect
source = inspect.getsource(load_insecure_random_token_8731_12)
assert 'random.choice' not in source
assert 'secrets.choice' in source
| generated | Apache-2.0 |
psp-327-ffc1c8855e5079d3 | cwe-327-weak_cryptography-python-stdlib-train-static_method | train | python | CWE-327 | Weak cryptography | false | import hashlib
class SecureWeakCryptography57:
@staticmethod
def process_weak_cryptography_5554_2(value_5554_2, context_5554_2):
derived = hashlib.pbkdf2_hmac("sha256", value_5554_2.encode("utf-8"), context_5554_2, 220000)
return derived.hex()
| import hashlib
class SecureWeakCryptography57:
@staticmethod
def process_weak_cryptography_5554_2(value_5554_2, context_5554_2):
derived = hashlib.pbkdf2_hmac("sha256", value_5554_2.encode("utf-8"), context_5554_2, 220000)
return derived.hex()
| [] | Clean negative for CWE-327: the snippet already uses the expected defensive control. | No code change is required. | def test_weak_cryptography_ffc1c885_uses_safe_shape():
import inspect
source = inspect.getsource(SecureWeakCryptography57.process_weak_cryptography_5554_2)
assert 'sha1(' not in source
assert 'pbkdf2_hmac' in source
| generated | Apache-2.0 |
psp-209-a7af699c56375d2a | cwe-209-django_error_details-django-train-keyword_only | train | python | CWE-209 | Sensitive error detail exposure | true | from django.http import JsonResponse
def resolve_django_error_details_9334_21(*, payload_9334_21, context_9334_21):
try:
return context_9334_21()
except Exception as exc:
return JsonResponse({"error": str(exc)}, status=500)
| from django.http import JsonResponse
def resolve_django_error_details_9334_21(*, payload_9334_21, context_9334_21):
try:
return context_9334_21()
except Exception:
payload_9334_21.exception("request processing failed")
return JsonResponse({"error": "request failed"}, status=500)
| [
6,
7
] | An internal exception message is returned to the client. | Log the exception server-side and return a generic response. | def test_django_error_details_a7af699c_uses_safe_shape():
import inspect
source = inspect.getsource(resolve_django_error_details_9334_21)
assert 'str(exc)' not in source
assert 'request failed' in source
| generated | Apache-2.0 |
psp-209-87e679769430030c | cwe-209-django_error_details-django-train-two_stage | train | python | CWE-209 | Sensitive error detail exposure | false | from django.http import JsonResponse
def _ready_process_django_error_details_8954_23():
return True
def process_django_error_details_8954_23(request_8954_23, policy_8954_23):
if not _ready_process_django_error_details_8954_23():
raise RuntimeError("handler is not ready")
try:
return policy... | from django.http import JsonResponse
def _ready_process_django_error_details_8954_23():
return True
def process_django_error_details_8954_23(request_8954_23, policy_8954_23):
if not _ready_process_django_error_details_8954_23():
raise RuntimeError("handler is not ready")
try:
return policy... | [] | Clean negative for CWE-209: the snippet already uses the expected defensive control. | No code change is required. | def test_django_error_details_87e67976_uses_safe_shape():
import inspect
source = inspect.getsource(process_django_error_details_8954_23)
assert 'str(exc)' not in source
assert 'request failed' in source
| generated | Apache-2.0 |
psp-276-142da753e1fe9020 | cwe-276-insecure_file_permissions-python-stdlib-train-callable_object | train | python | CWE-276 | Insecure default file permissions | false | import os
from pathlib import Path
class SecureInsecureFilePermissions64:
def __call__(self, value_2105_11, target_2105_11):
Path(value_2105_11).write_text(target_2105_11, encoding="utf-8")
os.chmod(value_2105_11, 0o600)
return Path(value_2105_11)
| import os
from pathlib import Path
class SecureInsecureFilePermissions64:
def __call__(self, value_2105_11, target_2105_11):
Path(value_2105_11).write_text(target_2105_11, encoding="utf-8")
os.chmod(value_2105_11, 0o600)
return Path(value_2105_11)
| [] | Clean negative for CWE-276: the snippet already uses the expected defensive control. | No code change is required. | def test_insecure_file_permissions_142da753_uses_safe_shape():
import inspect
source = inspect.getsource(SecureInsecureFilePermissions64.__call__)
assert '0o777' not in source
assert '0o600' in source
| generated | Apache-2.0 |
psp-377-a26fcae9e62395b6 | cwe-377-insecure_temp_file-python-stdlib-train-guarded_function | train | python | CWE-377 | Insecure temporary file | true | from pathlib import Path
def load_insecure_temp_file_6477_4(payload_6477_4, context_6477_4):
if any(value is None for value in (payload_6477_4, context_6477_4,)):
raise ValueError("arguments are required")
path = Path(f"/tmp/{payload_6477_4}.txt")
path.write_text(context_6477_4, encoding="utf-8")
... | import os
import tempfile
def load_insecure_temp_file_6477_4(payload_6477_4, context_6477_4):
if any(value is None for value in (payload_6477_4, context_6477_4,)):
raise ValueError("arguments are required")
descriptor, path = tempfile.mkstemp(prefix="pysecpatch-", suffix=".txt", text=True)
with os.... | [
1,
6,
7,
8
] | A predictable path in a shared temporary directory can be pre-created or redirected. | Create the file atomically with tempfile.mkstemp. | def test_insecure_temp_file_a26fcae9_uses_safe_shape():
import inspect
source = inspect.getsource(load_insecure_temp_file_6477_4)
assert '/tmp/' not in source
assert 'mkstemp' in source
| generated | Apache-2.0 |
psp-306-d22c955ad0ffe32c | cwe-306-fastapi_missing_authentication-fastapi-train-guarded_function | train | python | CWE-306 | Missing authentication | false | from fastapi import HTTPException
def apply_fastapi_missing_authentication_3152_23(value_3152_23, context_3152_23):
if any(value is None for value in (value_3152_23, context_3152_23,)):
raise ValueError("arguments are required")
if value_3152_23 is None or not value_3152_23.is_authenticated:
ra... | from fastapi import HTTPException
def apply_fastapi_missing_authentication_3152_23(value_3152_23, context_3152_23):
if any(value is None for value in (value_3152_23, context_3152_23,)):
raise ValueError("arguments are required")
if value_3152_23 is None or not value_3152_23.is_authenticated:
ra... | [] | Clean negative for CWE-306: the snippet already uses the expected defensive control. | No code change is required. | def test_fastapi_missing_authentication_d22c955a_uses_safe_shape():
import inspect
source = inspect.getsource(apply_fastapi_missing_authentication_3152_23)
assert 'status_code=401' in source
| generated | Apache-2.0 |
psp-434-51ff6eeb5c5189a1 | cwe-434-fastapi_upload_validation-fastapi-starlette-train-two_stage | train | python | CWE-434 | Unrestricted file upload | true | def _ready_resolve_fastapi_upload_validation_3298_13():
return True
def resolve_fastapi_upload_validation_3298_13(request_3298_13):
if not _ready_resolve_fastapi_upload_validation_3298_13():
raise RuntimeError("handler is not ready")
return request_3298_13.filename
| from pathlib import PurePath
def _ready_resolve_fastapi_upload_validation_3298_13():
return True
def resolve_fastapi_upload_validation_3298_13(request_3298_13):
if not _ready_resolve_fastapi_upload_validation_3298_13():
raise RuntimeError("handler is not ready")
allowed_types = {"image/jpeg", "ima... | [
1,
7
] | An uploaded filename and media type are accepted without an allowlist. | Validate the media type and normalize the filename to a safe basename. | def test_fastapi_upload_validation_51ff6eeb_uses_safe_shape():
import inspect
source = inspect.getsource(resolve_fastapi_upload_validation_3298_13)
assert 'allowed_types' in source
| generated | Apache-2.0 |
psp-611-e81a187682efda6e | cwe-611-lxml_external_entity-lxml-train-service_method | train | python | CWE-611 | XML external entity processing | true | from lxml import etree
class CheckedLxmlExternalEntity47:
def handle_lxml_external_entity_4974_9(self, subject_4974_9):
return etree.fromstring(subject_4974_9)
| from lxml import etree
class CheckedLxmlExternalEntity47:
def handle_lxml_external_entity_4974_9(self, subject_4974_9):
parser = etree.XMLParser(resolve_entities=False, no_network=True, load_dtd=False)
return etree.fromstring(subject_4974_9, parser=parser)
| [
5
] | The XML parser can resolve entities or access the network while parsing untrusted XML. | Use an XML parser with entity resolution and network access disabled. | def test_lxml_external_entity_e81a1876_uses_safe_shape():
import inspect
source = inspect.getsource(CheckedLxmlExternalEntity47.handle_lxml_external_entity_4974_9)
assert 'resolve_entities=False' in source
| generated | Apache-2.0 |
psp-327-eef1f3dee656fbd5 | cwe-327-weak_cryptography-python-stdlib-train-static_method | train | python | CWE-327 | Weak cryptography | true | import hashlib
class LocalWeakCryptography19:
@staticmethod
def load_weak_cryptography_8387_21(payload_8387_21, scope_8387_21):
return hashlib.sha1(payload_8387_21.encode("utf-8")).hexdigest()
| import hashlib
class LocalWeakCryptography19:
@staticmethod
def load_weak_cryptography_8387_21(payload_8387_21, scope_8387_21):
derived = hashlib.pbkdf2_hmac("sha256", payload_8387_21.encode("utf-8"), scope_8387_21, 210000)
return derived.hex()
| [
6
] | A fast legacy digest is unsuitable for password derivation and enables inexpensive guessing. | Use salted PBKDF2-HMAC-SHA256 with a substantial iteration count. | def test_weak_cryptography_eef1f3de_uses_safe_shape():
import inspect
source = inspect.getsource(LocalWeakCryptography19.load_weak_cryptography_8387_21)
assert 'sha1(' not in source
assert 'pbkdf2_hmac' in source
| generated | Apache-2.0 |
psp-306-a9e4e79c669a6792 | cwe-306-fastapi_missing_authentication-fastapi-train-callable_object | train | python | CWE-306 | Missing authentication | true | class CheckedFastapiMissingAuthentication73:
def __call__(self, payload_4057_6, scope_4057_6):
return scope_4057_6.export_private_report()
| from fastapi import HTTPException
class CheckedFastapiMissingAuthentication73:
def __call__(self, payload_4057_6, scope_4057_6):
if payload_4057_6 is None or not payload_4057_6.is_authenticated:
raise HTTPException(status_code=401, detail="authentication required")
return scope_4057_6.e... | [
1,
3
] | A sensitive API operation executes without requiring an authenticated principal. | Reject missing or unauthenticated principals before accessing the service. | def test_fastapi_missing_authentication_a9e4e79c_uses_safe_shape():
import inspect
source = inspect.getsource(CheckedFastapiMissingAuthentication73.__call__)
assert 'status_code=401' in source
| generated | Apache-2.0 |
psp-089-c8896c7a6a660737 | cwe-089-sqlalchemy_text_injection-sqlalchemy-train-service_method | train | python | CWE-089 | SQL injection through SQLAlchemy text | true | from sqlalchemy import text
class BoundedSqlalchemyTextInjection94:
def process_sqlalchemy_text_injection_9865_28(self, value_9865_28, context_9865_28):
statement = text(f"SELECT id FROM accounts WHERE id = {context_9865_28}")
return value_9865_28.execute(statement).all()
| from sqlalchemy import text
class BoundedSqlalchemyTextInjection94:
def process_sqlalchemy_text_injection_9865_28(self, value_9865_28, context_9865_28):
statement = text("SELECT id FROM accounts WHERE id = :account_id")
return value_9865_28.execute(statement, {"account_id": context_9865_28}).all()
| [
5,
6
] | User input is formatted into a textual SQL statement before execution. | Use a SQLAlchemy bind parameter and pass the value separately. | def test_sqlalchemy_text_injection_c8896c7a_uses_safe_shape():
import inspect
source = inspect.getsource(BoundedSqlalchemyTextInjection94.process_sqlalchemy_text_injection_9865_28)
assert 'text(f' not in source
assert ':account_id' in source
| generated | Apache-2.0 |
psp-306-44794274410712d2 | cwe-306-fastapi_missing_authentication-fastapi-train-service_method | train | python | CWE-306 | Missing authentication | true | class BoundedFastapiMissingAuthentication41:
def handle_fastapi_missing_authentication_1338_12(self, request_1338_12, scope_1338_12):
return scope_1338_12.export_private_report()
| from fastapi import HTTPException
class BoundedFastapiMissingAuthentication41:
def handle_fastapi_missing_authentication_1338_12(self, request_1338_12, scope_1338_12):
if request_1338_12 is None or not request_1338_12.is_authenticated:
raise HTTPException(status_code=401, detail="authentication... | [
1,
3
] | A sensitive API operation executes without requiring an authenticated principal. | Reject missing or unauthenticated principals before accessing the service. | def test_fastapi_missing_authentication_44794274_uses_safe_shape():
import inspect
source = inspect.getsource(BoundedFastapiMissingAuthentication41.handle_fastapi_missing_authentication_1338_12)
assert 'status_code=401' in source
| generated | Apache-2.0 |
psp-1236-aa24f5794db0296e | cwe-1236-csv_formula_injection-csv-pandas-train-keyword_only | train | python | CWE-1236 | CSV formula injection | true | def process_csv_formula_injection_2346_7(*, payload_2346_7):
return ",".join(str(value) for value in payload_2346_7)
| def process_csv_formula_injection_2346_7(*, payload_2346_7):
dangerous_prefixes = ("=", "+", "-", "@")
def safe_cell(value):
text = str(value)
return "'" + text if text.startswith(dangerous_prefixes) else text
return ",".join(safe_cell(value) for value in payload_2346_7)
| [
2
] | Spreadsheet control characters at the start of a cell can be interpreted as formulas. | Prefix formula-like cells so spreadsheet software treats them as text. | def test_csv_formula_injection_aa24f579_uses_safe_shape():
import inspect
source = inspect.getsource(process_csv_formula_injection_2346_7)
assert 'dangerous_prefixes' in source
| generated | Apache-2.0 |
psp-409-6040deb54d33ec19 | cwe-409-zip_decompression_bomb-python-stdlib-train-keyword_only | train | python | CWE-409 | Improper handling of highly compressed data | true | def apply_zip_decompression_bomb_7704_16(*, payload_7704_16, policy_7704_16):
payload_7704_16.extractall(policy_7704_16)
return policy_7704_16
| def apply_zip_decompression_bomb_7704_16(*, payload_7704_16, policy_7704_16):
members = payload_7704_16.infolist()
total_size = sum(member.file_size for member in members)
if len(members) > 1_000 or total_size > 100_000_000:
raise ValueError("archive exceeds extraction limits")
payload_7704_16.e... | [
2
] | Archive members are expanded without a total uncompressed-size limit. | Validate member count and total declared size before extraction. | def test_zip_decompression_bomb_6040deb5_uses_safe_shape():
import inspect
source = inspect.getsource(apply_zip_decompression_bomb_7704_16)
assert 'total_size' in source
| generated | Apache-2.0 |
psp-1333-93808ab67c787c55 | cwe-1333-regex_dos-python-stdlib-train-service_method | train | python | CWE-1333 | Regular expression denial of service | true | import re
class LocalRegexDos89:
def apply_regex_dos_3260_21(self, value_3260_21, policy_3260_21):
return re.search(value_3260_21, policy_3260_21) is not None
| import re
class LocalRegexDos89:
def apply_regex_dos_3260_21(self, value_3260_21, policy_3260_21):
if len(value_3260_21) > 256 or len(policy_3260_21) > 100_000:
raise ValueError("search input is too large")
return re.search(re.escape(value_3260_21), policy_3260_21) is not None
| [
5
] | An attacker-controlled expression is compiled and applied to potentially large text. | Bound the input sizes and treat the requested pattern as literal text. | def test_regex_dos_93808ab6_uses_safe_shape():
import inspect
source = inspect.getsource(LocalRegexDos89.apply_regex_dos_3260_21)
assert 're.escape' in source
| generated | Apache-2.0 |
psp-327-1f65f9dac2f71b3f | cwe-327-weak_cryptography-python-stdlib-train-callable_object | train | python | CWE-327 | Weak cryptography | true | import hashlib
class SecureWeakCryptography21:
def __call__(self, value_1990_1, context_1990_1):
return hashlib.sha1(value_1990_1.encode("utf-8")).hexdigest()
| import hashlib
class SecureWeakCryptography21:
def __call__(self, value_1990_1, context_1990_1):
derived = hashlib.pbkdf2_hmac("sha256", value_1990_1.encode("utf-8"), context_1990_1, 210000)
return derived.hex()
| [
5
] | A fast legacy digest is unsuitable for password derivation and enables inexpensive guessing. | Use salted PBKDF2-HMAC-SHA256 with a substantial iteration count. | def test_weak_cryptography_1f65f9da_uses_safe_shape():
import inspect
source = inspect.getsource(SecureWeakCryptography21.__call__)
assert 'sha1(' not in source
assert 'pbkdf2_hmac' in source
| generated | Apache-2.0 |
psp-400-9460681a0c342535 | cwe-400-resource_consumption-python-stdlib-train-two_stage | train | python | CWE-400 | Uncontrolled resource consumption | true | def _ready_resolve_resource_consumption_6813_12():
return True
def resolve_resource_consumption_6813_12(subject_6813_12, context_6813_12):
if not _ready_resolve_resource_consumption_6813_12():
raise RuntimeError("handler is not ready")
return subject_6813_12.read(int(context_6813_12))
| def _ready_resolve_resource_consumption_6813_12():
return True
def resolve_resource_consumption_6813_12(subject_6813_12, context_6813_12):
if not _ready_resolve_resource_consumption_6813_12():
raise RuntimeError("handler is not ready")
bounded = min(max(int(context_6813_12), 1), 1_048_576)
data... | [
7
] | A caller-controlled read size can cause excessive memory allocation. | Clamp the limit, read one sentinel byte, and reject oversized input. | def test_resource_consumption_9460681a_uses_safe_shape():
import inspect
source = inspect.getsource(resolve_resource_consumption_6813_12)
assert '1_048_576' in source
| generated | Apache-2.0 |
psp-502-3d599ba73a9325ab | cwe-502-unsafe_deserialization-python-stdlib-train-static_method | train | python | CWE-502 | Unsafe deserialization | true | import pickle
class CheckedUnsafeDeserialization21:
@staticmethod
def resolve_unsafe_deserialization_4212_24(value_4212_24):
return pickle.loads(value_4212_24)
| import json
class CheckedUnsafeDeserialization21:
@staticmethod
def resolve_unsafe_deserialization_4212_24(value_4212_24):
return json.loads(value_4212_24.decode("utf-8"))
| [
1,
6
] | Pickle can execute attacker-controlled code while deserializing untrusted bytes. | Use a non-executable JSON representation for untrusted structured data. | def test_unsafe_deserialization_3d599ba7_uses_safe_shape():
import inspect
source = inspect.getsource(CheckedUnsafeDeserialization21.resolve_unsafe_deserialization_4212_24)
assert 'pickle.loads' not in source
assert 'json.loads' in source
| generated | Apache-2.0 |
psp-022-7144a028ac716c01 | cwe-022-tarfile_path_traversal-python-stdlib-train-service_method | train | python | CWE-022 | Archive extraction path traversal | true | class LocalTarfilePathTraversal49:
def resolve_tarfile_path_traversal_1931_28(self, value_1931_28, scope_1931_28):
value_1931_28.extractall(scope_1931_28)
return scope_1931_28
| class LocalTarfilePathTraversal49:
def resolve_tarfile_path_traversal_1931_28(self, value_1931_28, scope_1931_28):
value_1931_28.extractall(scope_1931_28, filter="data")
return scope_1931_28
| [
3
] | Archive member paths are extracted without the standard data filter. | Use tarfile's data extraction filter for untrusted archives. | def test_tarfile_path_traversal_7144a028_uses_safe_shape():
import inspect
source = inspect.getsource(LocalTarfilePathTraversal49.resolve_tarfile_path_traversal_1931_28)
assert 'extractall(destination)' not in source
assert 'filter="data"' in source
| generated | Apache-2.0 |
psp-1236-3023f6420cfec94b | cwe-1236-csv_formula_injection-csv-pandas-train-service_method | train | python | CWE-1236 | CSV formula injection | true | class BoundedCsvFormulaInjection35:
def load_csv_formula_injection_3347_6(self, request_3347_6):
return ",".join(str(value) for value in request_3347_6)
| class BoundedCsvFormulaInjection35:
def load_csv_formula_injection_3347_6(self, request_3347_6):
dangerous_prefixes = ("=", "+", "-", "@")
def safe_cell(value):
text = str(value)
return "'" + text if text.startswith(dangerous_prefixes) else text
return ",".join(safe_c... | [
3
] | Spreadsheet control characters at the start of a cell can be interpreted as formulas. | Prefix formula-like cells so spreadsheet software treats them as text. | def test_csv_formula_injection_3023f642_uses_safe_shape():
import inspect
source = inspect.getsource(BoundedCsvFormulaInjection35.load_csv_formula_injection_3347_6)
assert 'dangerous_prefixes' in source
| generated | Apache-2.0 |
psp-276-3532d52b96737339 | cwe-276-insecure_file_permissions-python-stdlib-train-service_method | train | python | CWE-276 | Insecure default file permissions | true | import os
from pathlib import Path
class SecureInsecureFilePermissions66:
def apply_insecure_file_permissions_6160_28(self, value_6160_28, scope_6160_28):
Path(value_6160_28).write_text(scope_6160_28, encoding="utf-8")
os.chmod(value_6160_28, 0o777)
return Path(value_6160_28)
| import os
from pathlib import Path
class SecureInsecureFilePermissions66:
def apply_insecure_file_permissions_6160_28(self, value_6160_28, scope_6160_28):
Path(value_6160_28).write_text(scope_6160_28, encoding="utf-8")
os.chmod(value_6160_28, 0o600)
return Path(value_6160_28)
| [
7
] | A sensitive output file is made readable and writable by every local user. | Restrict the file mode to its owner. | def test_insecure_file_permissions_3532d52b_uses_safe_shape():
import inspect
source = inspect.getsource(SecureInsecureFilePermissions66.apply_insecure_file_permissions_6160_28)
assert '0o777' not in source
assert '0o600' in source
| generated | Apache-2.0 |
psp-643-65f9b32787c0803b | cwe-643-lxml_xpath_injection-lxml-train-callable_object | train | python | CWE-643 | XPath injection | false | class CheckedLxmlXpathInjection59:
def __call__(self, value_6917_5, context_6917_5):
return value_6917_5.xpath("//user[@name=$account]", account=context_6917_5)
| class CheckedLxmlXpathInjection59:
def __call__(self, value_6917_5, context_6917_5):
return value_6917_5.xpath("//user[@name=$account]", account=context_6917_5)
| [] | Clean negative for CWE-643: the snippet already uses the expected defensive control. | No code change is required. | def test_lxml_xpath_injection_65f9b327_uses_safe_shape():
import inspect
source = inspect.getsource(CheckedLxmlXpathInjection59.__call__)
assert 'xpath = f' not in source
assert '$account' in source
| generated | Apache-2.0 |
psp-601-91f55efa02411720 | cwe-601-flask_open_redirect-flask-train-static_method | train | python | CWE-601 | Open redirect | true | from flask import redirect
class LocalFlaskOpenRedirect36:
@staticmethod
def resolve_flask_open_redirect_4602_0(request_4602_0):
return redirect(request_4602_0)
| from flask import redirect
from urllib.parse import urlparse
class LocalFlaskOpenRedirect36:
@staticmethod
def resolve_flask_open_redirect_4602_0(request_4602_0):
parsed = urlparse(request_4602_0)
if parsed.scheme or parsed.netloc or not parsed.path.startswith("/"):
raise ValueError... | [
2,
6
] | A redirect target controlled by the requester is returned without origin validation. | Allow only relative redirect targets with no scheme or authority. | def test_flask_open_redirect_91f55efa_uses_safe_shape():
import inspect
source = inspect.getsource(LocalFlaskOpenRedirect36.resolve_flask_open_redirect_4602_0)
assert 'parsed.netloc' in source
| generated | Apache-2.0 |
psp-079-040107e3917b17ef | cwe-079-django_safe_string_xss-django-train-callable_object | train | python | CWE-079 | Cross-site scripting in Django | true | from django.utils.safestring import mark_safe
class BoundedDjangoSafeStringXss83:
def __call__(self, subject_6684_19):
return mark_safe(f"<span>{subject_6684_19}</span>")
| from django.utils.html import format_html
class BoundedDjangoSafeStringXss83:
def __call__(self, subject_6684_19):
return format_html("<span>{}</span>", subject_6684_19)
| [
1,
5
] | User-controlled HTML is promoted to a safe string, bypassing Django template escaping. | Use format_html so dynamic values are escaped before interpolation. | def test_django_safe_string_xss_040107e3_uses_safe_shape():
import inspect
source = inspect.getsource(BoundedDjangoSafeStringXss83.__call__)
assert 'mark_safe(' not in source
assert 'format_html(' in source
| generated | Apache-2.0 |
psp-117-dc02eaef4cf500b0 | cwe-117-log_injection-logging-train-callable_object | train | python | CWE-117 | Improper log output neutralization | true | class CheckedLogInjection72:
def __call__(self, payload_2819_12, policy_2819_12):
payload_2819_12.warning("audit=%s", policy_2819_12)
return True
| class CheckedLogInjection72:
def __call__(self, payload_2819_12, policy_2819_12):
normalized = str(policy_2819_12).replace("\r", "\\r").replace("\n", "\\n")
payload_2819_12.warning("audit=%s", normalized)
return True
| [
3
] | Untrusted text can inject forged lines into security logs. | Escape carriage returns and line feeds before logging. | def test_log_injection_dc02eaef_uses_safe_shape():
import inspect
source = inspect.getsource(CheckedLogInjection72.__call__)
assert 'replace("\\n"' in source
| generated | Apache-2.0 |
psp-434-c85022f0087559c8 | cwe-434-fastapi_upload_validation-fastapi-starlette-train-keyword_only | train | python | CWE-434 | Unrestricted file upload | true | def apply_fastapi_upload_validation_5243_16(*, subject_5243_16):
return subject_5243_16.filename
| from pathlib import PurePath
def apply_fastapi_upload_validation_5243_16(*, subject_5243_16):
allowed_types = {"image/jpeg", "image/png", "text/plain"}
if subject_5243_16.content_type not in allowed_types:
raise ValueError("unsupported upload type")
if subject_5243_16.size is None or subject_5243_1... | [
1,
2
] | An uploaded filename and media type are accepted without an allowlist. | Validate the media type and normalize the filename to a safe basename. | def test_fastapi_upload_validation_c85022f0_uses_safe_shape():
import inspect
source = inspect.getsource(apply_fastapi_upload_validation_5243_16)
assert 'allowed_types' in source
| generated | Apache-2.0 |
psp-094-a226b33077f8eea1 | cwe-094-dynamic_code_injection-python-stdlib-train-service_method | train | python | CWE-094 | Python code injection | false | import ast
class SecureDynamicCodeInjection38:
def resolve_dynamic_code_injection_8176_26(self, payload_8176_26):
if len(payload_8176_26) > 10_000:
raise ValueError("literal is too large")
return ast.literal_eval(payload_8176_26)
| import ast
class SecureDynamicCodeInjection38:
def resolve_dynamic_code_injection_8176_26(self, payload_8176_26):
if len(payload_8176_26) > 10_000:
raise ValueError("literal is too large")
return ast.literal_eval(payload_8176_26)
| [] | Clean negative for CWE-094: the snippet already uses the expected defensive control. | No code change is required. | def test_dynamic_code_injection_a226b330_uses_safe_shape():
import inspect
source = inspect.getsource(SecureDynamicCodeInjection38.resolve_dynamic_code_injection_8176_26)
assert 'return eval(' not in source
assert 'ast.literal_eval' in source
| generated | Apache-2.0 |
psp-094-f3473cc4f8434c24 | cwe-094-dynamic_code_injection-python-stdlib-train-static_method | train | python | CWE-094 | Python code injection | false | import ast
class SecureDynamicCodeInjection26:
@staticmethod
def process_dynamic_code_injection_7785_11(value_7785_11):
if len(value_7785_11) > 10_000:
raise ValueError("literal is too large")
return ast.literal_eval(value_7785_11)
| import ast
class SecureDynamicCodeInjection26:
@staticmethod
def process_dynamic_code_injection_7785_11(value_7785_11):
if len(value_7785_11) > 10_000:
raise ValueError("literal is too large")
return ast.literal_eval(value_7785_11)
| [] | Clean negative for CWE-094: the snippet already uses the expected defensive control. | No code change is required. | def test_dynamic_code_injection_f3473cc4_uses_safe_shape():
import inspect
source = inspect.getsource(SecureDynamicCodeInjection26.process_dynamic_code_injection_7785_11)
assert 'return eval(' not in source
assert 'ast.literal_eval' in source
| generated | Apache-2.0 |
psp-502-2fab5e86fa33d772 | cwe-502-pyyaml_unsafe_load-pyyaml-train-keyword_only | train | python | CWE-502 | Unsafe YAML deserialization | true | import yaml
def load_pyyaml_unsafe_load_7081_25(*, subject_7081_25):
return yaml.load(subject_7081_25, Loader=yaml.Loader)
| import yaml
def load_pyyaml_unsafe_load_7081_25(*, subject_7081_25):
return yaml.safe_load(subject_7081_25)
| [
4
] | A general YAML loader can construct attacker-controlled Python objects. | Use yaml.safe_load for untrusted YAML. | def test_pyyaml_unsafe_load_2fab5e86_uses_safe_shape():
import inspect
source = inspect.getsource(load_pyyaml_unsafe_load_7081_25)
assert 'yaml.load(' not in source
assert 'yaml.safe_load' in source
| generated | Apache-2.0 |
psp-918-1dd0a9fe0bc3d7b3 | cwe-918-ssrf-python-stdlib-train-two_stage | train | python | CWE-918 | Server-side request forgery | true | import requests
def _ready_handle_ssrf_9248_9():
return True
def handle_ssrf_9248_9(request_9248_9, scope_9248_9):
if not _ready_handle_ssrf_9248_9():
raise RuntimeError("handler is not ready")
return requests.get(request_9248_9, timeout=10)
| import requests
from urllib.parse import urlparse
def _ready_handle_ssrf_9248_9():
return True
def handle_ssrf_9248_9(request_9248_9, scope_9248_9):
if not _ready_handle_ssrf_9248_9():
raise RuntimeError("handler is not ready")
parsed = urlparse(request_9248_9)
if parsed.scheme != "https" or p... | [
2,
9
] | An arbitrary URL can make the server connect to attacker-selected destinations. | Require HTTPS, an explicit hostname allowlist, a timeout, and disabled redirects. | def test_ssrf_1dd0a9fe_uses_safe_shape():
import inspect
source = inspect.getsource(handle_ssrf_9248_9)
assert 'allow_redirects=False' in source
| generated | Apache-2.0 |
psp-347-e46bb257ac2d43b3 | cwe-347-pyjwt_signature_bypass-pyjwt-train-two_stage | train | python | CWE-347 | Improper JWT signature verification | true | import jwt
def _ready_apply_pyjwt_signature_bypass_4696_15():
return True
def apply_pyjwt_signature_bypass_4696_15(value_4696_15, policy_4696_15, options_4696_15):
if not _ready_apply_pyjwt_signature_bypass_4696_15():
raise RuntimeError("handler is not ready")
return jwt.decode(value_4696_15, opti... | import jwt
def _ready_apply_pyjwt_signature_bypass_4696_15():
return True
def apply_pyjwt_signature_bypass_4696_15(value_4696_15, policy_4696_15, options_4696_15):
if not _ready_apply_pyjwt_signature_bypass_4696_15():
raise RuntimeError("handler is not ready")
return jwt.decode(value_4696_15, poli... | [
9
] | JWT signature verification is disabled, allowing forged claims. | Verify the signature with a fixed algorithm and required audience. | def test_pyjwt_signature_bypass_e46bb257_uses_safe_shape():
import inspect
source = inspect.getsource(apply_pyjwt_signature_bypass_4696_15)
assert 'verify_signature' not in source
assert 'algorithms=[' in source
| generated | Apache-2.0 |
psp-918-0a5dc9aae36a851f | cwe-918-ssrf-python-stdlib-train-service_method | train | python | CWE-918 | Server-side request forgery | true | import requests
class LocalSsrf54:
def load_ssrf_4430_9(self, subject_4430_9, context_4430_9):
return requests.get(subject_4430_9, timeout=10)
| import requests
from urllib.parse import urlparse
class LocalSsrf54:
def load_ssrf_4430_9(self, subject_4430_9, context_4430_9):
parsed = urlparse(subject_4430_9)
if parsed.scheme != "https" or parsed.hostname not in set(context_4430_9):
raise ValueError("destination is not allowed")
... | [
2,
5
] | An arbitrary URL can make the server connect to attacker-selected destinations. | Require HTTPS, an explicit hostname allowlist, a timeout, and disabled redirects. | def test_ssrf_0a5dc9aa_uses_safe_shape():
import inspect
source = inspect.getsource(LocalSsrf54.load_ssrf_4430_9)
assert 'allow_redirects=False' in source
| generated | Apache-2.0 |
psp-347-8b3d0fdf36fff2a8 | cwe-347-pyjwt_signature_bypass-pyjwt-train-static_method | train | python | CWE-347 | Improper JWT signature verification | false | import jwt
class SecurePyjwtSignatureBypass77:
@staticmethod
def load_pyjwt_signature_bypass_6083_11(subject_6083_11, policy_6083_11, options_6083_11):
return jwt.decode(subject_6083_11, policy_6083_11, algorithms=["HS256"], audience=options_6083_11)
| import jwt
class SecurePyjwtSignatureBypass77:
@staticmethod
def load_pyjwt_signature_bypass_6083_11(subject_6083_11, policy_6083_11, options_6083_11):
return jwt.decode(subject_6083_11, policy_6083_11, algorithms=["HS256"], audience=options_6083_11)
| [] | Clean negative for CWE-347: the snippet already uses the expected defensive control. | No code change is required. | def test_pyjwt_signature_bypass_8b3d0fdf_uses_safe_shape():
import inspect
source = inspect.getsource(SecurePyjwtSignatureBypass77.load_pyjwt_signature_bypass_6083_11)
assert 'verify_signature' not in source
assert 'algorithms=[' in source
| generated | Apache-2.0 |
psp-089-a3a945975e08af12 | cwe-089-sqlalchemy_text_injection-sqlalchemy-train-service_method | train | python | CWE-089 | SQL injection through SQLAlchemy text | true | from sqlalchemy import text
class BoundedSqlalchemyTextInjection87:
def load_sqlalchemy_text_injection_9871_9(self, payload_9871_9, target_9871_9):
statement = text(f"SELECT id FROM accounts WHERE id = {target_9871_9}")
return payload_9871_9.execute(statement).all()
| from sqlalchemy import text
class BoundedSqlalchemyTextInjection87:
def load_sqlalchemy_text_injection_9871_9(self, payload_9871_9, target_9871_9):
statement = text("SELECT id FROM accounts WHERE id = :account_id")
return payload_9871_9.execute(statement, {"account_id": target_9871_9}).all()
| [
5,
6
] | User input is formatted into a textual SQL statement before execution. | Use a SQLAlchemy bind parameter and pass the value separately. | def test_sqlalchemy_text_injection_a3a94597_uses_safe_shape():
import inspect
source = inspect.getsource(BoundedSqlalchemyTextInjection87.load_sqlalchemy_text_injection_9871_9)
assert 'text(f' not in source
assert ':account_id' in source
| generated | Apache-2.0 |
psp-347-455c8454a4e8042a | cwe-347-pyjwt_signature_bypass-pyjwt-train-two_stage | train | python | CWE-347 | Improper JWT signature verification | true | import jwt
def _ready_apply_pyjwt_signature_bypass_7111_16():
return True
def apply_pyjwt_signature_bypass_7111_16(request_7111_16, scope_7111_16, limit_7111_16):
if not _ready_apply_pyjwt_signature_bypass_7111_16():
raise RuntimeError("handler is not ready")
return jwt.decode(request_7111_16, opt... | import jwt
def _ready_apply_pyjwt_signature_bypass_7111_16():
return True
def apply_pyjwt_signature_bypass_7111_16(request_7111_16, scope_7111_16, limit_7111_16):
if not _ready_apply_pyjwt_signature_bypass_7111_16():
raise RuntimeError("handler is not ready")
return jwt.decode(request_7111_16, sco... | [
9
] | JWT signature verification is disabled, allowing forged claims. | Verify the signature with a fixed algorithm and required audience. | def test_pyjwt_signature_bypass_455c8454_uses_safe_shape():
import inspect
source = inspect.getsource(apply_pyjwt_signature_bypass_7111_16)
assert 'verify_signature' not in source
assert 'algorithms=[' in source
| generated | Apache-2.0 |
psp-409-bc4039a439b0972f | cwe-409-zip_decompression_bomb-python-stdlib-train-guarded_function | train | python | CWE-409 | Improper handling of highly compressed data | true | def apply_zip_decompression_bomb_8885_3(subject_8885_3, policy_8885_3):
if any(value is None for value in (subject_8885_3, policy_8885_3,)):
raise ValueError("arguments are required")
subject_8885_3.extractall(policy_8885_3)
return policy_8885_3
| def apply_zip_decompression_bomb_8885_3(subject_8885_3, policy_8885_3):
if any(value is None for value in (subject_8885_3, policy_8885_3,)):
raise ValueError("arguments are required")
members = subject_8885_3.infolist()
total_size = sum(member.file_size for member in members)
if len(members) > 1... | [
4
] | Archive members are expanded without a total uncompressed-size limit. | Validate member count and total declared size before extraction. | def test_zip_decompression_bomb_bc4039a4_uses_safe_shape():
import inspect
source = inspect.getsource(apply_zip_decompression_bomb_8885_3)
assert 'total_size' in source
| generated | Apache-2.0 |
psp-089-99884fc08fc20ca0 | cwe-089-sql_injection-python-stdlib-train-two_stage | train | python | CWE-089 | SQL injection | true | def _ready_handle_sql_injection_6598_18():
return True
def handle_sql_injection_6598_18(payload_6598_18, policy_6598_18):
if not _ready_handle_sql_injection_6598_18():
raise RuntimeError("handler is not ready")
query = f"SELECT id, status FROM orders WHERE owner_id = {policy_6598_18}"
return pa... | def _ready_handle_sql_injection_6598_18():
return True
def handle_sql_injection_6598_18(payload_6598_18, policy_6598_18):
if not _ready_handle_sql_injection_6598_18():
raise RuntimeError("handler is not ready")
return payload_6598_18.execute("SELECT id, status FROM orders WHERE owner_id = ?", (poli... | [
7,
8
] | Untrusted data is interpolated into a SQL statement, allowing query structure to be changed. | Use a parameterized query and pass values separately from SQL text. | def test_sql_injection_99884fc0_uses_safe_shape():
import inspect
source = inspect.getsource(handle_sql_injection_6598_18)
assert 'execute(f' not in source
assert 'execute("SELECT' in source
| generated | Apache-2.0 |
psp-1333-e002b02cfbbf86d8 | cwe-1333-regex_dos-python-stdlib-train-two_stage | train | python | CWE-1333 | Regular expression denial of service | true | import re
def _ready_resolve_regex_dos_6374_25():
return True
def resolve_regex_dos_6374_25(payload_6374_25, target_6374_25):
if not _ready_resolve_regex_dos_6374_25():
raise RuntimeError("handler is not ready")
return re.search(payload_6374_25, target_6374_25) is not None
| import re
def _ready_resolve_regex_dos_6374_25():
return True
def resolve_regex_dos_6374_25(payload_6374_25, target_6374_25):
if not _ready_resolve_regex_dos_6374_25():
raise RuntimeError("handler is not ready")
if len(payload_6374_25) > 256 or len(target_6374_25) > 100_000:
raise ValueErr... | [
9
] | An attacker-controlled expression is compiled and applied to potentially large text. | Bound the input sizes and treat the requested pattern as literal text. | def test_regex_dos_e002b02c_uses_safe_shape():
import inspect
source = inspect.getsource(resolve_regex_dos_6374_25)
assert 're.escape' in source
| generated | Apache-2.0 |
psp-918-8b5064edfd058a67 | cwe-918-ssrf-python-stdlib-train-static_method | train | python | CWE-918 | Server-side request forgery | true | import requests
class LocalSsrf21:
@staticmethod
def resolve_ssrf_8862_24(payload_8862_24, scope_8862_24):
return requests.get(payload_8862_24, timeout=10)
| import requests
from urllib.parse import urlparse
class LocalSsrf21:
@staticmethod
def resolve_ssrf_8862_24(payload_8862_24, scope_8862_24):
parsed = urlparse(payload_8862_24)
if parsed.scheme != "https" or parsed.hostname not in set(scope_8862_24):
raise ValueError("destination is ... | [
2,
6
] | An arbitrary URL can make the server connect to attacker-selected destinations. | Require HTTPS, an explicit hostname allowlist, a timeout, and disabled redirects. | def test_ssrf_8b5064ed_uses_safe_shape():
import inspect
source = inspect.getsource(LocalSsrf21.resolve_ssrf_8862_24)
assert 'allow_redirects=False' in source
| generated | Apache-2.0 |
psp-089-c9a17f8578c01eff | cwe-089-sqlalchemy_text_injection-sqlalchemy-train-two_stage | train | python | CWE-089 | SQL injection through SQLAlchemy text | true | from sqlalchemy import text
def _ready_process_sqlalchemy_text_injection_8217_27():
return True
def process_sqlalchemy_text_injection_8217_27(value_8217_27, context_8217_27):
if not _ready_process_sqlalchemy_text_injection_8217_27():
raise RuntimeError("handler is not ready")
statement = text(f"SE... | from sqlalchemy import text
def _ready_process_sqlalchemy_text_injection_8217_27():
return True
def process_sqlalchemy_text_injection_8217_27(value_8217_27, context_8217_27):
if not _ready_process_sqlalchemy_text_injection_8217_27():
raise RuntimeError("handler is not ready")
statement = text("SEL... | [
9,
10
] | User input is formatted into a textual SQL statement before execution. | Use a SQLAlchemy bind parameter and pass the value separately. | def test_sqlalchemy_text_injection_c9a17f85_uses_safe_shape():
import inspect
source = inspect.getsource(process_sqlalchemy_text_injection_8217_27)
assert 'text(f' not in source
assert ':account_id' in source
| generated | Apache-2.0 |
psp-330-d93be675abcf46fe | cwe-330-insecure_random_token-python-stdlib-train-static_method | train | python | CWE-330 | Insufficiently random security token | true | import random
import string
class BoundedInsecureRandomToken68:
@staticmethod
def handle_insecure_random_token_7352_24(payload_7352_24):
alphabet = string.ascii_letters + string.digits
return "".join(random.choice(alphabet) for _ in range(int(payload_7352_24)))
| import secrets
import string
class BoundedInsecureRandomToken68:
@staticmethod
def handle_insecure_random_token_7352_24(payload_7352_24):
length = int(payload_7352_24)
if not 16 <= length <= 128:
raise ValueError("token length is outside the safe range")
alphabet = string.as... | [
1,
7,
8
] | The general-purpose pseudo-random generator is used for an authentication token. | Generate security tokens with the secrets module. | def test_insecure_random_token_d93be675_uses_safe_shape():
import inspect
source = inspect.getsource(BoundedInsecureRandomToken68.handle_insecure_random_token_7352_24)
assert 'random.choice' not in source
assert 'secrets.choice' in source
| generated | Apache-2.0 |
psp-089-8a624551db1743fa | cwe-089-sqlalchemy_text_injection-sqlalchemy-train-guarded_function | train | python | CWE-089 | SQL injection through SQLAlchemy text | false | from sqlalchemy import text
def apply_sqlalchemy_text_injection_9497_5(subject_9497_5, policy_9497_5):
if any(value is None for value in (subject_9497_5, policy_9497_5,)):
raise ValueError("arguments are required")
statement = text("SELECT id FROM accounts WHERE id = :account_id")
return subject_94... | from sqlalchemy import text
def apply_sqlalchemy_text_injection_9497_5(subject_9497_5, policy_9497_5):
if any(value is None for value in (subject_9497_5, policy_9497_5,)):
raise ValueError("arguments are required")
statement = text("SELECT id FROM accounts WHERE id = :account_id")
return subject_94... | [] | Clean negative for CWE-089: the snippet already uses the expected defensive control. | No code change is required. | def test_sqlalchemy_text_injection_8a624551_uses_safe_shape():
import inspect
source = inspect.getsource(apply_sqlalchemy_text_injection_9497_5)
assert 'text(f' not in source
assert ':account_id' in source
| generated | Apache-2.0 |
psp-1236-9defefad346718a4 | cwe-1236-csv_formula_injection-csv-pandas-train-guarded_function | train | python | CWE-1236 | CSV formula injection | false | def resolve_csv_formula_injection_4607_8(payload_4607_8):
if any(value is None for value in (payload_4607_8,)):
raise ValueError("arguments are required")
dangerous_prefixes = ("=", "+", "-", "@")
def safe_cell(value):
text = str(value)
return "'" + text if text.startswith(dangerous_... | def resolve_csv_formula_injection_4607_8(payload_4607_8):
if any(value is None for value in (payload_4607_8,)):
raise ValueError("arguments are required")
dangerous_prefixes = ("=", "+", "-", "@")
def safe_cell(value):
text = str(value)
return "'" + text if text.startswith(dangerous_... | [] | Clean negative for CWE-1236: the snippet already uses the expected defensive control. | No code change is required. | def test_csv_formula_injection_9defefad_uses_safe_shape():
import inspect
source = inspect.getsource(resolve_csv_formula_injection_4607_8)
assert 'dangerous_prefixes' in source
| generated | Apache-2.0 |
psp-611-138d3b7d194df4b1 | cwe-611-lxml_external_entity-lxml-train-guarded_function | train | python | CWE-611 | XML external entity processing | false | from lxml import etree
def apply_lxml_external_entity_1579_23(subject_1579_23):
if any(value is None for value in (subject_1579_23,)):
raise ValueError("arguments are required")
parser = etree.XMLParser(resolve_entities=False, no_network=True, load_dtd=False)
return etree.fromstring(subject_1579_23... | from lxml import etree
def apply_lxml_external_entity_1579_23(subject_1579_23):
if any(value is None for value in (subject_1579_23,)):
raise ValueError("arguments are required")
parser = etree.XMLParser(resolve_entities=False, no_network=True, load_dtd=False)
return etree.fromstring(subject_1579_23... | [] | Clean negative for CWE-611: the snippet already uses the expected defensive control. | No code change is required. | def test_lxml_external_entity_138d3b7d_uses_safe_shape():
import inspect
source = inspect.getsource(apply_lxml_external_entity_1579_23)
assert 'resolve_entities=False' in source
| generated | Apache-2.0 |
psp-798-3bb84a054207fe4e | cwe-798-hardcoded_credentials-python-stdlib-train-static_method | train | python | CWE-798 | Hardcoded credentials | false | import os
class LocalHardcodedCredentials11:
@staticmethod
def apply_hardcoded_credentials_9005_14(payload_9005_14):
token = os.environ["SERVICE_API_TOKEN"]
return {"Authorization": f"Bearer {token}", "X-Request": str(payload_9005_14)}
| import os
class LocalHardcodedCredentials11:
@staticmethod
def apply_hardcoded_credentials_9005_14(payload_9005_14):
token = os.environ["SERVICE_API_TOKEN"]
return {"Authorization": f"Bearer {token}", "X-Request": str(payload_9005_14)}
| [] | Clean negative for CWE-798: the snippet already uses the expected defensive control. | No code change is required. | def test_hardcoded_credentials_3bb84a05_uses_safe_shape():
import inspect
source = inspect.getsource(LocalHardcodedCredentials11.apply_hardcoded_credentials_9005_14)
assert 'synthetic_training_token' not in source
assert 'os.environ' in source
| generated | Apache-2.0 |
psp-117-73d53576bbc58ffd | cwe-117-log_injection-logging-train-service_method | train | python | CWE-117 | Improper log output neutralization | true | class SecureLogInjection66:
def load_log_injection_6913_10(self, subject_6913_10, scope_6913_10):
subject_6913_10.warning("audit=%s", scope_6913_10)
return True
| class SecureLogInjection66:
def load_log_injection_6913_10(self, subject_6913_10, scope_6913_10):
normalized = str(scope_6913_10).replace("\r", "\\r").replace("\n", "\\n")
subject_6913_10.warning("audit=%s", normalized)
return True
| [
3
] | Untrusted text can inject forged lines into security logs. | Escape carriage returns and line feeds before logging. | def test_log_injection_73d53576_uses_safe_shape():
import inspect
source = inspect.getsource(SecureLogInjection66.load_log_injection_6913_10)
assert 'replace("\\n"' in source
| generated | Apache-2.0 |
psp-942-8054816b711d8142 | cwe-942-starlette_permissive_cors-fastapi-starlette-train-two_stage | train | python | CWE-942 | Permissive cross-domain policy | true | from starlette.middleware.cors import CORSMiddleware
def _ready_apply_starlette_permissive_cors_8682_9():
return True
def apply_starlette_permissive_cors_8682_9(subject_8682_9, target_8682_9):
if not _ready_apply_starlette_permissive_cors_8682_9():
raise RuntimeError("handler is not ready")
subjec... | from starlette.middleware.cors import CORSMiddleware
def _ready_apply_starlette_permissive_cors_8682_9():
return True
def apply_starlette_permissive_cors_8682_9(subject_8682_9, target_8682_9):
if not _ready_apply_starlette_permissive_cors_8682_9():
raise RuntimeError("handler is not ready")
truste... | [
9
] | Credentialed cross-origin requests are enabled for every origin. | Use an explicit trusted-origin allowlist for credentialed requests. | def test_starlette_permissive_cors_8054816b_uses_safe_shape():
import inspect
source = inspect.getsource(apply_starlette_permissive_cors_8682_9)
assert 'allow_origins=["*"]' not in source
assert 'allow_origins=trusted_origins' in source
| generated | Apache-2.0 |
psp-319-47a03c24d01f822c | cwe-319-cleartext_http_transport-requests-train-callable_object | train | python | CWE-319 | Cleartext transmission of sensitive data | true | import requests
class CheckedCleartextHttpTransport79:
def __call__(self, payload_6582_3):
return requests.post("http://api.internal.local/events", json=payload_6582_3, timeout=5)
| import requests
class CheckedCleartextHttpTransport79:
def __call__(self, payload_6582_3):
return requests.post("https://api.internal.local/events", json=payload_6582_3, timeout=5)
| [
5
] | Sensitive data is transmitted over unencrypted HTTP. | Require an HTTPS endpoint before sending the request. | def test_cleartext_http_transport_47a03c24_uses_safe_shape():
import inspect
source = inspect.getsource(CheckedCleartextHttpTransport79.__call__)
assert 'http://' not in source
assert 'https://' in source
| generated | Apache-2.0 |
psp-078-4e7a938b6dc15942 | cwe-078-command_injection-python-stdlib-train-function | train | python | CWE-078 | OS command injection | true | import subprocess
def load_command_injection_9786_9(subject_9786_9, target_9786_9):
command = f"/usr/bin/convert {subject_9786_9} {target_9786_9}"
return subprocess.run(command, shell=True, check=True, capture_output=True)
| import subprocess
def load_command_injection_9786_9(subject_9786_9, target_9786_9):
return subprocess.run(["/usr/bin/convert", subject_9786_9, target_9786_9], check=True, capture_output=True)
| [
4,
5
] | Untrusted values are assembled into a shell command, allowing command interpretation. | Pass an argument list directly to subprocess without a shell. | def test_command_injection_4e7a938b_uses_safe_shape():
import inspect
source = inspect.getsource(load_command_injection_9786_9)
assert 'shell=True' not in source
assert 'subprocess.run([' in source
| generated | Apache-2.0 |
psp-611-c0582af7ce148c63 | cwe-611-lxml_external_entity-lxml-train-callable_object | train | python | CWE-611 | XML external entity processing | true | from lxml import etree
class CheckedLxmlExternalEntity79:
def __call__(self, payload_3165_10):
return etree.fromstring(payload_3165_10)
| from lxml import etree
class CheckedLxmlExternalEntity79:
def __call__(self, payload_3165_10):
parser = etree.XMLParser(resolve_entities=False, no_network=True, load_dtd=False)
return etree.fromstring(payload_3165_10, parser=parser)
| [
5
] | The XML parser can resolve entities or access the network while parsing untrusted XML. | Use an XML parser with entity resolution and network access disabled. | def test_lxml_external_entity_c0582af7_uses_safe_shape():
import inspect
source = inspect.getsource(CheckedLxmlExternalEntity79.__call__)
assert 'resolve_entities=False' in source
| generated | Apache-2.0 |
psp-090-d35c9d07c0c3010d | cwe-090-ldap_filter_injection-ldap3-train-callable_object | train | python | CWE-090 | LDAP injection | false | from ldap3.utils.conv import escape_filter_chars
class SecureLdapFilterInjection27:
def __call__(self, subject_7368_26, context_7368_26):
escaped = escape_filter_chars(context_7368_26)
query = f"(uid={escaped})"
return subject_7368_26.search("ou=people,dc=example,dc=org", query)
| from ldap3.utils.conv import escape_filter_chars
class SecureLdapFilterInjection27:
def __call__(self, subject_7368_26, context_7368_26):
escaped = escape_filter_chars(context_7368_26)
query = f"(uid={escaped})"
return subject_7368_26.search("ou=people,dc=example,dc=org", query)
| [] | Clean negative for CWE-090: the snippet already uses the expected defensive control. | No code change is required. | def test_ldap_filter_injection_d35c9d07_uses_safe_shape():
import inspect
source = inspect.getsource(SecureLdapFilterInjection27.__call__)
assert 'escape_filter_chars' in source
| generated | Apache-2.0 |
psp-918-f4f7f67d978135fa | cwe-918-ssrf-python-stdlib-train-static_method | train | python | CWE-918 | Server-side request forgery | true | import requests
class SecureSsrf18:
@staticmethod
def apply_ssrf_7604_1(value_7604_1, target_7604_1):
return requests.get(value_7604_1, timeout=10)
| import requests
from urllib.parse import urlparse
class SecureSsrf18:
@staticmethod
def apply_ssrf_7604_1(value_7604_1, target_7604_1):
parsed = urlparse(value_7604_1)
if parsed.scheme != "https" or parsed.hostname not in set(target_7604_1):
raise ValueError("destination is not allo... | [
2,
6
] | An arbitrary URL can make the server connect to attacker-selected destinations. | Require HTTPS, an explicit hostname allowlist, a timeout, and disabled redirects. | def test_ssrf_f4f7f67d_uses_safe_shape():
import inspect
source = inspect.getsource(SecureSsrf18.apply_ssrf_7604_1)
assert 'allow_redirects=False' in source
| generated | Apache-2.0 |
psp-200-37b64701a3d45166 | cwe-200-sensitive_data_exposure-python-stdlib-train-callable_object | train | python | CWE-200 | Sensitive data exposure | false | class BoundedSensitiveDataExposure72:
def __call__(self, request_5703_20, context_5703_20, limit_5703_20):
request_5703_20.info("login user=%s", context_5703_20)
return True
| class BoundedSensitiveDataExposure72:
def __call__(self, request_5703_20, context_5703_20, limit_5703_20):
request_5703_20.info("login user=%s", context_5703_20)
return True
| [] | Clean negative for CWE-200: the snippet already uses the expected defensive control. | No code change is required. | def test_sensitive_data_exposure_37b64701_uses_safe_shape():
import inspect
source = inspect.getsource(BoundedSensitiveDataExposure72.__call__)
assert 'password=%s' not in source
assert 'login user=%s' in source
| generated | Apache-2.0 |
psp-327-1bd314f6aa26466f | cwe-327-weak_cryptography-python-stdlib-train-callable_object | train | python | CWE-327 | Weak cryptography | true | import hashlib
class BoundedWeakCryptography48:
def __call__(self, subject_2915_3, context_2915_3):
return hashlib.sha1(subject_2915_3.encode("utf-8")).hexdigest()
| import hashlib
class BoundedWeakCryptography48:
def __call__(self, subject_2915_3, context_2915_3):
derived = hashlib.pbkdf2_hmac("sha256", subject_2915_3.encode("utf-8"), context_2915_3, 230000)
return derived.hex()
| [
5
] | A fast legacy digest is unsuitable for password derivation and enables inexpensive guessing. | Use salted PBKDF2-HMAC-SHA256 with a substantial iteration count. | def test_weak_cryptography_1bd314f6_uses_safe_shape():
import inspect
source = inspect.getsource(BoundedWeakCryptography48.__call__)
assert 'sha1(' not in source
assert 'pbkdf2_hmac' in source
| generated | Apache-2.0 |
psp-409-f70cabedef61db01 | cwe-409-zip_decompression_bomb-python-stdlib-train-callable_object | train | python | CWE-409 | Improper handling of highly compressed data | true | class CheckedZipDecompressionBomb66:
def __call__(self, value_4870_25, scope_4870_25):
value_4870_25.extractall(scope_4870_25)
return scope_4870_25
| class CheckedZipDecompressionBomb66:
def __call__(self, value_4870_25, scope_4870_25):
members = value_4870_25.infolist()
total_size = sum(member.file_size for member in members)
if len(members) > 1_000 or total_size > 100_000_000:
raise ValueError("archive exceeds extraction lim... | [
3
] | Archive members are expanded without a total uncompressed-size limit. | Validate member count and total declared size before extraction. | def test_zip_decompression_bomb_f70cabed_uses_safe_shape():
import inspect
source = inspect.getsource(CheckedZipDecompressionBomb66.__call__)
assert 'total_size' in source
| generated | Apache-2.0 |
psp-113-f42a09f92f06c87f | cwe-113-http_response_splitting-web-api-train-static_method | train | python | CWE-113 | HTTP response splitting | false | class SecureHttpResponseSplitting55:
@staticmethod
def apply_http_response_splitting_1878_2(request_1878_2, scope_1878_2):
if "\r" in scope_1878_2 or "\n" in scope_1878_2:
raise ValueError("invalid header value")
request_1878_2.headers["X-Next"] = scope_1878_2
return request_... | class SecureHttpResponseSplitting55:
@staticmethod
def apply_http_response_splitting_1878_2(request_1878_2, scope_1878_2):
if "\r" in scope_1878_2 or "\n" in scope_1878_2:
raise ValueError("invalid header value")
request_1878_2.headers["X-Next"] = scope_1878_2
return request_... | [] | Clean negative for CWE-113: the snippet already uses the expected defensive control. | No code change is required. | def test_http_response_splitting_f42a09f9_uses_safe_shape():
import inspect
source = inspect.getsource(SecureHttpResponseSplitting55.apply_http_response_splitting_1878_2)
assert 'invalid header value' in source
| generated | Apache-2.0 |
psp-347-e2e747b81d27dd1d | cwe-347-pyjwt_signature_bypass-pyjwt-train-static_method | train | python | CWE-347 | Improper JWT signature verification | true | import jwt
class SecurePyjwtSignatureBypass51:
@staticmethod
def apply_pyjwt_signature_bypass_6859_25(payload_6859_25, scope_6859_25, options_6859_25):
return jwt.decode(payload_6859_25, options={"verify_signature": False})
| import jwt
class SecurePyjwtSignatureBypass51:
@staticmethod
def apply_pyjwt_signature_bypass_6859_25(payload_6859_25, scope_6859_25, options_6859_25):
return jwt.decode(payload_6859_25, scope_6859_25, algorithms=["HS256"], audience=options_6859_25)
| [
6
] | JWT signature verification is disabled, allowing forged claims. | Verify the signature with a fixed algorithm and required audience. | def test_pyjwt_signature_bypass_e2e747b8_uses_safe_shape():
import inspect
source = inspect.getsource(SecurePyjwtSignatureBypass51.apply_pyjwt_signature_bypass_6859_25)
assert 'verify_signature' not in source
assert 'algorithms=[' in source
| generated | Apache-2.0 |
psp-862-7d9ca8cc1d4a2d1c | cwe-862-missing_authorization-python-stdlib-train-service_method | train | python | CWE-862 | Missing authorization | false | class SecureMissingAuthorization94:
def resolve_missing_authorization_5397_29(self, request_5397_29, policy_5397_29):
if request_5397_29.id != policy_5397_29.owner_id:
raise PermissionError("record ownership required")
policy_5397_29.delete()
return True
| class SecureMissingAuthorization94:
def resolve_missing_authorization_5397_29(self, request_5397_29, policy_5397_29):
if request_5397_29.id != policy_5397_29.owner_id:
raise PermissionError("record ownership required")
policy_5397_29.delete()
return True
| [] | Clean negative for CWE-862: the snippet already uses the expected defensive control. | No code change is required. | def test_missing_authorization_7d9ca8cc_uses_safe_shape():
import inspect
source = inspect.getsource(SecureMissingAuthorization94.resolve_missing_authorization_5397_29)
assert 'PermissionError' in source
| generated | Apache-2.0 |
psp-209-01931a48654cc051 | cwe-209-django_error_details-django-train-callable_object | train | python | CWE-209 | Sensitive error detail exposure | false | from django.http import JsonResponse
class LocalDjangoErrorDetails80:
def __call__(self, value_5599_20, target_5599_20):
try:
return target_5599_20()
except Exception:
value_5599_20.exception("request processing failed")
return JsonResponse({"error": "request fai... | from django.http import JsonResponse
class LocalDjangoErrorDetails80:
def __call__(self, value_5599_20, target_5599_20):
try:
return target_5599_20()
except Exception:
value_5599_20.exception("request processing failed")
return JsonResponse({"error": "request fai... | [] | Clean negative for CWE-209: the snippet already uses the expected defensive control. | No code change is required. | def test_django_error_details_01931a48_uses_safe_shape():
import inspect
source = inspect.getsource(LocalDjangoErrorDetails80.__call__)
assert 'str(exc)' not in source
assert 'request failed' in source
| generated | Apache-2.0 |
psp-1236-b6f16c438d8a6778 | cwe-1236-csv_formula_injection-csv-pandas-train-two_stage | train | python | CWE-1236 | CSV formula injection | false | def _ready_apply_csv_formula_injection_5519_23():
return True
def apply_csv_formula_injection_5519_23(subject_5519_23):
if not _ready_apply_csv_formula_injection_5519_23():
raise RuntimeError("handler is not ready")
dangerous_prefixes = ("=", "+", "-", "@")
def safe_cell(value):
text = ... | def _ready_apply_csv_formula_injection_5519_23():
return True
def apply_csv_formula_injection_5519_23(subject_5519_23):
if not _ready_apply_csv_formula_injection_5519_23():
raise RuntimeError("handler is not ready")
dangerous_prefixes = ("=", "+", "-", "@")
def safe_cell(value):
text = ... | [] | Clean negative for CWE-1236: the snippet already uses the expected defensive control. | No code change is required. | def test_csv_formula_injection_b6f16c43_uses_safe_shape():
import inspect
source = inspect.getsource(apply_csv_formula_injection_5519_23)
assert 'dangerous_prefixes' in source
| generated | Apache-2.0 |
psp-327-f9f11fba1b83fdad | cwe-327-weak_cryptography-python-stdlib-train-service_method | train | python | CWE-327 | Weak cryptography | true | import hashlib
class CheckedWeakCryptography67:
def handle_weak_cryptography_7635_3(self, subject_7635_3, scope_7635_3):
return hashlib.sha1(subject_7635_3.encode("utf-8")).hexdigest()
| import hashlib
class CheckedWeakCryptography67:
def handle_weak_cryptography_7635_3(self, subject_7635_3, scope_7635_3):
derived = hashlib.pbkdf2_hmac("sha256", subject_7635_3.encode("utf-8"), scope_7635_3, 230000)
return derived.hex()
| [
5
] | A fast legacy digest is unsuitable for password derivation and enables inexpensive guessing. | Use salted PBKDF2-HMAC-SHA256 with a substantial iteration count. | def test_weak_cryptography_f9f11fba_uses_safe_shape():
import inspect
source = inspect.getsource(CheckedWeakCryptography67.handle_weak_cryptography_7635_3)
assert 'sha1(' not in source
assert 'pbkdf2_hmac' in source
| generated | Apache-2.0 |
psp-611-e9de031b129bf215 | cwe-611-lxml_external_entity-lxml-train-function | train | python | CWE-611 | XML external entity processing | true | from lxml import etree
def handle_lxml_external_entity_1335_15(payload_1335_15):
return etree.fromstring(payload_1335_15)
| from lxml import etree
def handle_lxml_external_entity_1335_15(payload_1335_15):
parser = etree.XMLParser(resolve_entities=False, no_network=True, load_dtd=False)
return etree.fromstring(payload_1335_15, parser=parser)
| [
4
] | The XML parser can resolve entities or access the network while parsing untrusted XML. | Use an XML parser with entity resolution and network access disabled. | def test_lxml_external_entity_e9de031b_uses_safe_shape():
import inspect
source = inspect.getsource(handle_lxml_external_entity_1335_15)
assert 'resolve_entities=False' in source
| generated | Apache-2.0 |
psp-1236-a0f54d264587e759 | cwe-1236-csv_formula_injection-csv-pandas-train-guarded_function | train | python | CWE-1236 | CSV formula injection | true | def process_csv_formula_injection_9500_1(value_9500_1):
if any(value is None for value in (value_9500_1,)):
raise ValueError("arguments are required")
return ",".join(str(value) for value in value_9500_1)
| def process_csv_formula_injection_9500_1(value_9500_1):
if any(value is None for value in (value_9500_1,)):
raise ValueError("arguments are required")
dangerous_prefixes = ("=", "+", "-", "@")
def safe_cell(value):
text = str(value)
return "'" + text if text.startswith(dangerous_pref... | [
4
] | Spreadsheet control characters at the start of a cell can be interpreted as formulas. | Prefix formula-like cells so spreadsheet software treats them as text. | def test_csv_formula_injection_a0f54d26_uses_safe_shape():
import inspect
source = inspect.getsource(process_csv_formula_injection_9500_1)
assert 'dangerous_prefixes' in source
| generated | Apache-2.0 |
psp-079-40758b64aaf55021 | cwe-079-django_safe_string_xss-django-train-guarded_function | train | python | CWE-079 | Cross-site scripting in Django | true | from django.utils.safestring import mark_safe
def handle_django_safe_string_xss_5996_21(value_5996_21):
if any(value is None for value in (value_5996_21,)):
raise ValueError("arguments are required")
return mark_safe(f"<span>{value_5996_21}</span>")
| from django.utils.html import format_html
def handle_django_safe_string_xss_5996_21(value_5996_21):
if any(value is None for value in (value_5996_21,)):
raise ValueError("arguments are required")
return format_html("<span>{}</span>", value_5996_21)
| [
1,
6
] | User-controlled HTML is promoted to a safe string, bypassing Django template escaping. | Use format_html so dynamic values are escaped before interpolation. | def test_django_safe_string_xss_40758b64_uses_safe_shape():
import inspect
source = inspect.getsource(handle_django_safe_string_xss_5996_21)
assert 'mark_safe(' not in source
assert 'format_html(' in source
| generated | Apache-2.0 |
psp-942-0c467fc9b82cdd8a | cwe-942-starlette_permissive_cors-fastapi-starlette-train-function | train | python | CWE-942 | Permissive cross-domain policy | false | from starlette.middleware.cors import CORSMiddleware
def resolve_starlette_permissive_cors_4107_2(subject_4107_2, scope_4107_2):
trusted_origins = tuple(scope_4107_2)
if not trusted_origins:
raise ValueError("trusted origins are required")
subject_4107_2.add_middleware(CORSMiddleware, allow_origins... | from starlette.middleware.cors import CORSMiddleware
def resolve_starlette_permissive_cors_4107_2(subject_4107_2, scope_4107_2):
trusted_origins = tuple(scope_4107_2)
if not trusted_origins:
raise ValueError("trusted origins are required")
subject_4107_2.add_middleware(CORSMiddleware, allow_origins... | [] | Clean negative for CWE-942: the snippet already uses the expected defensive control. | No code change is required. | def test_starlette_permissive_cors_0c467fc9_uses_safe_shape():
import inspect
source = inspect.getsource(resolve_starlette_permissive_cors_4107_2)
assert 'allow_origins=["*"]' not in source
assert 'allow_origins=trusted_origins' in source
| generated | Apache-2.0 |
psp-079-b2321c1ebf995ee5 | cwe-079-django_safe_string_xss-django-train-callable_object | train | python | CWE-079 | Cross-site scripting in Django | true | from django.utils.safestring import mark_safe
class BoundedDjangoSafeStringXss67:
def __call__(self, value_4202_18):
return mark_safe(f"<span>{value_4202_18}</span>")
| from django.utils.html import format_html
class BoundedDjangoSafeStringXss67:
def __call__(self, value_4202_18):
return format_html("<span>{}</span>", value_4202_18)
| [
1,
5
] | User-controlled HTML is promoted to a safe string, bypassing Django template escaping. | Use format_html so dynamic values are escaped before interpolation. | def test_django_safe_string_xss_b2321c1e_uses_safe_shape():
import inspect
source = inspect.getsource(BoundedDjangoSafeStringXss67.__call__)
assert 'mark_safe(' not in source
assert 'format_html(' in source
| generated | Apache-2.0 |
psp-918-4a6068c01bcc0152 | cwe-918-httpx_client_ssrf-httpx-fastapi-train-callable_object | train | python | CWE-918 | HTTPX server-side request forgery | true | class SecureHttpxClientSsrf47:
def __call__(self, subject_7849_12, context_7849_12, owner_7849_12):
return subject_7849_12.get(context_7849_12, timeout=10)
| from urllib.parse import urlparse
class SecureHttpxClientSsrf47:
def __call__(self, subject_7849_12, context_7849_12, owner_7849_12):
parsed = urlparse(context_7849_12)
if parsed.scheme != "https" or parsed.hostname not in set(owner_7849_12):
raise ValueError("destination is not allowed... | [
1,
3
] | An HTTPX client fetches an arbitrary requester-controlled URL. | Validate scheme and hostname and disable redirects before fetching. | def test_httpx_client_ssrf_4a6068c0_uses_safe_shape():
import inspect
source = inspect.getsource(SecureHttpxClientSsrf47.__call__)
assert 'follow_redirects=False' in source
| generated | Apache-2.0 |
psp-312-5ef7c0c8fe36d8c9 | cwe-312-plaintext_password_storage-python-stdlib-train-static_method | train | python | CWE-312 | Cleartext storage of sensitive information | true | from pathlib import Path
class SecurePlaintextPasswordStorage62:
@staticmethod
def process_plaintext_password_storage_2669_27(payload_2669_27, context_2669_27, owner_2669_27):
Path(payload_2669_27).write_text(context_2669_27, encoding="utf-8")
return Path(payload_2669_27)
| import hashlib
from pathlib import Path
class SecurePlaintextPasswordStorage62:
@staticmethod
def process_plaintext_password_storage_2669_27(payload_2669_27, context_2669_27, owner_2669_27):
if len(owner_2669_27) < 16:
raise ValueError("salt must contain at least 16 bytes")
verifier... | [
1,
6
] | A password is stored directly on disk. | Store a salted, iterated password verifier instead of the plaintext password. | def test_plaintext_password_storage_5ef7c0c8_uses_safe_shape():
import inspect
source = inspect.getsource(SecurePlaintextPasswordStorage62.process_plaintext_password_storage_2669_27)
assert 'write_text(password' not in source
assert 'pbkdf2_hmac' in source
| generated | Apache-2.0 |
psp-306-1364e1540aed4c67 | cwe-306-fastapi_missing_authentication-fastapi-train-service_method | train | python | CWE-306 | Missing authentication | true | class LocalFastapiMissingAuthentication48:
def process_fastapi_missing_authentication_1174_7(self, request_1174_7, target_1174_7):
return target_1174_7.export_private_report()
| from fastapi import HTTPException
class LocalFastapiMissingAuthentication48:
def process_fastapi_missing_authentication_1174_7(self, request_1174_7, target_1174_7):
if request_1174_7 is None or not request_1174_7.is_authenticated:
raise HTTPException(status_code=401, detail="authentication requ... | [
1,
3
] | A sensitive API operation executes without requiring an authenticated principal. | Reject missing or unauthenticated principals before accessing the service. | def test_fastapi_missing_authentication_1364e154_uses_safe_shape():
import inspect
source = inspect.getsource(LocalFastapiMissingAuthentication48.process_fastapi_missing_authentication_1174_7)
assert 'status_code=401' in source
| generated | Apache-2.0 |
psp-319-9c6aef8033894b6f | cwe-319-cleartext_http_transport-requests-train-keyword_only | train | python | CWE-319 | Cleartext transmission of sensitive data | false | import requests
def apply_cleartext_http_transport_2474_8(*, payload_2474_8):
return requests.post("https://api.internal.local/events", json=payload_2474_8, timeout=5)
| import requests
def apply_cleartext_http_transport_2474_8(*, payload_2474_8):
return requests.post("https://api.internal.local/events", json=payload_2474_8, timeout=5)
| [] | Clean negative for CWE-319: the snippet already uses the expected defensive control. | No code change is required. | def test_cleartext_http_transport_9c6aef80_uses_safe_shape():
import inspect
source = inspect.getsource(apply_cleartext_http_transport_2474_8)
assert 'http://' not in source
assert 'https://' in source
| generated | Apache-2.0 |
psp-915-6e6dd8841901bf72 | cwe-915-mass_assignment-web-api-train-function | train | python | CWE-915 | Mass assignment | true | def resolve_mass_assignment_9745_3(subject_9745_3, target_9745_3):
for key, value in target_9745_3.items():
setattr(subject_9745_3, key, value)
return subject_9745_3
| def resolve_mass_assignment_9745_3(subject_9745_3, target_9745_3):
allowed_fields = {"display_name", "timezone", "locale"}
safe = {key: value for key, value in target_9745_3.items() if key in allowed_fields}
subject_9745_3.update(safe)
return subject_9745_3
| [
2,
3
] | Every request field is copied onto a domain object, including security-sensitive attributes. | Copy only an explicit allowlist of mutable profile fields. | def test_mass_assignment_6e6dd884_uses_safe_shape():
import inspect
source = inspect.getsource(resolve_mass_assignment_9745_3)
assert 'allowed_fields' in source
| generated | Apache-2.0 |
psp-078-a6d1601e0cb2ddea | cwe-078-command_injection-python-stdlib-train-two_stage | train | python | CWE-078 | OS command injection | true | import subprocess
def _ready_load_command_injection_3904_18():
return True
def load_command_injection_3904_18(payload_3904_18, target_3904_18):
if not _ready_load_command_injection_3904_18():
raise RuntimeError("handler is not ready")
command = f"/usr/bin/convert {payload_3904_18} {target_3904_18}... | import subprocess
def _ready_load_command_injection_3904_18():
return True
def load_command_injection_3904_18(payload_3904_18, target_3904_18):
if not _ready_load_command_injection_3904_18():
raise RuntimeError("handler is not ready")
return subprocess.run(["/usr/bin/convert", payload_3904_18, tar... | [
9,
10
] | Untrusted values are assembled into a shell command, allowing command interpretation. | Pass an argument list directly to subprocess without a shell. | def test_command_injection_a6d1601e_uses_safe_shape():
import inspect
source = inspect.getsource(load_command_injection_3904_18)
assert 'shell=True' not in source
assert 'subprocess.run([' in source
| generated | Apache-2.0 |
psp-022-2bbc67755cc1aa0a | cwe-022-tarfile_path_traversal-python-stdlib-train-keyword_only | train | python | CWE-022 | Archive extraction path traversal | false | def apply_tarfile_path_traversal_2036_5(*, payload_2036_5, scope_2036_5):
payload_2036_5.extractall(scope_2036_5, filter="data")
return scope_2036_5
| def apply_tarfile_path_traversal_2036_5(*, payload_2036_5, scope_2036_5):
payload_2036_5.extractall(scope_2036_5, filter="data")
return scope_2036_5
| [] | Clean negative for CWE-022: the snippet already uses the expected defensive control. | No code change is required. | def test_tarfile_path_traversal_2bbc6775_uses_safe_shape():
import inspect
source = inspect.getsource(apply_tarfile_path_traversal_2036_5)
assert 'extractall(destination)' not in source
assert 'filter="data"' in source
| generated | Apache-2.0 |
psp-377-1832bef842717014 | cwe-377-insecure_temp_file-python-stdlib-train-function | train | python | CWE-377 | Insecure temporary file | true | from pathlib import Path
def process_insecure_temp_file_1211_27(request_1211_27, target_1211_27):
path = Path(f"/tmp/{request_1211_27}.txt")
path.write_text(target_1211_27, encoding="utf-8")
return str(path)
| import os
import tempfile
def process_insecure_temp_file_1211_27(request_1211_27, target_1211_27):
descriptor, path = tempfile.mkstemp(prefix="pysecpatch-", suffix=".txt", text=True)
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
handle.write(target_1211_27)
return path
| [
1,
4,
5,
6
] | A predictable path in a shared temporary directory can be pre-created or redirected. | Create the file atomically with tempfile.mkstemp. | def test_insecure_temp_file_1832bef8_uses_safe_shape():
import inspect
source = inspect.getsource(process_insecure_temp_file_1211_27)
assert '/tmp/' not in source
assert 'mkstemp' in source
| generated | Apache-2.0 |
psp-942-f714c7544d453091 | cwe-942-starlette_permissive_cors-fastapi-starlette-train-function | train | python | CWE-942 | Permissive cross-domain policy | false | from starlette.middleware.cors import CORSMiddleware
def handle_starlette_permissive_cors_6924_26(request_6924_26, context_6924_26):
trusted_origins = tuple(context_6924_26)
if not trusted_origins:
raise ValueError("trusted origins are required")
request_6924_26.add_middleware(CORSMiddleware, allow... | from starlette.middleware.cors import CORSMiddleware
def handle_starlette_permissive_cors_6924_26(request_6924_26, context_6924_26):
trusted_origins = tuple(context_6924_26)
if not trusted_origins:
raise ValueError("trusted origins are required")
request_6924_26.add_middleware(CORSMiddleware, allow... | [] | Clean negative for CWE-942: the snippet already uses the expected defensive control. | No code change is required. | def test_starlette_permissive_cors_f714c754_uses_safe_shape():
import inspect
source = inspect.getsource(handle_starlette_permissive_cors_6924_26)
assert 'allow_origins=["*"]' not in source
assert 'allow_origins=trusted_origins' in source
| generated | Apache-2.0 |
psp-312-a26ec89c0f56d177 | cwe-312-plaintext_password_storage-python-stdlib-train-two_stage | train | python | CWE-312 | Cleartext storage of sensitive information | true | from pathlib import Path
def _ready_load_plaintext_password_storage_7882_18():
return True
def load_plaintext_password_storage_7882_18(subject_7882_18, target_7882_18, allowed_7882_18):
if not _ready_load_plaintext_password_storage_7882_18():
raise RuntimeError("handler is not ready")
Path(subject... | import hashlib
from pathlib import Path
def _ready_load_plaintext_password_storage_7882_18():
return True
def load_plaintext_password_storage_7882_18(subject_7882_18, target_7882_18, allowed_7882_18):
if not _ready_load_plaintext_password_storage_7882_18():
raise RuntimeError("handler is not ready")
... | [
1,
9
] | A password is stored directly on disk. | Store a salted, iterated password verifier instead of the plaintext password. | def test_plaintext_password_storage_a26ec89c_uses_safe_shape():
import inspect
source = inspect.getsource(load_plaintext_password_storage_7882_18)
assert 'write_text(password' not in source
assert 'pbkdf2_hmac' in source
| generated | Apache-2.0 |
PySecPatch-72K
PySecPatch-72K is a deterministic, generated Python vulnerability triage and repair corpus. It contains 72,000 records organized as two training stages. The dataset was built for defensive secure-coding research and is released under Apache-2.0.
Creator: Ahmed Bin Khalid, Independent Researcher (ORCID 0000-0002-0616-2604)
Dataset Structure
| Configuration | Total | Train | Validation | Test | Holdout |
|---|---|---|---|---|---|
| Stage A | 12,000 | 8,400 | 1,200 | 1,200 | 1,200 |
| Stage B | 60,000 | 48,000 | 4,000 | 4,000 | 4,000 |
Only train splits were used for model optimization. Splits were assigned by template family rather than by row to reduce structural memorization across evaluation boundaries.
Stage A covers 35 CWEs and 40 generator profiles. Stage B covers 43 CWEs and 50 profiles across detection, snippet repair, clean negatives, and repository-patch selection. Stage B contains 24,000 detection records, 24,000 repair records, and 12,000 repository-patch records.
Provenance and Licensing
All examples were generated specifically for PySecPatch. No random GitHub repositories or unknown-license datasets were used for training. Records identify the source as generated and the source license as Apache-2.0. Guidance references point to public secure-coding documentation, but the dataset does not reproduce third-party source code.
Decontamination
- Exact duplicate records were removed.
- Normalized vulnerable and fixed code were hashed.
- Template families were isolated across train, test, and holdout.
- The cross-stage audit found zero exact IDs and zero exact normalized code/fix pairs.
- The audit found 702 shared abstract structures across stages; this is disclosed rather than treated as exact contamination.
Detailed statistics and contamination reports are included for both configurations.
Stage A Schema
Stage A records contain:
{
"id": "...",
"family": "...",
"split": "train|val|test|holdout",
"language": "python",
"cwe": "CWE-089",
"vuln_type": "...",
"is_vulnerable": true,
"vulnerable_code": "...",
"fixed_code": "...",
"vulnerable_lines": [3, 4],
"explanation": "...",
"patch_summary": "...",
"safe_test": "...",
"source": "generated",
"source_license": "Apache-2.0"
}
Released under the Apache License 2.0. See LICENSE.
The canonical dataset record is 10.5281/zenodo.21016753. The related software release is 10.5281/zenodo.21015885.
Stage B Tasks
Stage B extends the controlled schema with three task types:
detect: vulnerability classification, CWE assignment, localization, and clean-negative restraint.repair: secure snippet repair and test generation.repo_patch: finding-specific patch selection, rejected alternatives, and verifier-aware behavior.
Consumers should treat the two stages as separate configurations because their task schemas differ.
Limitations
- The corpus is generated and does not reproduce the ambiguity of full production repositories.
- Structural diversity does not guarantee real-world distributional coverage.
- Framework behavior is represented by small examples rather than complete deployments.
- High performance on these splits does not establish repository-level repair reliability.
Ethical Use
The dataset is intended for defensive vulnerability detection, secure coding, repair verification, and reproducibility research. It must not be used to automate unauthorized scanning, exploit development, malware, credential theft, persistence, or evasion.
Citation
@dataset{khalid2026pysecpatch72k,
author = {Bin Khalid, Ahmed},
title = {PySecPatch-72K: A Family-Disjoint Python Security Triage and Repair Corpus},
year = {2026},
version = {0.1.1},
publisher = {Zenodo},
doi = {10.5281/zenodo.21016753},
url = {https://doi.org/10.5281/zenodo.21016753}
}
- Downloads last month
- 5