File size: 4,750 Bytes
ed663e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Validate a generated dataset directory: offsets, label counts, regex detectability, random samples.

Usage: python validate.py --data /path/to/dataset [--sample-files 2] [--n-eyeball 20] [--write-sample sample.jsonl --sample-n 500]
"""
import argparse, collections, glob, json, os, random, re

SCANNER = {  # a deliberately simple regex scanner (gitleaks-like) used only as a sanity check
    "aws_access_key_id": re.compile(r"AKIA[0-9A-Z]{16}"),
    "github_pat": re.compile(r"gh[pos]_[A-Za-z0-9]{36}"),
    "github_fine_grained_pat": re.compile(r"github_pat_[A-Za-z0-9]{22}_[A-Za-z0-9]{59}"),
    "slack_token": re.compile(r"xox[abp]-[0-9A-Za-z-]{10,}"),
    "jwt": re.compile(r"eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+"),
    "google_api_key": re.compile(r"AIza[0-9A-Za-z_-]{35}"),
    "stripe_secret_key": re.compile(r"(?:sk|rk)_(?:live|test)_[0-9A-Za-z]{24}"),
    "pem_private_key": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
    "email": re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"),
    "sendgrid_api_key": re.compile(r"SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}"),
    "openai_api_key": re.compile(r"sk-(?:proj-)?[A-Za-z0-9]{48}"),
    "hf_token": re.compile(r"hf_[A-Za-z0-9]{34}"),
    "gitlab_pat": re.compile(r"glpat-[A-Za-z0-9_-]{20}"),
    "npm_token": re.compile(r"npm_[A-Za-z0-9]{36}"),
    "generic_hex_key": re.compile(r"\b[0-9a-f]{32,64}\b"),
}

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--data", required=True)
    ap.add_argument("--sample-files", type=int, default=2)
    ap.add_argument("--n-eyeball", type=int, default=20)
    ap.add_argument("--write-sample")
    ap.add_argument("--sample-n", type=int, default=500)
    ap.add_argument("--seed", type=int, default=0)
    a = ap.parse_args()
    random.seed(a.seed)
    parts = sorted(glob.glob(os.path.join(a.data, "part-*.jsonl")))
    use = parts[:a.sample_files]
    C = collections.Counter
    st = dict(files=0, injected=0, clean=0, spans=0, negs=0, bad_offsets=0, label=C(), vtype=C(), ctx=C(), lang=C(), negtype=C(),
              size_hist=C(), spans_per_file=C(), bytes=0)
    det = C(); det_tot = C()
    reservoir = []; n_seen = 0
    for p in use:
        with open(p, encoding="utf-8") as fh:
            for line in fh:
                r = json.loads(line); t = r["text"]
                st["files"] += 1; st["bytes"] += len(line)
                st["lang"][r["language"]] += 1
                st["size_hist"][("<1KB" if len(t) < 1024 else "<10KB" if len(t) < 10240 else "<100KB" if len(t) < 102400 else ">=100KB")] += 1
                st["spans_per_file"][min(len(r["spans"]), 6)] += 1
                st["injected" if r["spans"] else "clean"] += 1
                for s in r["spans"] + r["hard_negatives"]:
                    if t[s["start"]:s["end"]] != s["value"]:
                        st["bad_offsets"] += 1
                for s in r["spans"]:
                    st["spans"] += 1; st["label"][s["label"]] += 1; st["vtype"][s["value_type"]] += 1; st["ctx"][s["context"]] += 1
                    rx = SCANNER.get(s["value_type"])
                    if rx:
                        det_tot[s["value_type"]] += 1
                        if rx.search(s["value"]) and any(m.start() <= s["start"] < m.end() for m in rx.finditer(t)):
                            det[s["value_type"]] += 1
                for s in r["hard_negatives"]:
                    st["negs"] += 1; st["negtype"][s["value_type"]] += 1
                n_seen += 1
                if len(reservoir) < a.sample_n:
                    reservoir.append(r)
                else:
                    j = random.randrange(n_seen)
                    if j < a.sample_n: reservoir[j] = r
    assert st["bad_offsets"] == 0, st["bad_offsets"]
    out = {k: (dict(v.most_common()) if isinstance(v, C) else v) for k, v in st.items()}
    out["regex_detectability"] = {k: f"{det[k]}/{det_tot[k]} ({100*det[k]/det_tot[k]:.1f}%)" for k in sorted(det_tot)}
    print(json.dumps(out, indent=1))
    if a.write_sample:
        with open(a.write_sample, "w", encoding="utf-8") as fh:
            for r in reservoir:
                fh.write(json.dumps(r, ensure_ascii=False) + "\n")
    print("\n===== EYEBALL SAMPLES =====")
    eye = [r for r in reservoir if r["spans"] or r["hard_negatives"]]
    for r in random.sample(eye, min(a.n_eyeball, len(eye))):
        t = r["text"]
        print(f"\n--- {r['id']} {r['language']} {r['path']}")
        for s in r["spans"] + r["hard_negatives"]:
            ls = t.rfind("\n", 0, s["start"]) + 1; le = t.find("\n", s["end"]); le = len(t) if le < 0 else le
            print(f"  [{s['label']}/{s['value_type']}] {t[ls:le][:160]!r}")

if __name__ == "__main__":
    main()