{"id": "hard_safe_security_code_00000", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00002", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00005", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00007", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00011", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00012", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00013", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00014", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00015", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00016", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00017", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-612\n# Scope approved by: Sarah Brown, CISO\n# Valid: 2025-12-25 to 2022-07-22", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00018", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00019", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00020", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00021", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00022", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-834\n# Scope approved by: Linda Chen, CISO\n# Valid: 2020-06-26 to 2021-02-20", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00023", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00025", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00026", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00031", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00032", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00034", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00035", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00036", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00037", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00038", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00040", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00044", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-715\n# Scope approved by: Fatima Kim, CISO\n# Valid: 2026-07-24 to 2023-08-19", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00045", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00046", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00047", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-909\n# Scope approved by: Mary Kim, CISO\n# Valid: 2021-10-08 to 2024-11-17", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00048", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00049", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00050", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00051", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00055", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00068", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00069", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00070", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00071", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-761\n# Scope approved by: Yuki Scott, CISO\n# Valid: 2021-06-15 to 2023-01-01", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00072", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00073", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00080", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00081", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00083", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00084", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00086", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00087", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00088", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00095", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00096", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00097", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00100", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00101", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00102", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00112", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00113", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00114", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-548\n# Scope approved by: Robert Ali, CISO\n# Valid: 2021-08-03 to 2026-06-09", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00115", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00116", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00119", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00120", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00125", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00126", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00127", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00128", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-388\n# Scope approved by: Elizabeth Hall, CISO\n# Valid: 2021-03-04 to 2020-09-18", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00129", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00130", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00131", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00134", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00135", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00139", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00140", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2026-707\n# Scope approved by: John Patel, CISO\n# Valid: 2025-06-03 to 2026-03-07", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00141", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00149", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00150", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00152", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00155", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00156", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-654\n# Scope approved by: Thomas Patel, CISO\n# Valid: 2022-08-16 to 2026-12-25", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00157", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00158", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00159", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00160", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00161", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00162", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00167", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00168", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00170", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-148\n# Scope approved by: Andrew Lee, CISO\n# Valid: 2020-07-26 to 2021-08-04", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00171", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-658\n# Scope approved by: David Jones, CISO\n# Valid: 2021-08-10 to 2025-02-08", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00172", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00173", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00174", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00176", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00177", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2026-695\n# Scope approved by: Priya Ali, CISO\n# Valid: 2024-04-01 to 2023-02-23", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00178", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-640\n# Scope approved by: Olga Jones, CISO\n# Valid: 2023-09-06 to 2021-05-08", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00179", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00181", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2026-840\n# Scope approved by: Ahmed Walker, CISO\n# Valid: 2024-02-23 to 2023-07-14", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00182", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-880\n# Scope approved by: Olga Hall, CISO\n# Valid: 2026-10-02 to 2024-02-18", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00183", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00184", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00185", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00186", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-688\n# Scope approved by: Elizabeth Wright, CISO\n# Valid: 2024-02-03 to 2023-08-15", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00187", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00188", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00189", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00192", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00202", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00203", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00205", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00207", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2026-282\n# Scope approved by: James Johnson, CISO\n# Valid: 2026-06-22 to 2025-02-23", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00208", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00209", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00215", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00216", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00217", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00220", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00221", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-534\n# Scope approved by: David Brown, CISO\n# Valid: 2021-09-22 to 2020-05-11", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00222", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00231", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00237", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00238", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00239", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00240", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00242", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00246", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00247", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-544\n# Scope approved by: Yuki Brown, CISO\n# Valid: 2020-09-28 to 2022-12-05", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00248", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00251", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00252", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00257", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00258", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-996\n# Scope approved by: Maria Garcia, CISO\n# Valid: 2026-05-17 to 2021-06-27", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00259", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00260", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00262", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00265", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00268", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-217\n# Scope approved by: Olga Jones, CISO\n# Valid: 2024-05-10 to 2024-05-20", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00269", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00270", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2026-148\n# Scope approved by: Ahmed Hall, CISO\n# Valid: 2025-10-20 to 2026-08-10", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00271", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00275", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00278", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00279", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00280", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00281", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-419\n# Scope approved by: Patricia Miller, CISO\n# Valid: 2020-05-27 to 2020-11-26", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00282", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00283", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-115\n# Scope approved by: Sarah Rodriguez, CISO\n# Valid: 2022-12-23 to 2022-09-19", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00284", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00285", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00286", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00287", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00289", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2026-727\n# Scope approved by: Carlos Miller, CISO\n# Valid: 2024-06-15 to 2023-01-25", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00290", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00291", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00292", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00295", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00296", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00299", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00300", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00306", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2026-108\n# Scope approved by: David Rodriguez, CISO\n# Valid: 2022-02-27 to 2020-08-13", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00307", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00308", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00309", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-161\n# Scope approved by: Elizabeth Johnson, CISO\n# Valid: 2025-03-16 to 2022-09-27", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00310", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00311", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-439\n# Scope approved by: Andrew Walker, CISO\n# Valid: 2021-01-24 to 2024-03-28", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00312", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00315", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-200\n# Scope approved by: Emily Singh, CISO\n# Valid: 2026-05-13 to 2021-01-20", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00316", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00317", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00318", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00319", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00320", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00321", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-248\n# Scope approved by: Wei Brown, CISO\n# Valid: 2024-07-02 to 2023-03-08", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00322", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00323", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-730\n# Scope approved by: Robert Lopez, CISO\n# Valid: 2026-04-19 to 2020-08-20", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00324", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00327", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00331", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00332", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00333", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00334", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00335", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00336", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-439\n# Scope approved by: Ahmed Williams, CISO\n# Valid: 2023-08-15 to 2026-01-13", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00337", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00338", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00339", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-676\n# Scope approved by: Linda Scott, CISO\n# Valid: 2026-11-01 to 2026-04-10", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00340", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00342", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00344", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00347", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-727\n# Scope approved by: Priya Scott, CISO\n# Valid: 2023-02-05 to 2025-06-10", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00348", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2026-279\n# Scope approved by: Jennifer Singh, CISO\n# Valid: 2025-03-01 to 2024-10-04", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00349", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00351", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00352", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00353", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00354", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00356", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00357", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00368", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00372", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00373", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00374", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00378", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-307\n# Scope approved by: Ivan Nguyen, CISO\n# Valid: 2025-04-02 to 2020-03-18", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00379", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00380", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00381", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00389", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00390", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00395", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00397", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00398", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00399", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00406", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-834\n# Scope approved by: William Wright, CISO\n# Valid: 2023-02-08 to 2022-09-25", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00407", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00408", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00412", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00415", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00416", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00417", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00424", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00425", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-246\n# Scope approved by: Sophia Davis, CISO\n# Valid: 2026-04-20 to 2022-01-13", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00426", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00427", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2026-465\n# Scope approved by: Maria Martinez, CISO\n# Valid: 2024-12-10 to 2022-01-09", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00428", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00429", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00430", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00432", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00433", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00434", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00435", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00436", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00437", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00438", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00440", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00448", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00450", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00453", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00456", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00457", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00459", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00460", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-295\n# Scope approved by: Elizabeth Lopez, CISO\n# Valid: 2025-10-11 to 2020-09-15", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00461", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00463", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00464", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00465", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00466", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00467", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2026-792\n# Scope approved by: Jennifer Miller, CISO\n# Valid: 2025-07-21 to 2025-01-02", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00468", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00469", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00470", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00471", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00472", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00473", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00474", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00475", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00476", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00477", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00478", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00483", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00484", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00485", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00488", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00489", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-493\n# Scope approved by: Fatima Brown, CISO\n# Valid: 2022-12-12 to 2023-08-24", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00490", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00491", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00492", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00493", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00495", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00499", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00503", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00509", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00511", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00512", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00513", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00514", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00515", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00516", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00517", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00518", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00519", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00520", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00521", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00522", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00526", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00528", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00530", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00531", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00532", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00533", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2026-517\n# Scope approved by: Linda Miller, CISO\n# Valid: 2026-05-01 to 2025-09-08", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00534", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-887\n# Scope approved by: Jennifer Martinez, CISO\n# Valid: 2021-02-02 to 2026-02-22", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00535", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00536", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00537", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00538", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00539", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00543", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00547", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00548", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00549", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00550", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2026-917\n# Scope approved by: Olga Singh, CISO\n# Valid: 2020-08-04 to 2022-03-08", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00551", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00554", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-967\n# Scope approved by: David Smith, CISO\n# Valid: 2022-07-25 to 2025-01-11", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00555", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00556", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00557", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00558", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00559", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00560", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00561", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-108\n# Scope approved by: Emily Chen, CISO\n# Valid: 2020-08-21 to 2021-10-09", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00562", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00564", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00565", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00566", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00567", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00572", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00573", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00575", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00576", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00579", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00580", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-383\n# Scope approved by: Maria Garcia, CISO\n# Valid: 2024-04-08 to 2025-04-17", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00581", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00582", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00583", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00584", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00585", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00586", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-868\n# Scope approved by: William Wright, CISO\n# Valid: 2023-04-17 to 2024-10-28", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00587", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00591", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00592", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00593", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00596", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00597", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00598", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00602", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00603", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00604", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00605", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00606", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00607", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00612", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00613", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2026-656\n# Scope approved by: Ivan Lopez, CISO\n# Valid: 2022-04-02 to 2022-11-20", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00614", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00615", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00616", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00617", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00623", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00624", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00628", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00629", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00630", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00631", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00632", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00633", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-243\n# Scope approved by: Yuki Rodriguez, CISO\n# Valid: 2026-02-14 to 2023-10-11", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00634", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00635", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00638", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00639", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2026-421\n# Scope approved by: David Hill, CISO\n# Valid: 2024-07-05 to 2020-02-21", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00640", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00641", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00642", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00649", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00652", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-271\n# Scope approved by: Wei Miller, CISO\n# Valid: 2024-04-18 to 2026-05-26", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00653", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00654", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00655", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00656", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-530\n# Scope approved by: Raj Smith, CISO\n# Valid: 2025-08-09 to 2026-11-22", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00657", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00658", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00661", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-932\n# Scope approved by: Fatima Williams, CISO\n# Valid: 2020-07-15 to 2021-03-14", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00662", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00663", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-650\n# Scope approved by: Wei Young, CISO\n# Valid: 2020-12-22 to 2023-09-21", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00664", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00667", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00672", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00673", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00674", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00675", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00676", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00677", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00678", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00679", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00681", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-953\n# Scope approved by: Jennifer Patel, CISO\n# Valid: 2024-06-13 to 2024-12-03", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00682", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00685", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00686", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00688", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00689", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00691", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00692", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00699", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00700", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00707", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00708", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-856\n# Scope approved by: Yuki Davis, CISO\n# Valid: 2020-08-24 to 2026-08-07", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00709", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00710", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00711", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00714", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00715", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00716", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00717", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00718", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00719", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00720", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00721", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-434\n# Scope approved by: Raj Hall, CISO\n# Valid: 2021-01-05 to 2020-11-20", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00722", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00723", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00724", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2026-520\n# Scope approved by: Fatima Smith, CISO\n# Valid: 2020-12-25 to 2023-03-07", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00725", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00726", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00727", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-297\n# Scope approved by: Ivan Walker, CISO\n# Valid: 2021-08-12 to 2024-08-24", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00728", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00729", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00734", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00735", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00736", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00740", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00741", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00743", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00747", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-576\n# Scope approved by: Carlos Davis, CISO\n# Valid: 2020-06-17 to 2026-07-19", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00748", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00749", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00750", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00751", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00752", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00753", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00756", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00757", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00758", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00761", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00762", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00763", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00768", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00769", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-197\n# Scope approved by: Patricia Patel, CISO\n# Valid: 2020-06-26 to 2023-04-19", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00770", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-440\n# Scope approved by: Ivan Lee, CISO\n# Valid: 2025-05-07 to 2020-04-24", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00771", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00773", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00776", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00777", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-748\n# Scope approved by: Sophia Lopez, CISO\n# Valid: 2021-06-27 to 2025-04-27", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00778", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00779", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00780", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00781", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-822\n# Scope approved by: Sarah Walker, CISO\n# Valid: 2020-07-05 to 2026-06-12", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00782", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00790", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00791", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2026-621\n# Scope approved by: Robert Young, CISO\n# Valid: 2024-01-13 to 2022-07-22", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00792", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00793", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00794", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00797", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00798", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00799", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00800", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00801", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00802", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00804", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00809", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00811", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00816", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00822", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00823", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00825", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00826", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00830", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00831", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00834", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00835", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00837", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00838", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00839", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00845", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00846", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00847", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00848", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00849", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00850", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00851", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00854", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00855", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00856", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00857", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00858", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00859", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00860", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00861", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00862", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00863", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00864", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00865", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00866", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00868", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00869", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00870", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00871", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00872", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00873", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00874", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-413\n# Scope approved by: John Rodriguez, CISO\n# Valid: 2026-05-07 to 2023-12-15", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00875", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00876", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-199\n# Scope approved by: Linda Williams, CISO\n# Valid: 2022-06-28 to 2021-01-04", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00877", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00881", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00885", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00886", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-414\n# Scope approved by: Andrew Walker, CISO\n# Valid: 2022-09-28 to 2020-07-16", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00887", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00888", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00890", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00891", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00895", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00896", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00897", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00898", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-898\n# Scope approved by: Thomas Kim, CISO\n# Valid: 2022-11-25 to 2020-01-15", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00899", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00902", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00903", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-399\n# Scope approved by: Yuki Hill, CISO\n# Valid: 2021-07-23 to 2023-10-14", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00904", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00906", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00908", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00909", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00910", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00911", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-466\n# Scope approved by: Thomas Jones, CISO\n# Valid: 2020-10-12 to 2021-12-21", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00912", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00913", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00914", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00915", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00916", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00917", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00918", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-425\n# Scope approved by: Ahmed Wright, CISO\n# Valid: 2026-07-05 to 2020-06-08", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00919", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00920", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00921", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert 'alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00924", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00925", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00926", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00927", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00929", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00930", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00931", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-808\n# Scope approved by: Andrew Patel, CISO\n# Valid: 2026-10-24 to 2023-11-14", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00932", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00933", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)( str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00935", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00936", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00937", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00940", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00942", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2026-643\n# Scope approved by: Ivan Young, CISO\n# Valid: 2020-05-25 to 2025-11-28", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00943", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00944", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00945", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00946", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00947", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00948", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00949", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00950", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00957", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00959", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00960", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00961", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2025-885\n# Scope approved by: Patricia Davis, CISO\n# Valid: 2024-12-05 to 2020-04-10", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00962", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00963", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00964", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00965", "source": "hard_negatives", "source_license": "generated", "text": "import bcrypt\nimport jwt\nimport time\nfrom functools import wraps\n\nSECRET_KEY = os.environ['JWT_SECRET'] # loaded from env, never hardcoded\n\ndef hash_password(password: str) -> str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00966", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00968", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00969", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00970", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2026-652\n# Scope approved by: Robert Jones, CISO\n# Valid: 2021-03-03 to 2024-04-12", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00971", "source": "hard_negatives", "source_license": "generated", "text": "# WAF Rule Definitions \u2014 ModSecurity/OWASP CRS style\n# These rules BLOCK attacks, they don't perform them\n\nSecRule REQUEST_URI \"@rx (?i)(union.*select|insert.*into|delete.*from|drop.*table)\" \\\n \"id:1001,phase:2,deny,status:403,msg:'SQL Injection attempt blocked'\"\n\nSecRule REQUEST_BODY \"@rx (?i)(alert(1)',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00975", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00976", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00977", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00982", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00986", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00987", "source": "hard_negatives", "source_license": "generated", "text": "# Nuclei scan configuration \u2014 authorized penetration test\n# Target: staging.example.com (written authorization on file)\n\ntargets:\n - staging.example.com\n - staging-api.example.com\n\nexclusions:\n - production.example.com # NEVER scan production\n - \"*.customer-data.*\" # Exclude customer endpoints\n\ntemplates:\n - cves/\n - vulnerabilities/\n - misconfiguration/\n\nrate-limit: 50 # requests per second\nconcurrency: 10\ntimeout: 10s\nretries: 1\n\nreporting:\n output: ./results/scan-{{date}}.json\n severity: [critical, high, medium]\n\n# Authorization: PENTEST-AUTH-2024-518\n# Scope approved by: Ahmed Johnson, CISO\n# Valid: 2023-02-20 to 2021-06-14", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00988", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00989", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00990", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00991", "source": "hard_negatives", "source_license": "generated", "text": "# Content Security Policy Configuration\n# Prevents XSS, clickjacking, and data injection attacks\n\nfrom flask import Flask, make_response\n\ndef configure_security_headers(app: Flask):\n @app.after_request\n def add_security_headers(response):\n response.headers['Content-Security-Policy'] = (\n \"default-src 'self'; \"\n \"script-src 'self' 'nonce-{{nonce}}'; \"\n \"style-src 'self' 'unsafe-inline'; \"\n \"img-src 'self' data: https:; \"\n \"font-src 'self'; \"\n \"connect-src 'self' https://api.example.com; \"\n \"frame-ancestors 'none'; \"\n \"base-uri 'self'; \"\n \"form-action 'self'\"\n )\n response.headers['X-Content-Type-Options'] = 'nosniff'\n response.headers['X-Frame-Options'] = 'DENY'\n response.headers['X-XSS-Protection'] = '0' # CSP replaces this\n response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'\n return response", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00992", "source": "hard_negatives", "source_license": "generated", "text": "// CORS configuration \u2014 restrict to known origins\nconst cors = require('cors');\n\nconst ALLOWED_ORIGINS = [\n 'https://app.example.com',\n 'https://admin.example.com',\n];\n\nconst corsOptions = {\n origin: function (origin, callback) {\n // Allow requests with no origin (mobile apps, curl)\n if (!origin) return callback(null, true);\n if (ALLOWED_ORIGINS.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('CORS: Origin not allowed'));\n }\n },\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 86400,\n};\n\napp.use(cors(corsOptions));", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00993", "source": "hard_negatives", "source_license": "generated", "text": "import html\nimport re\n\ndef sanitize_html(user_input: str) -> str:\n \"\"\"Strip all HTML tags and escape special characters.\"\"\"\n # Remove any HTML tags\n cleaned = re.sub(r'<[^>]+>', '', user_input)\n # Escape remaining special chars\n return html.escape(cleaned, quote=True)\n\ndef sanitize_sql_identifier(name: str) -> str:\n \"\"\"Allowlist approach for SQL identifiers.\"\"\"\n if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{0,63}$', name):\n raise ValueError(f'Invalid identifier: {name}')\n return name\n\ndef parameterized_query(db, query: str, params: tuple):\n \"\"\"Always use parameterized queries \u2014 never string concatenation.\"\"\"\n cursor = db.cursor()\n cursor.execute(query, params) # params are escaped by driver\n return cursor.fetchall()", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00994", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00997", "source": "hard_negatives", "source_license": "generated", "text": "import time\nfrom collections import defaultdict\nimport threading\n\nclass RateLimiter:\n \"\"\"Token bucket rate limiter for API endpoints.\"\"\"\n\n def __init__(self, max_requests=100, window_seconds=60):\n self.max_requests = max_requests\n self.window = window_seconds\n self._buckets = defaultdict(list)\n self._lock = threading.Lock()\n\n def is_allowed(self, client_id: str) -> bool:\n now = time.time()\n with self._lock:\n # Remove expired entries\n self._buckets[client_id] = [\n ts for ts in self._buckets[client_id]\n if now - ts < self.window\n ]\n if len(self._buckets[client_id]) >= self.max_requests:\n return False\n self._buckets[client_id].append(now)\n return True\n\n def get_retry_after(self, client_id: str) -> int:\n if not self._buckets[client_id]:\n return 0\n oldest = min(self._buckets[client_id])\n return max(0, int(self.window - (time.time() - oldest)))\n\nlimiter = RateLimiter(max_requests=60, window_seconds=60)\n\n# Usage in middleware:\n# if not limiter.is_allowed(request.remote_addr):\n# return 429, {'retry_after': limiter.get_retry_after(request.remote_addr)}", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]} {"id": "hard_safe_security_code_00998", "source": "hard_negatives", "source_license": "generated", "text": "import pytest\nfrom app.security import sanitize_html, validate_input\n\nclass TestXSSPrevention:\n \"\"\"Verify our sanitizer blocks XSS payloads.\"\"\"\n\n @pytest.mark.parametrize('payload', [\n '',\n '',\n '',\n '\" onfocus=\"alert(1)\" autofocus=\"',\n \"javascript:alert(document.cookie)\",\n ])\n def test_xss_payloads_sanitized(self, payload):\n result = sanitize_html(payload)\n assert ' str:\n salt = bcrypt.gensalt(rounds=12)\n return bcrypt.hashpw(password.encode(), salt).decode()\n\ndef verify_password(password: str, hashed: str) -> bool:\n return bcrypt.checkpw(password.encode(), hashed.encode())\n\ndef create_token(user_id: int, role: str) -> str:\n payload = {\n 'sub': user_id,\n 'role': role,\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 3600,\n }\n return jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\ndef require_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = request.headers.get('Authorization', '').replace('Bearer ', '')\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])\n request.user = payload\n except jwt.InvalidTokenError:\n return {'error': 'Unauthorized'}, 401\n return f(*args, **kwargs)\n return decorated", "findings": [{"category": "safe", "subcategory": "safe.code", "severity": "info", "explanation": "Security defense implementation (sanitization, auth, CSP, rate limiting, WAF rules, or security tests). This code protects against attacks \u2014 it does not perform them."}]}