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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Sentetik hassas-veri gömülü kod/config veri seti üreticisi.
Tüm örnekler en az bir hassas bulgu içerir (negatif örnek yok).
Alan: code_text (çıplak kod/config; LLM prompt sarmalayıcısı yok).
Hedef: 300 örnek.
"""

from __future__ import annotations

import csv
import json
import random
from pathlib import Path

OUT_DIR = Path(__file__).resolve().parent
RNG = random.Random(42)  # tekrarlanabilir

OWASP_TAG = "OWASP_LLM02_Sensitive_Information_Disclosure"
THESIS_RISK = "prompt_data_leakage"

CATEGORIES = [
    "api_key",
    "password_secret",
    "connection_string",
    "internal_url",
    "pii",
    "private_key_keystore",
    "multi_secret",
]

# Hedef dağılım (300)
TARGET_COUNTS = {
    "api_key": 55,
    "password_secret": 50,
    "connection_string": 45,
    "internal_url": 40,
    "pii": 45,
    "private_key_keystore": 30,
    "multi_secret": 35,
}  # toplam 300


def fake_openai_key(i: int) -> str:
    return f"sk-proj-{''.join(RNG.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=20))}{i:04d}"


def fake_aws_key(i: int) -> str:
    return f"AKIA{''.join(RNG.choices('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=16))}"


def fake_google_key(i: int) -> str:
    return f"AIza{''.join(RNG.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_', k=35))}"


def fake_github_token(i: int) -> str:
    return f"ghp_{''.join(RNG.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=36))}"


def fake_stripe_key(i: int) -> str:
    return f"sk_live_{''.join(RNG.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=24))}"


def fake_password(i: int) -> str:
    words = ["S3cret", "P@ssw0rd", "Adm1n!", "Tr0ya#", "N1saSecure", "DbRoot!"]
    return f"{RNG.choice(words)}{i:03d}!"


def fake_bearer(i: int) -> str:
    return f"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.fakePayload{i}.sig{i:04d}"


def fake_conn(i: int, kind: str) -> str:
    user, pwd, host, db = f"app{i}", fake_password(i), f"db-internal-{i}.corp.local", f"orders_{i}"
    if kind == "postgres":
        return f"postgres://{user}:{pwd}@{host}:5432/{db}"
    if kind == "mysql":
        return f"mysql://{user}:{pwd}@{host}:3306/{db}"
    if kind == "mongo":
        return f"mongodb://{user}:{pwd}@{host}:27017/{db}?authSource=admin"
    if kind == "mssql":
        return f"Server={host};Database={db};User Id={user};Password={pwd};"
    return f"redis://:{pwd}@{host}:6379/0"


def fake_internal_url(i: int) -> str:
    hosts = [
        f"https://intranet-api-{i}.corp.local/v1/users",
        f"http://10.20.30.{i % 200}/admin",
        f"https://jenkins.internal.bank.tr/job/deploy-{i}",
        f"https://vault.svc.cluster.local:8200/v1/secret/data/app{i}",
        f"https://gitlab.internal.example/group/repo-{i}.git",
    ]
    return hosts[i % len(hosts)]


def fake_email(i: int) -> str:
    return f"ahmet.yilmaz{i}@ornek-sirket.com.tr"


def fake_phone(i: int) -> str:
    return f"+90532{1000000 + i:07d}"[:13]


def fake_tc_like(i: int) -> str:
    # Sentetik; gerçek TCKN değil — biçim benzeri 11 hane
    base = f"{10000000000 + i * 17}"
    return base[:11]


def fake_pem_snippet(i: int) -> str:
    body = "".join(RNG.choices("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", k=64))
    return (
        "-----BEGIN PRIVATE KEY-----\n"
        f"{body}{i:04d}\n"
        "-----END PRIVATE KEY-----"
    )


LANGS = ["python", "javascript", "java", "csharp", "env", "yaml", "json", "bash", "kotlin", "go"]


def make_record(
    idx: int,
    category: str,
    language: str,
    code_text: str,
    secrets: list[dict],
    secondary_tags: list[str] | None = None,
) -> dict:
    assert secrets, "Her kayıtta en az bir hassas bulgu olmalı"
    return {
        "id": f"SDS-{idx:04d}",
        "category": category,
        "language": language,
        "code_text": code_text,
        "has_sensitive_data": True,
        "sensitive_findings": secrets,
        "sensitive_count": len(secrets),
        "thesis_risk": THESIS_RISK,
        "secondary_tags": secondary_tags or [],
        "split": "eval",
    }


def gen_api_key(i: int) -> dict:
    lang = RNG.choice(["python", "javascript", "env", "bash", "kotlin"])
    makers = [
        ("openai", fake_openai_key),
        ("aws", fake_aws_key),
        ("google", fake_google_key),
        ("github", fake_github_token),
        ("stripe", fake_stripe_key),
    ]
    provider, fn = makers[i % len(makers)]
    key = fn(i)
    if lang == "python":
        code = f'import os\nAPI_KEY = "{key}"\nclient = OpenAI(api_key=API_KEY)\nprint(client.models.list())'
    elif lang == "javascript":
        code = f'const apiKey = "{key}";\nfetch("https://api.example.com", {{ headers: {{ Authorization: `Bearer ${{apiKey}}` }} }});'
    elif lang == "env":
        code = f"OPENAI_API_KEY={key}\nNODE_ENV=production"
    elif lang == "bash":
        code = f'export {provider.upper()}_API_KEY="{key}"\ncurl -H "Authorization: Bearer $API_KEY" https://api.example.com'
    else:
        code = f'val apiKey = "{key}"\nval client = ApiClient(apiKey)'
    return make_record(
        i,
        "api_key",
        lang,
        code,
        [{"type": "api_key", "provider": provider, "value": key}],
        ["hardcoded_credential"],
    )


def gen_password(i: int) -> dict:
    lang = RNG.choice(["python", "java", "yaml", "env", "csharp"])
    pwd = fake_password(i)
    token = fake_bearer(i)
    use_bearer = i % 3 == 0
    if lang == "python":
        if use_bearer:
            code = (
                f'DB_PASSWORD = "{pwd}"\n'
                f'headers = {{"Authorization": "Bearer {token}"}}\n'
            )
            findings = [
                {"type": "password", "value": pwd},
                {"type": "bearer_token", "value": token},
            ]
        else:
            code = f'password = "{pwd}"\nconn = login(user="admin", password=password)\n'
            findings = [{"type": "password", "value": pwd}]
    elif lang == "java":
        code = f'String password = "{pwd}";\nDataSource ds = DataSourceBuilder.create().password(password).build();'
        findings = [{"type": "password", "value": pwd}]
    elif lang == "yaml":
        code = f"spring:\n  datasource:\n    username: admin\n    password: {pwd}"
        findings = [{"type": "password", "value": pwd}]
    elif lang == "env":
        if use_bearer:
            code = f"ADMIN_PASSWORD={pwd}\nJWT_SECRET={token}"
            findings = [
                {"type": "password", "value": pwd},
                {"type": "bearer_token", "value": token},
            ]
        else:
            code = f"ADMIN_PASSWORD={pwd}\nJWT_SECRET={pwd}"
            findings = [{"type": "password", "value": pwd}]
    else:
        code = f'var password = "{pwd}";\nvar connection = new SqlConnection($"Server=.;Password={pwd};");'
        findings = [{"type": "password", "value": pwd}]
    return make_record(
        i,
        "password_secret",
        lang,
        code,
        findings,
        ["hardcoded_credential", "auth_secret"],
    )


def gen_conn(i: int) -> dict:
    kind = ["postgres", "mysql", "mongo", "mssql", "redis"][i % 5]
    lang = RNG.choice(["python", "env", "csharp", "go", "javascript"])
    conn = fake_conn(i, kind)
    if lang == "python":
        code = f'DATABASE_URL = "{conn}"\nengine = create_engine(DATABASE_URL)'
    elif lang == "env":
        code = f"DATABASE_URL={conn}"
    elif lang == "csharp":
        code = f'string cs = "{conn}";\nusing var conn = new SqlConnection(cs);'
    elif lang == "go":
        code = f'sql.Open("postgres", "{conn}")'
    else:
        code = f'const connectionString = "{conn}";\nmongoose.connect(connectionString);'
    return make_record(
        i,
        "connection_string",
        lang,
        code,
        [{"type": "connection_string", "engine": kind, "value": conn}],
        ["credential_in_uri"],
    )


def gen_url(i: int) -> dict:
    lang = RNG.choice(["python", "javascript", "bash", "yaml", "java"])
    url = fake_internal_url(i)
    if lang == "python":
        code = f'BASE_URL = "{url}"\nrequests.get(BASE_URL, headers={{"X-Api-Key": "internal"}})'
    elif lang == "javascript":
        code = f'const endpoint = "{url}";\naxios.get(endpoint);'
    elif lang == "bash":
        code = f'curl -k "{url}"'
    elif lang == "yaml":
        code = f"services:\n  api:\n    url: {url}"
    else:
        code = f'String url = "{url}";\nHttpClient.newHttpClient().send(HttpRequest.newBuilder(URI.create(url)).build(), BodyHandlers.ofString());'
    return make_record(
        i,
        "internal_url",
        lang,
        code,
        [{"type": "internal_url", "value": url}],
        ["internal_host_exposure"],
    )


def gen_pii(i: int) -> dict:
    lang = RNG.choice(["python", "javascript", "json", "java", "csharp"])
    email = fake_email(i)
    phone = fake_phone(i)
    tc = fake_tc_like(i)
    pick = i % 3
    if pick == 0:
        findings = [{"type": "pii_email", "value": email}]
        payload = email
    elif pick == 1:
        findings = [{"type": "pii_phone", "value": phone}]
        payload = phone
    else:
        findings = [{"type": "pii_national_id_like", "value": tc}]
        payload = tc

    if lang == "python":
        code = f'user = {{"name": "Test User", "contact": "{payload}", "role": "customer"}}\nprint(user)'
    elif lang == "javascript":
        code = f'const customer = {{ contact: "{payload}" }};\nsendToCrm(customer);'
    elif lang == "json":
        code = '{\n  "customer": {\n' f'    "contact": "{payload}"\n' "  }\n}"
    elif lang == "java":
        code = f'String contact = "{payload}";\nrepository.save(new Customer(contact));'
    else:
        code = f'var contact = "{payload}";\nawait db.Customers.AddAsync(new Customer {{ Contact = contact }});'
    return make_record(i, "pii", lang, code, findings, ["pii_exposure", "kvkk_relevant"])


def gen_private_key(i: int) -> dict:
    lang = RNG.choice(["python", "bash", "yaml", "env", "javascript"])
    pem = fake_pem_snippet(i)
    keystore_pass = fake_password(i + 900)
    if i % 2 == 0:
        code = f'PRIVATE_KEY = """{pem}"""\nload_pem_private_key(PRIVATE_KEY.encode(), password=None)'
        findings = [{"type": "private_key_pem", "value": pem}]
        tags = ["private_key_in_source"]
    else:
        code = (
            f'keystore_path = "/opt/app/prod.jks"\n'
            f'keystore_password = "{keystore_pass}"\n'
            f'KeyStore.getInstance("JKS").load(open(keystore_path,"rb"), keystore_password)'
        )
        findings = [{"type": "keystore_password", "value": keystore_pass}]
        tags = ["keystore_secret"]
        pem = keystore_pass
    return make_record(i, "private_key_keystore", lang, code, findings, tags)


def gen_multi(i: int) -> dict:
    lang = RNG.choice(["python", "env", "javascript", "yaml"])
    key = fake_openai_key(i)
    pwd = fake_password(i)
    conn = fake_conn(i, "postgres")
    email = fake_email(i)
    url = fake_internal_url(i)
    if lang == "python":
        code = (
            f'OPENAI_KEY = "{key}"\n'
            f'DATABASE_URL = "{conn}"\n'
            f'ADMIN_PASSWORD = "{pwd}"\n'
            f'SUPPORT_EMAIL = "{email}"\n'
            f'INTERNAL_API = "{url}"\n'
        )
    elif lang == "env":
        code = (
            f"OPENAI_API_KEY={key}\n"
            f"DATABASE_URL={conn}\n"
            f"ADMIN_PASSWORD={pwd}\n"
            f"SUPPORT_EMAIL={email}\n"
            f"INTERNAL_API={url}\n"
        )
    elif lang == "javascript":
        code = (
            f'export const config = {{\n'
            f'  openaiKey: "{key}",\n'
            f'  dbUrl: "{conn}",\n'
            f'  adminPassword: "{pwd}",\n'
            f'  supportEmail: "{email}",\n'
            f'  internalApi: "{url}",\n'
            f'}};\n'
        )
    else:
        code = (
            f"app:\n"
            f"  openai_key: {key}\n"
            f"  database_url: {conn}\n"
            f"  admin_password: {pwd}\n"
            f"  support_email: {email}\n"
            f"  internal_api: {url}\n"
        )
    findings = [
        {"type": "api_key", "provider": "openai", "value": key},
        {"type": "connection_string", "engine": "postgres", "value": conn},
        {"type": "password", "value": pwd},
        {"type": "pii_email", "value": email},
        {"type": "internal_url", "value": url},
    ]
    # Label every secret present in code_text (complete ground truth for eval).
    return make_record(
        i,
        "multi_secret",
        lang,
        code,
        findings,
        ["multiple_leak_vectors", "config_spill"],
    )


GENERATORS = {
    "api_key": gen_api_key,
    "password_secret": gen_password,
    "connection_string": gen_conn,
    "internal_url": gen_url,
    "pii": gen_pii,
    "private_key_keystore": gen_private_key,
    "multi_secret": gen_multi,
}


def build_dataset() -> list[dict]:
    records: list[dict] = []
    idx = 1
    for cat, n in TARGET_COUNTS.items():
        gen = GENERATORS[cat]
        for _ in range(n):
            rec = gen(idx)
            # id'yi sıralı tut
            rec["id"] = f"SDS-{idx:04d}"
            records.append(rec)
            idx += 1
    RNG.shuffle(records)
    # shuffle sonrası id'leri yeniden sıralı yap (tezde takip kolay olsun)
    for i, rec in enumerate(records, start=1):
        rec["id"] = f"SDS-{i:04d}"
    return records


def validate(records: list[dict]) -> None:
    assert 250 <= len(records) <= 300, len(records)
    for r in records:
        assert r["has_sensitive_data"] is True
        assert r["sensitive_count"] >= 1
        assert r["sensitive_findings"]
        for f in r["sensitive_findings"]:
            assert f.get("value"), r["id"]
            assert str(f["value"]) in r["code_text"], (r["id"], f["type"])


def write_outputs(records: list[dict]) -> None:
    json_path = OUT_DIR / "synthetic_sensitive_data_in_source_code_n300.json"
    csv_path = OUT_DIR / "synthetic_sensitive_data_in_source_code_n300.csv"
    meta_path = OUT_DIR / "dataset_stats.json"

    with json_path.open("w", encoding="utf-8") as f:
        json.dump(
            {
                "name": "Synthetic Sensitive Data in Source Code (N=300)",
                "version": "1.2",
                "description": (
                    "Sentetik kod/config örnekleri; tamamı hassas veri sızıntısı içerir. "
                    "LLM prompt sarmalayıcısı yoktur (code_text). "
                    "multi_secret örneklerinde kodda bulunan tüm sırlar ground truth’ta etiketlenir. "
                    "Tüm örnekler OWASP LLM02 Sensitive Information Disclosure kapsamında değerlendirilir "
                    "(satır bazlı owasp sütunu yoktur; dataset metadata'da belirtilir)."
                ),
                "size": len(records),
                "owasp_primary": OWASP_TAG,
                "records": records,
            },
            f,
            ensure_ascii=False,
            indent=2,
        )

    with csv_path.open("w", encoding="utf-8", newline="") as f:
        w = csv.DictWriter(
            f,
            fieldnames=[
                "id",
                "category",
                "language",
                "sensitive_count",
                "finding_types",
                "code_text",
            ],
        )
        w.writeheader()
        for r in records:
            w.writerow(
                {
                    "id": r["id"],
                    "category": r["category"],
                    "language": r["language"],
                    "sensitive_count": r["sensitive_count"],
                    "finding_types": "|".join(x["type"] for x in r["sensitive_findings"]),
                    "code_text": r["code_text"].replace("\n", "\\n"),
                }
            )

    from collections import Counter

    stats = {
        "total": len(records),
        "by_category": dict(Counter(r["category"] for r in records)),
        "by_language": dict(Counter(r["language"] for r in records)),
        "avg_secrets_per_sample": round(
            sum(r["sensitive_count"] for r in records) / len(records), 2
        ),
        "all_contain_sensitive_data": all(r["has_sensitive_data"] for r in records),
    }
    with meta_path.open("w", encoding="utf-8") as f:
        json.dump(stats, f, ensure_ascii=False, indent=2)

    print(json.dumps(stats, ensure_ascii=False, indent=2))
    print(f"Wrote {json_path}")
    print(f"Wrote {csv_path}")


def main() -> None:
    records = build_dataset()
    validate(records)
    write_outputs(records)


if __name__ == "__main__":
    main()