synthetic-sensitive-data-in-source-code-n300 / generate_split_pattern_n300.py
nisaefendioglu's picture
v1.3.8: add OSS-carrier injection set, adversarial pilot and remaining generator scripts; update card
b2fecf7 verified
Raw History Blame Contribute Delete
9.28 kB
#!/usr/bin/env python3
"""Bölünmüş / dolaylı sır senaryoları (N=300) + önerilen özel regex kuralları."""
from __future__ import annotations
import csv
import json
import re
from pathlib import Path
from generate_dataset import (
fake_aws_key,
fake_conn,
fake_email,
fake_github_token,
fake_internal_url,
fake_openai_key,
fake_password,
)
OUT = Path(__file__).resolve().parent / "extensions"
TARGET = 300
def _variants(i: int) -> tuple[str, bool, str, list[dict], list[dict]]:
"""category, regex_expected_builtin, code, sensitive_findings, custom_rules."""
k1 = fake_openai_key(1000 + i)
k2 = fake_openai_key(2000 + i)
aws = fake_aws_key(3000 + i)
ghp = fake_github_token(4000 + i)
pw = fake_password(5000 + i)
conn = fake_conn(6000 + i, "postgres")
email = fake_email(7000 + i)
url = fake_internal_url(8000 + i)
prefix, suffix = k1[:8], k1[8:]
catalog = [
(
"split_concat",
False,
f'key = "{prefix}" + "{suffix}"\n',
[{"type": "api_key", "value": k1}],
[{"name": "split_sk", "pattern": r'"sk-proj-"\s*\+\s*"[A-Za-z0-9_-]+"'}],
),
(
"fstring_conn",
False,
f'user, pw = "app{i}", "S3cret{i}!"\n'
f'uri = f"postgres://{{user}}:{{pw}}@db-internal-{i}.corp.local:5432/orders"\n',
[{"type": "connection_string", "value": conn}],
[{"name": "fstring_uri", "pattern": r'f"postgres://\{[^}]+\}:\{[^}]+\}@[^"]+"'}],
),
(
"comment_secret",
False,
f"# eski parola: {pw}\nprint(ready)\n",
[{"type": "password_secret", "value": pw}],
[{"name": "comment_pw", "pattern": r"(?i)#.*(?:parola|password|secret)\s*:\s*\S+"}],
),
(
"split_backslash",
False,
f'api = "sk-proj-" \\\n + "{k2[8:]}"\n',
[{"type": "api_key", "value": k2}],
[
{
"name": "bs_split",
"pattern": r'"sk-proj-"\s*\\\s*\n\s*\+\s*"[A-Za-z0-9_-]+"',
}
],
),
(
"json_fragment_key",
False,
f'{{ "meta": "cfg", "openai_key":\n "{k1}" }}\n',
[{"type": "api_key", "value": k1}],
[{"name": "json_key_fold", "pattern": r'"openai_key":\s*\n\s*"[A-Za-z0-9_-]+"'}],
),
(
"yaml_fold",
False,
f"openai_key: >-\n {k1[:12]}\n {k1[12:]}\n",
[{"type": "api_key", "value": k1}],
[{"name": "yaml_fold_key", "pattern": r"openai_key:\s*>-\s*\n\s*\S+\s*\n\s*\S+"}],
),
(
"split_lines",
False,
f"p1 = '{aws[:8]}'\np2 = '{aws[8:]}'\nkey = p1 + p2\n",
[{"type": "api_key", "value": aws}],
[{"name": "split_aws", "pattern": r"p1\s*=\s*'AKIA[0-9A-Z]{4}'\s*\n\s*p2\s*=\s*'[0-9A-Z]+'"}],
),
(
"quoted_pieces_ghp",
False,
f'tok = "ghp_" + "{ghp[4:]}"\n',
[{"type": "api_key", "value": ghp}],
[{"name": "split_ghp", "pattern": r'"ghp_"\s*\+\s*"[A-Za-z0-9]+"'}],
),
(
"assign_via_dict",
False,
f'cfg = {{}}\ncfg["openai_key"] = "{k1}"\n',
[{"type": "api_key", "value": k1}],
[],
),
(
"literal_but_spaces",
False,
f"key = 'sk - proj - {k1[8:]}'\n",
[{"type": "api_key", "value": k1}],
[{"name": "spaced_sk", "pattern": r"sk\s*-\s*proj\s*-\s*[A-Za-z0-9_-]+"}],
),
(
"docx_like_zwsp",
False,
f'key = "{k1[0]}\u200b{k1[1:]}"\n',
[{"type": "api_key", "value": k1}],
[{"name": "zwsp_key", "pattern": r'key\s*=\s*"[^"]*\u200b[^"]*"'}],
),
(
"sql_concat",
False,
f'q = "SELECT * FROM t WHERE token=\'" + "{k1}" + "\'"\n',
[{"type": "api_key", "value": k1}],
[],
),
(
"dotenv_export",
False,
f'export OPENAI_KEY="{k1}"\n',
[{"type": "api_key", "value": k1}],
[],
),
(
"js_template",
False,
"const uri = `postgres://${user}:${pass}@db/app`;\n",
[{"type": "connection_string", "value": "postgres://"}],
[{"name": "js_pg", "pattern": r"`postgres://\$\{[^}]+\}:\$\{[^}]+\}@[^`]+`"}],
),
(
"kotlin_buildstring",
False,
f'val key = buildString {{ append("sk-proj-"); append("{k1[8:]}") }}\n',
[{"type": "api_key", "value": k1}],
[{"name": "kt_build", "pattern": r'append\("sk-proj-"\);\s*append\("[A-Za-z0-9_-]+"\)'}],
),
(
"plus_email",
False,
f'support = "{email[:6]}" + "{email[6:]}"\n',
[{"type": "email", "value": email}],
[{"name": "split_email", "pattern": r'"[A-Za-z0-9._%+-]+"\s*\+\s*"[A-Za-z0-9.-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"'}],
),
(
"url_builder",
False,
f'host = "intranet-api-{i}.corp.local"\npath = "/v1/users"\nurl = "https://" + host + path\n',
[{"type": "internal_url", "value": url}],
[{"name": "url_concat", "pattern": r'"https://"\s*\+\s*host\s*\+\s*path'}],
),
(
"visible_literal_control",
True,
f'openaiKey = "{k1}"\n',
[{"type": "api_key", "value": k1}],
[],
),
]
cat, expect, code, findings, custom = catalog[i % len(catalog)]
return cat, expect, code, findings, custom
def build_records() -> list[dict]:
recs: list[dict] = []
for i in range(1, TARGET + 1):
cat, expect, code, findings, custom = _variants(i)
contiguous = [f["value"] for f in findings if f.get("value") and f["value"] in code]
recs.append(
{
"id": f"SPL-{i:04d}",
"category": cat,
"language": "mixed",
"code_text": code,
"has_sensitive_data": bool(findings),
"regex_expected_builtin": expect,
"sensitive_findings": findings,
"contiguous_ground_truth": contiguous,
"custom_rules_recommended": custom,
"needs_custom_for_contiguous": bool(contiguous) and bool(custom),
}
)
return recs
def write_csv(records: list[dict], path: Path) -> None:
fields = [
"id",
"category",
"language",
"code_text",
"has_sensitive_data",
"regex_expected_builtin",
"needs_custom_for_contiguous",
"sensitive_findings_json",
"custom_rules_json",
]
with path.open("w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=fields)
w.writeheader()
for r in records:
w.writerow(
{
"id": r["id"],
"category": r["category"],
"language": r["language"],
"code_text": r["code_text"],
"has_sensitive_data": r["has_sensitive_data"],
"regex_expected_builtin": r.get("regex_expected_builtin"),
"needs_custom_for_contiguous": r.get("needs_custom_for_contiguous"),
"sensitive_findings_json": json.dumps(
r.get("sensitive_findings", []), ensure_ascii=False
),
"custom_rules_json": json.dumps(
r.get("custom_rules_recommended", []), ensure_ascii=False
),
}
)
def main() -> None:
OUT.mkdir(parents=True, exist_ok=True)
records = build_records()
if sum(1 for r in records if r.get("has_sensitive_data")) != TARGET:
raise SystemExit("Tüm kayıtlar hassas olmalı (N=300).")
payload = {
"name": "split_pattern_custom_n300",
"description": (
"Bölünmüş, birleştirilmiş veya biçim bozuculu sır örnekleri (N=300; tümü "
"hassas). Yerleşik regex ile kaçan contiguous sırlar için önerilen özel kurallar içerir."
),
"n": len(records),
"records": records,
}
path = OUT / "split_pattern_custom_n300.json"
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
manifest_path = OUT / "extension_manifest.json"
manifest = {}
if manifest_path.is_file():
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
csv_path = OUT / "split_pattern_custom_n300.csv"
write_csv(records, csv_path)
manifest["split_pattern_n300"] = {
"n": len(records),
"json": path.name,
"csv": csv_path.name,
}
manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
print(f"Wrote {path} ({len(records)} records)")
if __name__ == "__main__":
main()