File size: 12,646 Bytes
ed663e5
80a02b9
 
ed663e5
 
80a02b9
 
 
ed663e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80a02b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed663e5
 
 
 
 
 
 
80a02b9
ed663e5
 
 
80a02b9
ed663e5
 
 
80a02b9
 
 
 
 
ed663e5
80a02b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed663e5
 
 
80a02b9
 
 
ed663e5
 
 
 
 
 
 
 
80a02b9
 
 
 
ed663e5
 
 
 
 
 
 
 
 
80a02b9
 
 
 
ed663e5
 
80a02b9
ed663e5
80a02b9
 
ed663e5
 
80a02b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
#!/usr/bin/env python3
"""Validate a generated dataset directory: offsets, label counts, regex detectability, cluster / entity / replacement
consistency (v3), random samples.

Usage: python validate.py --data /path/to/dataset [--sample-files 2] [--n-eyeball 20] [--write-sample sample.jsonl --sample-n 500]
Hard failures (assert): bad offsets, dangling or inconsistent entity ids, surface forms that do not resolve to the
entity's form table, replacements with a different format/charset, replacement collisions inside a cluster,
non-contiguous clusters, duplicate entity ids. The sample written with --write-sample consists of whole clusters.
"""
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"),
}
PEM_ESCAPE = ("\n", "\\n\" +\n    \"")
PERSON_LABEL = {"full_name": "person_name", "first_name": "person_name", "last_name": "person_name", "username": "username", "handle": "username", "email": "email"}

def charset(v):
    return "+".join(k for k, rx in (("digit", "[0-9]"), ("lower", "[a-z]"), ("symbol", "[^A-Za-z0-9]"), ("upper", "[A-Z]")) if re.search(rx, v))

def check_cluster(recs, st, problems):
    """All invariants that need the whole cluster: entity table on doc 0, ids, forms, replacements, uniqueness."""
    cid = recs[0]["cluster_id"]
    if [r["doc_index"] for r in recs] != list(range(len(recs))) or any(r["cluster_size"] != len(recs) or r["cluster_kind"] != recs[0]["cluster_kind"] for r in recs):
        problems["cluster_shape"] += 1
    if recs[0]["entities"] is None or any(r["entities"] is not None for r in recs[1:]):
        problems["entities_placement"] += 1
    ents = {e["entity_id"]: e for e in (recs[0]["entities"] or [])}
    if len(ents) != len(recs[0]["entities"] or []):
        problems["duplicate_entity_id"] += 1
    seen = collections.Counter(); docs = collections.defaultdict(set)
    originals = set(); replacements = set()
    for e in ents.values():
        if not e["entity_id"].startswith(cid + "/"): problems["entity_id_prefix"] += 1
        if e["owner_entity_id"] is not None and ents.get(e["owner_entity_id"], {}).get("entity_type") != "person": problems["owner_unresolved"] += 1
        if e["entity_type"] == "person" and set(e["forms"]) != {"full_name", "first_name", "last_name", "username", "handle", "email"}: problems["person_forms"] += 1
        if e["entity_type"] != "person" and (e["forms"].get("literal") != e["canonical"] or e["replacement_forms"].get("literal") != e["replacement_canonical"]): problems["canonical_form"] += 1
        for k, v in e["forms"].items():
            originals.add(v)
            rv = e["replacement_forms"].get(k)
            if rv is None or rv == v: problems["replacement_missing_or_same"] += 1
            else: replacements.add(rv)
        if e["entity_type"] != "person":
            v, rv = e["canonical"], e["replacement_canonical"]
            rx = SCANNER.get(e["value_type"])
            if rx and bool(rx.search(v)) != bool(rx.search(rv)): problems["replacement_format"] += 1
            if e["value_type"] not in ("jwt", "basic_auth_b64") and charset(v) != charset(rv): problems["replacement_charset"] += 1
            if e["value_type"] not in ("password", "email", "jwt", "basic_auth_b64") and len(v) != len(rv): problems["replacement_length"] += 1
            if e["value_type"] == "pem_private_key" and v.split("\n")[0] != rv.split("\n")[0]: problems["replacement_pem_kind"] += 1
    if originals & replacements: problems["replacement_equals_original"] += 1
    for r in recs:
        t = r["text"]
        for s in r["spans"]:
            e = ents.get(s["entity_id"])
            if e is None: problems["span_entity_missing"] += 1; continue
            seen[e["entity_id"]] += 1; docs[e["entity_id"]].add(r["doc_index"])
            k = s["surface_form_type"]; fk = "literal" if k == "escaped_literal" else k
            form, repl = e["forms"].get(fk), e["replacement_forms"].get(fk)
            if k == "escaped_literal": form = form and form.replace(*PEM_ESCAPE); repl = repl and repl.replace(*PEM_ESCAPE)
            if form != s["value"]: problems["span_form_mismatch"] += 1
            if repl != s["replacement"]: problems["span_replacement_mismatch"] += 1
            exp_label = PERSON_LABEL.get(fk, e["entity_type"]) if e["entity_type"] == "person" else e["entity_type"]
            if s["label"] != exp_label: problems["span_label_vs_entity"] += 1
            st["surface_form"][k] += 1
        for s in r["hard_negatives"]:
            if s.get("entity_id") is not None or s.get("replacement") is not None: problems["negative_with_entity"] += 1
    for eid, e in ents.items():
        if seen[eid] == 0: problems["entity_without_span"] += 1
        if seen[eid] != e["n_mentions"] or len(docs[eid]) != e["n_docs"]: problems["entity_counts"] += 1
        st["entity_type"][e["entity_type"]] += 1
        st["docs_per_entity"][min(e["n_docs"], 6)] += 1; st["mentions_per_entity"][min(e["n_mentions"], 8)] += 1
        if e["owner_entity_id"]: st["owned_entities"] += 1
        if len(recs) > 1:
            st["multi_entities"] += 1; st["recurring_entities"] += e["n_docs"] > 1
    # gold anonymized text must keep the same scanner hits at the same spans (replacements are format-preserving)
    r = recs[0]; t = r["text"]; out = []; pos = 0; ok = True
    for s in sorted(r["spans"], key=lambda s: s["start"]):
        out.append(t[pos:s["start"]]); out.append(s["replacement"]); pos = s["end"]
        rx = SCANNER.get(s["value_type"])
        if rx and bool(rx.search(s["value"])) and not rx.search(s["replacement"]): ok = False
    out.append(t[pos:]); anon = "".join(out)
    if any(s["value"] in anon for s in r["spans"] if len(s["value"]) >= 8): problems["original_survives_in_gold_anonymized"] += 1
    if not ok: problems["gold_anonymized_scanner"] += 1
    st["clusters"] += 1; st["cluster_kind"][r["cluster_kind"]] += 1; st["cluster_size"][min(len(recs), 8)] += 1

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, help="approximate number of records (whole clusters are kept)")
    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, clusters=0, cluster_kind=C(), cluster_size=C(), entity_type=C(),
              docs_per_entity=C(), mentions_per_entity=C(), surface_form=C(), owned_entities=0, multi_entities=0, recurring_entities=0, cross_cluster_value_reuse_dictionary=0)
    problems = C(); det = C(); det_tot = C()
    all_entity_ids = set(); all_canonicals = C()
    reservoir = []; n_seen = 0      # reservoir over clusters
    for p in use:
        cur = []
        def finish():
            nonlocal n_seen
            if not cur: return
            check_cluster(cur, st, problems)
            for e in (cur[0]["entities"] or []):
                if e["entity_id"] in all_entity_ids: problems["global_duplicate_entity_id"] += 1
                all_entity_ids.add(e["entity_id"])
                if e["entity_type"] != "person": all_canonicals[(e["value_type"], e["canonical"])] += 1
            n_seen += 1
            if len(reservoir) < a.sample_n:
                reservoir.append(list(cur))
            else:
                j = random.randrange(n_seen)
                if j < a.sample_n: reservoir[j] = list(cur)
            cur.clear()
        with open(p, encoding="utf-8") as fh:
            for line in fh:
                r = json.loads(line); t = r["text"]
                if cur and r["cluster_id"] != cur[0]["cluster_id"]:
                    finish()
                cur.append(r)
                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
                prev_end = -1
                for s in sorted(r["spans"] + r["hard_negatives"], key=lambda s: s["start"]):
                    if s["start"] < prev_end: problems["overlap"] += 1
                    prev_end = s["end"]
                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
        finish()
    # short dictionary passwords / emails legitimately recur across clusters (reported); long random values must not
    st["cross_cluster_value_reuse_dictionary"] = sum(1 for (vt, v), n in all_canonicals.items() if n > 1 and vt in ("password", "email"))
    problems["cross_cluster_value_reuse_random"] = sum(1 for (vt, v), n in all_canonicals.items() if n > 1 and vt not in ("password", "email"))
    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)}
    out["problems"] = dict(problems)
    print(json.dumps(out, indent=1))
    assert st["bad_offsets"] == 0, st["bad_offsets"]
    assert not any(problems.values()), problems
    if a.write_sample:
        with open(a.write_sample, "w", encoding="utf-8") as fh:
            for cl in reservoir:
                for r in cl:
                    fh.write(json.dumps(r, ensure_ascii=False) + "\n")
    print("\n===== EYEBALL SAMPLES (clusters) =====")
    eye = [cl for cl in reservoir if any(r["spans"] or r["hard_negatives"] for r in cl)]
    for cl in random.sample(eye, min(a.n_eyeball, len(eye))):
        print(f"\n=== {cl[0]['cluster_id']} {cl[0]['cluster_kind']} size={len(cl)}")
        for e in cl[0]["entities"] or []:
            print(f"  ENT {e['entity_id'][-4:]} {e['entity_type']}/{e['value_type']} {e['canonical'][:40]!r} -> {e['replacement_canonical'][:40]!r} owner={e['owner_entity_id'] and e['owner_entity_id'][-4:]} docs={e['n_docs']} mentions={e['n_mentions']}")
        for r in cl:
            t = r["text"]
            print(f"--- doc {r['doc_index']} {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
                eid = s.get("entity_id"); eid = eid[-4:] if eid else "-"
                print(f"  [{s['label']}/{s['value_type']} {eid}] {t[ls:le][:140]!r}")

if __name__ == "__main__":
    main()