from __future__ import annotations
import difflib
import json
from pathlib import Path
from typing import Any
from src.domain import DEFAULT_SEED, RULESET_ID, SCHEMA_ID, Split
from src.rules import rule_catalog, ruleset_meta
from src.schemas import Scenario
ROOT = Path(__file__).resolve().parents[1]
def _diff(path: str, before: str, after: str) -> str:
old = before.splitlines(keepends=True)
new = after.splitlines(keepends=True)
if old and not old[-1].endswith("\n"):
old[-1] += "\n"
if new and not new[-1].endswith("\n"):
new[-1] += "\n"
lines = list(
difflib.unified_diff(
old,
new,
fromfile=f"a/{path}",
tofile=f"b/{path}",
lineterm="\n",
)
)
header = [f"diff --git a/{path} b/{path}\n"]
return "".join(header + lines)
S01_BEFORE = '''"""Lab invoice reader for ledger-api. Synthetic."""
def get_invoice(invoice_id):
return {"id": invoice_id, "status": "draft"}
'''
S01_AFTER = '''"""Lab invoice reader for ledger-api. Synthetic."""
def get_invoice(invoice_id):
cursor.execute("SELECT * FROM invoices WHERE id = '" + invoice_id + "'")
return cursor.fetchone()
'''
S02_BEFORE = '''"""Lab directory listing for filesvc. Synthetic."""
import subprocess
def list_dir(name):
return name
'''
S02_AFTER = '''"""Lab directory listing for filesvc. Synthetic."""
import subprocess
def list_dir(name):
return subprocess.check_output("ls " + name, shell=True)
'''
S03_BEFORE = '''"""Lab download helper for filesvc. Synthetic."""
def download(filename):
return filename
'''
S03_AFTER = '''"""Lab download helper for filesvc. Synthetic."""
def download(filename):
return open("/var/data/" + filename, "rb").read()
'''
S04_BEFORE = '''"""Lab batch import for ledger-api. Synthetic."""
def import_batch(raw_body):
return raw_body
'''
S04_AFTER = '''"""Lab batch import for ledger-api. Synthetic."""
import pickle
def import_batch(raw_body):
return pickle.loads(raw_body)
'''
S05_BEFORE = '''"""Lab URL preview for fetch-proxy. Synthetic."""
def preview(url):
return url
'''
S05_AFTER = '''"""Lab URL preview for fetch-proxy. Synthetic."""
import urllib.request
def preview(url):
return urllib.request.urlopen(url).read()
'''
S06_BEFORE = '''"""Lab greeting for fetch-proxy. Synthetic."""
def greet(name):
return name
'''
S06_AFTER = '''"""Lab greeting for fetch-proxy. Synthetic."""
from markupsafe import Markup
def greet(name):
return Markup("
Hello " + name + "
")
'''
S07_BEFORE = '''"""Lab invoice reader for payments-api. Synthetic."""
def get_invoice(invoice_id):
return {"id": invoice_id}
'''
S07_AFTER = '''"""Lab invoice reader for payments-api. Synthetic."""
def get_invoice(invoice_id):
cursor.execute("SELECT * FROM invoices WHERE id = %s", (invoice_id,))
return cursor.fetchone()
'''
S08_BEFORE = '''"""Lab audit helper for notes-app. Synthetic."""
import logging
logger = logging.getLogger("notes")
def audit(username, n):
return username
'''
S08_AFTER = '''"""Lab audit helper for notes-app. Synthetic."""
import hashlib
import logging
logger = logging.getLogger("notes")
def audit(username, n):
# never call pickle.loads on user input
logger.info("audit execute() count=%s user=%s", n, username)
return hashlib.md5(b"static-lab-fixture").hexdigest()
'''
S09_BEFORE = '''"""Lab profile view for notes-app. Synthetic."""
def show(user_id):
return {"id": user_id}
'''
S09_AFTER = '''"""Lab profile view for notes-app. Synthetic."""
def show(user_id):
return db.execute(build_query(user_id))
'''
S10_BEFORE = '''"""Lab password store for payments-api. Synthetic."""
def store_password(password):
return password
'''
S10_AFTER = '''"""Lab password store for payments-api. Synthetic."""
import hashlib
def store_password(password):
return hashlib.md5(password.encode()).hexdigest()
'''
RELATED = {
"ledger-api/db.py": '"""Lab database stub. Cursor is not connected."""\n\ncursor = None\n',
"filesvc/paths.py": '"""Lab path constants."""\n\nBASE = "/var/data"\n',
"fetch-proxy/net.py": '"""Lab network stub."""\n\nALLOWED_HOSTS = ("example.test",)\n',
}
SCENARIOS: list[dict[str, Any]] = [
{
"scenario_id": "S01",
"family": "sql-injection",
"repository": "ledger-api",
"split": Split.DEVELOPMENT.value,
"title": "Ledger invoice query concatenates the identifier",
"title_fa": "پرسوجوی فاکتور دفتر کل شناسه را الحاق میکند",
"description": "A Python change in ledger-api builds SQL with string addition. The AST engine should confirm CWE-89 on the added execute line.",
"description_fa": "تغییر پایتون در ledger-api دستور SQL را با جمع رشته میسازد. موتور AST باید CWE-89 را روی خط execute تأیید کند.",
"path": "ledger-api/invoices.py",
"before": S01_BEFORE,
"after": S01_AFTER,
"related": ["ledger-api/db.py"],
"expected": {
"findings": [{"family": "sql-injection", "path": "ledger-api/invoices.py", "start_line": 4, "end_line": 4}],
"baseline_false_positive": False,
},
},
{
"scenario_id": "S02",
"family": "command-injection",
"repository": "filesvc",
"split": Split.DEVELOPMENT.value,
"title": "Directory listing uses shell=True",
"title_fa": "فهرست پوشه با shell=True اجرا میشود",
"description": "filesvc starts a shell command from the directory name. This is a confirmed command-injection finding.",
"description_fa": "filesvc فرمان پوسته را از نام پوشه میسازد. این یافته تزریق فرمان تأییدشده است.",
"path": "filesvc/listing.py",
"before": S02_BEFORE,
"after": S02_AFTER,
"related": ["filesvc/paths.py"],
"expected": {
"findings": [{"family": "command-injection", "path": "filesvc/listing.py", "start_line": 6, "end_line": 6}],
},
},
{
"scenario_id": "S03",
"family": "path-traversal",
"repository": "filesvc",
"split": Split.DEVELOPMENT.value,
"title": "Download opens a joined user path",
"title_fa": "دانلود مسیر الحاقشده کاربر را باز میکند",
"description": "open() joins /var/data/ with filename. There is no resolve-and-contain check.",
"description_fa": "open مسیر /var/data را با filename الحاق میکند و بررسی محدوده نیست.",
"path": "filesvc/download.py",
"before": S03_BEFORE,
"after": S03_AFTER,
"related": ["filesvc/paths.py"],
"expected": {
"findings": [{"family": "path-traversal", "path": "filesvc/download.py", "start_line": 4, "end_line": 4}],
},
},
{
"scenario_id": "S04",
"family": "insecure-deserialization",
"repository": "ledger-api",
"split": Split.DEVELOPMENT.value,
"title": "Batch import unpickles the request body",
"title_fa": "ورود دسته بدنه درخواست را unpickle میکند",
"description": "pickle.loads is applied to raw_body. The Space does not execute that call.",
"description_fa": "pickle.loads روی raw_body اعمال شده است. این Space آن را اجرا نمیکند.",
"path": "ledger-api/batch.py",
"before": S04_BEFORE,
"after": S04_AFTER,
"related": ["ledger-api/db.py"],
"expected": {
"findings": [{"family": "insecure-deserialization", "path": "ledger-api/batch.py", "start_line": 6, "end_line": 6}],
},
},
{
"scenario_id": "S05",
"family": "ssrf",
"repository": "fetch-proxy",
"split": Split.DEVELOPMENT.value,
"title": "Preview fetches a caller-controlled URL",
"title_fa": "پیشنمایش URL کنترلشده را واکشی میکند",
"description": "urlopen receives the url argument with no host allowlist.",
"description_fa": "urlopen آرگومان url را بدون فهرست میزبان مجاز میگیرد.",
"path": "fetch-proxy/preview.py",
"before": S05_BEFORE,
"after": S05_AFTER,
"related": ["fetch-proxy/net.py"],
"expected": {
"findings": [{"family": "ssrf", "path": "fetch-proxy/preview.py", "start_line": 6, "end_line": 6}],
},
},
{
"scenario_id": "S06",
"family": "xss-template",
"repository": "fetch-proxy",
"split": Split.DEVELOPMENT.value,
"title": "Greeting wraps input in Markup",
"title_fa": "سلام ورودی را در Markup میگذارد",
"description": "Markup concatenates the name into HTML. Auto-escaping is bypassed.",
"description_fa": "Markup نام را داخل HTML میگذارد و escape خودکار را دور میزند.",
"path": "fetch-proxy/greet.py",
"before": S06_BEFORE,
"after": S06_AFTER,
"related": ["fetch-proxy/net.py"],
"expected": {
"findings": [{"family": "xss-template", "path": "fetch-proxy/greet.py", "start_line": 6, "end_line": 6}],
},
},
{
"scenario_id": "S07",
"family": "sql-injection",
"repository": "payments-api",
"split": Split.TEST.value,
"title": "Payments query is parameterized",
"title_fa": "پرسوجوی پرداخت پارامتر دارد",
"description": "Hard negative: execute uses a constant SQL string and a bound parameter. The AST engine should stay quiet; the keyword baseline still flags execute().",
"description_fa": "نمونه منفی سخت: execute رشته ثابت و پارامتر دارد. موتور AST نباید یافته بدهد؛ خط مبنای کلیدواژه هنوز execute را میبیند.",
"path": "payments-api/invoices.py",
"before": S07_BEFORE,
"after": S07_AFTER,
"related": [],
"expected": {
"findings": [],
"baseline_false_positive": True,
"baseline_families": ["sql-injection"],
},
},
{
"scenario_id": "S08",
"family": "weak-crypto",
"repository": "notes-app",
"split": Split.TEST.value,
"title": "Audit log mentions pickle and execute",
"title_fa": "لاگ ممیزی از pickle و execute نام میبرد",
"description": "Hard negative: comments and a constant MD5 digest. Keyword baseline fires; AST should not confirm a weakness.",
"description_fa": "نمونه منفی سخت: توضیح و چکیده MD5 ثابت. خط مبنای کلیدواژه هشدار میدهد؛ AST ضعف را تأیید نمیکند.",
"path": "notes-app/audit.py",
"before": S08_BEFORE,
"after": S08_AFTER,
"related": [],
"expected": {
"findings": [],
"baseline_false_positive": True,
"baseline_families": ["sql-injection", "insecure-deserialization", "weak-crypto"],
},
},
{
"scenario_id": "S09",
"family": "sql-injection",
"repository": "notes-app",
"split": Split.TEST.value,
"title": "Profile view calls a missing query builder",
"title_fa": "نمای پروفایل سازنده پرسوجوی غایب را صدا میزند",
"description": "db.execute(build_query(user_id)) is visible, but build_query is not in the diff or related files. The reviewer must mark insufficient evidence and must not invent a file.",
"description_fa": "db.execute(build_query) دیده میشود ولی تعریف build_query در diff یا فایل مرتبط نیست. بازبین باید شواهد ناکافی بگذارد و فایل نسازد.",
"path": "notes-app/profile.py",
"before": S09_BEFORE,
"after": S09_AFTER,
"related": [],
"expected": {
"findings": [],
"expect_insufficient": True,
"expect_no_patch": True,
},
},
{
"scenario_id": "S10",
"family": "weak-crypto",
"repository": "payments-api",
"split": Split.TEST.value,
"title": "Password stored with MD5",
"title_fa": "گذرواژه با MD5 ذخیره میشود",
"description": "store_password hashes a password with MD5. Integrity hashes of constants are out of scope; this password helper is in scope.",
"description_fa": "store_password گذرواژه را با MD5 چکیده میکند. چکیده صحت مقدار ثابت خارج از محدوده است.",
"path": "payments-api/passwords.py",
"before": S10_BEFORE,
"after": S10_AFTER,
"related": [],
"expected": {
"findings": [{"family": "weak-crypto", "path": "payments-api/passwords.py", "start_line": 6, "end_line": 6}],
},
},
]
def scenario_records() -> list[Scenario]:
rows: list[Scenario] = []
for item in SCENARIOS:
rows.append(
Scenario(
scenario_id=item["scenario_id"],
family=item["family"],
repository=item["repository"],
split=item["split"],
title=item["title"],
title_fa=item["title_fa"],
description=item["description"],
description_fa=item["description_fa"],
diff_name=f"{item['scenario_id'].lower()}.diff",
related_names=list(item["related"]),
expected=item["expected"],
)
)
return rows
def scenarios() -> list[Scenario]:
return scenario_records()
def scenario_by_id(scenario_id: str) -> Scenario:
for item in scenarios():
if item.scenario_id == scenario_id:
return item
raise KeyError(scenario_id)
def scenario_payload(scenario_id: str) -> dict[str, Any]:
for item in SCENARIOS:
if item["scenario_id"] == scenario_id:
return item
raise KeyError(scenario_id)
def load_diff_text(name: str, root: Path | None = None) -> str:
folder = (root or ROOT) / "examples" / "diffs"
path = folder / name
if path.exists():
return path.read_text(encoding="utf-8")
scenario_id = name.split(".")[0].upper()
payload = scenario_payload(scenario_id)
return _diff(payload["path"], payload["before"], payload["after"])
def load_related_text(names: list[str]) -> str:
parts: list[str] = []
for name in names:
text = RELATED.get(name, "")
if text:
parts.append(f"=== {name} ===\n{text.rstrip()}\n")
return "\n".join(parts)
def write_examples(folder: Path, seed: int = DEFAULT_SEED) -> dict[str, str]:
folder.mkdir(parents=True, exist_ok=True)
diffs = folder / "diffs"
changes = folder / "changes"
diffs.mkdir(parents=True, exist_ok=True)
changes.mkdir(parents=True, exist_ok=True)
records = []
expected: dict[str, Any] = {}
splits = {"development": [], "test": [], "seed": seed, "group": "repository_and_family"}
for item in SCENARIOS:
path = item["path"]
diff_text = _diff(path, item["before"], item["after"])
(diffs / f"{item['scenario_id'].lower()}.diff").write_text(diff_text, encoding="utf-8")
case = changes / item["scenario_id"].lower()
before_dir = case / "before"
after_dir = case / "after"
related_dir = case / "related"
before_dir.mkdir(parents=True, exist_ok=True)
after_dir.mkdir(parents=True, exist_ok=True)
related_dir.mkdir(parents=True, exist_ok=True)
rel = Path(path)
(before_dir / rel.name).write_text(item["before"], encoding="utf-8")
(after_dir / rel.name).write_text(item["after"], encoding="utf-8")
for related_name in item["related"]:
related_path = related_dir / Path(related_name).name
related_path.write_text(RELATED[related_name], encoding="utf-8")
record = scenario_by_id(item["scenario_id"])
records.append(record.model_dump())
expected[item["scenario_id"]] = item["expected"]
splits[item["split"]].append(
{
"scenario_id": item["scenario_id"],
"repository": item["repository"],
"family": item["family"],
}
)
(folder / "scenarios.jsonl").write_text(
"\n".join(json.dumps(item, ensure_ascii=False) for item in records) + "\n",
encoding="utf-8",
)
(folder / "expected.json").write_text(json.dumps(expected, indent=2), encoding="utf-8")
(folder / "splits.json").write_text(json.dumps(splits, indent=2), encoding="utf-8")
schema = {
"schema_id": SCHEMA_ID,
"ruleset_id": RULESET_ID,
"language": "python",
"input": ["unified_diff", "optional_related_files"],
"finding": [
"finding_id",
"rule_id",
"family",
"cwe",
"path",
"start_line",
"review_state",
"missing_context",
"patch",
],
"max_changed_lines": 1000,
}
(folder / "schema.json").write_text(json.dumps(schema, indent=2), encoding="utf-8")
(folder / "rules.json").write_text(
json.dumps({"meta": ruleset_meta(), "rules": [item.model_dump() for item in rule_catalog()]}, indent=2, default=str),
encoding="utf-8",
)
return {"folder": str(folder), "n": str(len(SCENARIOS))}