dpdp-scan 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dpdp_scan/__init__.py +15 -0
- dpdp_scan/allow.py +32 -0
- dpdp_scan/baseline.py +75 -0
- dpdp_scan/bench/__init__.py +293 -0
- dpdp_scan/bench/__main__.py +43 -0
- dpdp_scan/catalogue.py +165 -0
- dpdp_scan/cli.py +244 -0
- dpdp_scan/config.py +162 -0
- dpdp_scan/detectors/__init__.py +76 -0
- dpdp_scan/detectors/allowlist.py +77 -0
- dpdp_scan/detectors/base.py +94 -0
- dpdp_scan/detectors/checksums.py +76 -0
- dpdp_scan/detectors/india.py +452 -0
- dpdp_scan/engine.py +84 -0
- dpdp_scan/masking.py +73 -0
- dpdp_scan/model.py +148 -0
- dpdp_scan/output/__init__.py +7 -0
- dpdp_scan/output/inventory.py +119 -0
- dpdp_scan/output/markdown.py +72 -0
- dpdp_scan/output/sarif.py +162 -0
- dpdp_scan/rules/dpdpa.yml +261 -0
- dpdp_scan/schema/__init__.py +68 -0
- dpdp_scan/schema/lexicon.py +365 -0
- dpdp_scan/schema/parsers.py +240 -0
- dpdp_scan/semgrep_findings.py +120 -0
- dpdp_scan/semgrep_runner.py +184 -0
- dpdp_scan/walker.py +183 -0
- dpdp_scan-0.1.1.dist-info/METADATA +203 -0
- dpdp_scan-0.1.1.dist-info/RECORD +34 -0
- dpdp_scan-0.1.1.dist-info/WHEEL +5 -0
- dpdp_scan-0.1.1.dist-info/entry_points.txt +2 -0
- dpdp_scan-0.1.1.dist-info/licenses/LICENSE +202 -0
- dpdp_scan-0.1.1.dist-info/licenses/NOTICE +20 -0
- dpdp_scan-0.1.1.dist-info/top_level.txt +1 -0
dpdp_scan/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""dpdp-scan: find Indian personal data in code, schemas, fixtures and logs.
|
|
2
|
+
|
|
3
|
+
Every finding names the DPDP Act, 2023 section or DPDP Rules, 2025 rule it
|
|
4
|
+
touches. The tool reports an inventory and risky patterns; it never gives a
|
|
5
|
+
compliance verdict, and it is not legal advice.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
__version__ = version("dpdp-scan")
|
|
12
|
+
except PackageNotFoundError: # running from a checkout without an install
|
|
13
|
+
__version__ = "0.0.0"
|
|
14
|
+
|
|
15
|
+
__all__ = ["__version__"]
|
dpdp_scan/allow.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""User allowlist: values accepted by hash, and the organisation's own domains.
|
|
2
|
+
|
|
3
|
+
Kept free of other dpdp-scan imports so both the detectors and the config
|
|
4
|
+
loader can use it without a cycle.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def value_hash(compact: str) -> str:
|
|
14
|
+
"""sha256 of the compact (separator-free, upper-cased) value."""
|
|
15
|
+
return hashlib.sha256(compact.encode("utf-8")).hexdigest()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True, slots=True)
|
|
19
|
+
class AllowList:
|
|
20
|
+
#: Email and UPI findings whose domain or handle is one of these are dropped.
|
|
21
|
+
domains: tuple[str, ...] = ()
|
|
22
|
+
#: sha256 hex digests of compact values that are known not to be anyone's.
|
|
23
|
+
value_hashes: frozenset[str] = frozenset()
|
|
24
|
+
|
|
25
|
+
def allows_value(self, compact: str) -> bool:
|
|
26
|
+
return bool(self.value_hashes) and value_hash(compact) in self.value_hashes
|
|
27
|
+
|
|
28
|
+
def allows_domain(self, compact: str) -> bool:
|
|
29
|
+
if "@" not in compact or not self.domains:
|
|
30
|
+
return False
|
|
31
|
+
domain = compact.rsplit("@", 1)[1].lower()
|
|
32
|
+
return any(domain == d or domain.endswith("." + d) for d in self.domains)
|
dpdp_scan/baseline.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Baseline: accept the findings a repository already has.
|
|
2
|
+
|
|
3
|
+
The gitleaks shape. ``--write-baseline`` records a fingerprint for every
|
|
4
|
+
current finding; ``--baseline`` drops findings whose fingerprint is recorded
|
|
5
|
+
so CI only fails on what is new. A fingerprint covers the detector, the path,
|
|
6
|
+
the line and the masked evidence or locator, never a value, so the file is
|
|
7
|
+
safe to commit.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from datetime import UTC, datetime
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from dpdp_scan import __version__
|
|
18
|
+
from dpdp_scan.model import Finding, Inventory, fingerprint
|
|
19
|
+
|
|
20
|
+
BASELINE_VERSION = 1
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class BaselineError(ValueError):
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True, slots=True)
|
|
28
|
+
class Baseline:
|
|
29
|
+
fingerprints: frozenset[str]
|
|
30
|
+
generated_at: str = ""
|
|
31
|
+
source: str = ""
|
|
32
|
+
|
|
33
|
+
def contains(self, f: Finding) -> bool:
|
|
34
|
+
return fingerprint(f) in self.fingerprints
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def write_baseline(path: Path, inventory: Inventory) -> int:
|
|
38
|
+
fps = sorted({fingerprint(f) for f in inventory.findings})
|
|
39
|
+
doc = {
|
|
40
|
+
"version": BASELINE_VERSION,
|
|
41
|
+
"tool": "dpdp-scan",
|
|
42
|
+
"tool_version": __version__,
|
|
43
|
+
"generated_at": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
44
|
+
"note": "Fingerprints of accepted findings. No values are stored.",
|
|
45
|
+
"fingerprints": fps,
|
|
46
|
+
}
|
|
47
|
+
path.write_text(json.dumps(doc, indent=2) + "\n", encoding="utf-8")
|
|
48
|
+
return len(fps)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def load_baseline(path: Path) -> Baseline:
|
|
52
|
+
try:
|
|
53
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
54
|
+
except OSError as exc:
|
|
55
|
+
raise BaselineError(f"cannot read {path}: {exc.strerror}") from exc
|
|
56
|
+
except ValueError as exc:
|
|
57
|
+
raise BaselineError(f"{path}: not valid JSON") from exc
|
|
58
|
+
if not isinstance(data, dict) or data.get("version") != BASELINE_VERSION:
|
|
59
|
+
raise BaselineError(f"{path}: not a dpdp-scan baseline (version {BASELINE_VERSION})")
|
|
60
|
+
fps = data.get("fingerprints")
|
|
61
|
+
if not isinstance(fps, list) or not all(isinstance(x, str) for x in fps):
|
|
62
|
+
raise BaselineError(f"{path}: fingerprints must be a list of strings")
|
|
63
|
+
return Baseline(frozenset(fps), str(data.get("generated_at", "")), str(path))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def apply_baseline(inventory: Inventory, baseline: Baseline) -> tuple[Inventory, int]:
|
|
67
|
+
"""Return (findings not in the baseline, how many were suppressed)."""
|
|
68
|
+
kept = Inventory()
|
|
69
|
+
suppressed = 0
|
|
70
|
+
for f in inventory.findings:
|
|
71
|
+
if baseline.contains(f):
|
|
72
|
+
suppressed += 1
|
|
73
|
+
else:
|
|
74
|
+
kept.add(f)
|
|
75
|
+
return kept, suppressed
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
"""Benchmark: precision and recall per detector on a labelled synthetic corpus.
|
|
2
|
+
|
|
3
|
+
The corpus is generated, never read from a file, so no real identifier can
|
|
4
|
+
end up in the repository. Positives are values that *are* the identifier
|
|
5
|
+
(checksums computed, handles from the known list) placed in the kinds of
|
|
6
|
+
context code has: a field assignment, a bare literal, a log line. Negatives
|
|
7
|
+
are the look-alikes each detector must refuse: wrong checksums, wrong holder
|
|
8
|
+
types, unknown handles, example domains, and the generic noise classes
|
|
9
|
+
(UUIDs, hashes, timestamps, order ids, random digit runs).
|
|
10
|
+
|
|
11
|
+
``python -m dpdp_scan.bench`` prints the table the README carries. Numbers
|
|
12
|
+
are reported as k/N with the misses named by class, so the README can say
|
|
13
|
+
"detects 198/200 Aadhaar positives; misses: bare value with ORD- prefix"
|
|
14
|
+
instead of "detects all Aadhaar numbers".
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import random
|
|
20
|
+
import uuid
|
|
21
|
+
from collections import defaultdict
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
|
|
24
|
+
from dpdp_scan.detectors import scan_text
|
|
25
|
+
from dpdp_scan.detectors.checksums import gstin_check_character, verhoeff_check_digit
|
|
26
|
+
from dpdp_scan.detectors.india import UPI_HANDLES
|
|
27
|
+
|
|
28
|
+
DEFAULT_SEED = 20261106
|
|
29
|
+
N_PER_CLASS = 200
|
|
30
|
+
|
|
31
|
+
# Contexts a positive can appear in. The first is the common case; the rest
|
|
32
|
+
# are harder. A positive counts as detected if the detector fires on the line
|
|
33
|
+
# at any confidence.
|
|
34
|
+
_POS_CONTEXTS = (
|
|
35
|
+
"{field} = '{v}'",
|
|
36
|
+
"'{v}'",
|
|
37
|
+
"logger.info('kyc for %s', {v_q})",
|
|
38
|
+
'{{"{field}": "{v}"}}',
|
|
39
|
+
"# {field}: {v}",
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(slots=True)
|
|
44
|
+
class Sample:
|
|
45
|
+
detector: str # the detector expected to fire ("" for a pure negative)
|
|
46
|
+
label: str # class name for the report
|
|
47
|
+
text: str
|
|
48
|
+
positive: bool
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(slots=True)
|
|
52
|
+
class DetectorScore:
|
|
53
|
+
detector: str
|
|
54
|
+
tp: int = 0
|
|
55
|
+
fn: int = 0
|
|
56
|
+
fp: int = 0
|
|
57
|
+
positives: int = 0
|
|
58
|
+
negatives: int = 0
|
|
59
|
+
missed: dict[str, int] = field(default_factory=lambda: defaultdict(int))
|
|
60
|
+
false_hits: dict[str, int] = field(default_factory=lambda: defaultdict(int))
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def precision(self) -> float:
|
|
64
|
+
return self.tp / (self.tp + self.fp) if (self.tp + self.fp) else 1.0
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def recall(self) -> float:
|
|
68
|
+
return self.tp / self.positives if self.positives else 1.0
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class Corpus:
|
|
72
|
+
def __init__(self, seed: int = DEFAULT_SEED, n: int = N_PER_CLASS) -> None:
|
|
73
|
+
self.rng = random.Random(seed) # noqa: S311 (benchmark data, not security)
|
|
74
|
+
self.n = n
|
|
75
|
+
|
|
76
|
+
# ---- value generators (all synthetic) ----------------------------------
|
|
77
|
+
|
|
78
|
+
def aadhaar(self) -> str:
|
|
79
|
+
head = str(self.rng.randint(2, 9)) + "".join(self.rng.choices("0123456789", k=10))
|
|
80
|
+
return head + verhoeff_check_digit(head)
|
|
81
|
+
|
|
82
|
+
def aadhaar_bad_checksum(self) -> str:
|
|
83
|
+
v = self.aadhaar()
|
|
84
|
+
return v[:-1] + str((int(v[-1]) + self.rng.randint(1, 9)) % 10)
|
|
85
|
+
|
|
86
|
+
def pan(self) -> str:
|
|
87
|
+
return (
|
|
88
|
+
"".join(self.rng.choices("ABCDEFGHJKLMNPQRSTUVWXYZ", k=3))
|
|
89
|
+
+ self.rng.choice("ABCFGHJLPT")
|
|
90
|
+
+ self.rng.choice("ABCDEFGHJKLMNPQRSTUVWXYZ")
|
|
91
|
+
+ "".join(self.rng.choices("0123456789", k=4))
|
|
92
|
+
+ self.rng.choice("ABCDEFGHJKLMNPQRSTUVWXYZ")
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
def pan_bad_holder(self) -> str:
|
|
96
|
+
v = self.pan()
|
|
97
|
+
return v[:3] + self.rng.choice("DEIKMNOQRSUVWXYZ") + v[4:]
|
|
98
|
+
|
|
99
|
+
def gstin(self) -> str:
|
|
100
|
+
first14 = f"{self.rng.randint(1, 37):02d}" + self.pan() + self.rng.choice("123456789") + "Z"
|
|
101
|
+
return first14 + gstin_check_character(first14)
|
|
102
|
+
|
|
103
|
+
def gstin_bad_check(self) -> str:
|
|
104
|
+
v = self.gstin()
|
|
105
|
+
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
106
|
+
return v[:-1] + alphabet[(alphabet.index(v[-1]) + self.rng.randint(1, 35)) % 36]
|
|
107
|
+
|
|
108
|
+
def ifsc(self) -> str:
|
|
109
|
+
return (
|
|
110
|
+
"".join(self.rng.choices("ABCDEFGHIJKLMNOPQRSTUVWXYZ", k=4))
|
|
111
|
+
+ "0"
|
|
112
|
+
+ "".join(self.rng.choices("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", k=6))
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
def ifsc_bad_fifth(self) -> str:
|
|
116
|
+
v = self.ifsc()
|
|
117
|
+
return v[:4] + self.rng.choice("123456789") + v[5:]
|
|
118
|
+
|
|
119
|
+
def upi(self) -> str:
|
|
120
|
+
local = "".join(self.rng.choices("abcdefghijklmnopqrstuvwxyz", k=self.rng.randint(4, 10)))
|
|
121
|
+
return f"{local}{self.rng.randint(1, 99)}@{self.rng.choice(sorted(UPI_HANDLES))}"
|
|
122
|
+
|
|
123
|
+
def upi_unknown_handle(self) -> str:
|
|
124
|
+
local = "".join(self.rng.choices("abcdefghijklmnopqrstuvwxyz", k=6))
|
|
125
|
+
return f"{local}@{self.rng.choice(['gmail', 'yahoo', 'corp', 'mailer', 'internal'])}"
|
|
126
|
+
|
|
127
|
+
def mobile(self) -> str:
|
|
128
|
+
digits = self.rng.choice("6789") + "".join(self.rng.choices("0123456789", k=9))
|
|
129
|
+
return self.rng.choice(
|
|
130
|
+
[digits, f"+91 {digits[:5]} {digits[5:]}", f"+91-{digits}", f"0{digits}"]
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
def mobile_bad_first(self) -> str:
|
|
134
|
+
return self.rng.choice("12345") + "".join(self.rng.choices("0123456789", k=9))
|
|
135
|
+
|
|
136
|
+
def email(self) -> str:
|
|
137
|
+
local = "".join(self.rng.choices("abcdefghijklmnopqrstuvwxyz", k=self.rng.randint(4, 9)))
|
|
138
|
+
domain = "".join(self.rng.choices("abcdefghijklmnopqrstuvwxyz", k=self.rng.randint(4, 8)))
|
|
139
|
+
return (
|
|
140
|
+
f"{local}.{self.rng.randint(1, 99)}@{domain}.{self.rng.choice(['in', 'com', 'co.in'])}"
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
def email_example(self) -> str:
|
|
144
|
+
domain = self.rng.choice(["example.com", "example.in", "test.com"])
|
|
145
|
+
return f"user{self.rng.randint(1, 99)}@{domain}"
|
|
146
|
+
|
|
147
|
+
def voter(self) -> str:
|
|
148
|
+
return "".join(self.rng.choices("ABCDEFGHIJKLMNOPQRSTUVWXYZ", k=3)) + "".join(
|
|
149
|
+
self.rng.choices("0123456789", k=7)
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
def passport(self) -> str:
|
|
153
|
+
return (
|
|
154
|
+
self.rng.choice("ABCDEFGHJKLMNPRSTUVWY")
|
|
155
|
+
+ self.rng.choice("123456789")
|
|
156
|
+
+ "".join(self.rng.choices("0123456789", k=6))
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
def driving_licence(self) -> str:
|
|
160
|
+
return (
|
|
161
|
+
"".join(self.rng.choices("ABCDEFGHIJKLMNOPQRSTUVWXYZ", k=2))
|
|
162
|
+
+ f"{self.rng.randint(1, 99):02d} "
|
|
163
|
+
+ str(self.rng.randint(1990, 2024))
|
|
164
|
+
+ "".join(self.rng.choices("0123456789", k=7))
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
# ---- noise ---------------------------------------------------------------
|
|
168
|
+
|
|
169
|
+
def noise(self) -> list[tuple[str, str]]:
|
|
170
|
+
r = self.rng
|
|
171
|
+
out: list[tuple[str, str]] = []
|
|
172
|
+
for _ in range(self.n):
|
|
173
|
+
out.append(("uuid", str(uuid.UUID(int=r.getrandbits(128)))))
|
|
174
|
+
out.append(("sha1", f"{r.getrandbits(160):040x}"))
|
|
175
|
+
out.append(("epoch_ms", str(r.randint(1_600_000_000_000, 1_800_000_000_000))))
|
|
176
|
+
out.append(
|
|
177
|
+
(
|
|
178
|
+
"iso_datetime",
|
|
179
|
+
f"2026-{r.randint(1, 12):02d}-{r.randint(1, 28):02d}"
|
|
180
|
+
f"T{r.randint(0, 23):02d}:{r.randint(0, 59):02d}:00Z",
|
|
181
|
+
)
|
|
182
|
+
)
|
|
183
|
+
out.append(("order_id_prefixed", f"ORD-{r.randint(10**11, 10**12 - 1)}"))
|
|
184
|
+
out.append(("random_12_digits", str(r.randint(2 * 10**11, 10**12 - 1))))
|
|
185
|
+
out.append(("random_10_digits", str(r.randint(10**9, 10**10 - 1))))
|
|
186
|
+
out.append(("card_16_grouped", " ".join(str(r.randint(1000, 9999)) for _ in range(4))))
|
|
187
|
+
out.append(
|
|
188
|
+
(
|
|
189
|
+
"version_and_port",
|
|
190
|
+
f"v{r.randint(1, 9)}.{r.randint(0, 30)} on port {r.randint(1024, 65535)}",
|
|
191
|
+
)
|
|
192
|
+
)
|
|
193
|
+
out.append(("sku", f"SKU{r.randint(10**7, 10**8 - 1)}X"))
|
|
194
|
+
return out
|
|
195
|
+
|
|
196
|
+
# ---- assembly ------------------------------------------------------------
|
|
197
|
+
|
|
198
|
+
def build(self) -> list[Sample]:
|
|
199
|
+
samples: list[Sample] = []
|
|
200
|
+
positives = {
|
|
201
|
+
"in_aadhaar": ("aadhaar_no", self.aadhaar),
|
|
202
|
+
"in_pan": ("pan_number", self.pan),
|
|
203
|
+
"in_gstin": ("gstin", self.gstin),
|
|
204
|
+
"in_ifsc": ("ifsc_code", self.ifsc),
|
|
205
|
+
"in_upi": ("upi_id", self.upi),
|
|
206
|
+
"in_mobile": ("mobile", self.mobile),
|
|
207
|
+
"email": ("email", self.email),
|
|
208
|
+
"in_voter_epic": ("voter_id", self.voter),
|
|
209
|
+
"in_passport": ("passport_no", self.passport),
|
|
210
|
+
"in_driving_licence": ("dl_no", self.driving_licence),
|
|
211
|
+
}
|
|
212
|
+
for det, (fld, gen) in positives.items():
|
|
213
|
+
for i in range(self.n):
|
|
214
|
+
ctx = _POS_CONTEXTS[i % len(_POS_CONTEXTS)]
|
|
215
|
+
v = gen()
|
|
216
|
+
text = ctx.format(field=fld, v=v, v_q=repr(v))
|
|
217
|
+
samples.append(
|
|
218
|
+
Sample(det, f"{det}:{ctx.split('{')[0].strip() or 'bare'}", text, True)
|
|
219
|
+
)
|
|
220
|
+
negatives = {
|
|
221
|
+
"in_aadhaar": ("aadhaar_bad_checksum", self.aadhaar_bad_checksum),
|
|
222
|
+
"in_pan": ("pan_bad_holder_type", self.pan_bad_holder),
|
|
223
|
+
"in_gstin": ("gstin_bad_check_char", self.gstin_bad_check),
|
|
224
|
+
"in_ifsc": ("ifsc_nonzero_fifth", self.ifsc_bad_fifth),
|
|
225
|
+
"in_upi": ("upi_unknown_handle", self.upi_unknown_handle),
|
|
226
|
+
"in_mobile": ("mobile_first_digit_1_5", self.mobile_bad_first),
|
|
227
|
+
"email": ("email_example_domain", self.email_example),
|
|
228
|
+
}
|
|
229
|
+
for det, (label, gen) in negatives.items():
|
|
230
|
+
for _ in range(self.n):
|
|
231
|
+
samples.append(Sample(det, label, f"value = '{gen()}'", False))
|
|
232
|
+
for label, v in self.noise():
|
|
233
|
+
samples.append(Sample("", label, v, False))
|
|
234
|
+
return samples
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def run(seed: int = DEFAULT_SEED, n: int = N_PER_CLASS) -> dict[str, DetectorScore]:
|
|
238
|
+
samples = Corpus(seed, n).build()
|
|
239
|
+
scores: dict[str, DetectorScore] = {}
|
|
240
|
+
|
|
241
|
+
def score(det: str) -> DetectorScore:
|
|
242
|
+
return scores.setdefault(det, DetectorScore(det))
|
|
243
|
+
|
|
244
|
+
for s in samples:
|
|
245
|
+
fired = {f.detector_id for f in scan_text(s.text, "bench.txt")}
|
|
246
|
+
if s.positive:
|
|
247
|
+
sc = score(s.detector)
|
|
248
|
+
sc.positives += 1
|
|
249
|
+
if s.detector in fired:
|
|
250
|
+
sc.tp += 1
|
|
251
|
+
else:
|
|
252
|
+
sc.fn += 1
|
|
253
|
+
sc.missed[s.label] += 1
|
|
254
|
+
else:
|
|
255
|
+
if s.detector:
|
|
256
|
+
score(s.detector).negatives += 1
|
|
257
|
+
for det in fired:
|
|
258
|
+
sc = score(det)
|
|
259
|
+
sc.fp += 1
|
|
260
|
+
sc.false_hits[s.label] += 1
|
|
261
|
+
return dict(sorted(scores.items()))
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def markdown(scores: dict[str, DetectorScore], *, date: str = "", commit: str = "") -> str:
|
|
265
|
+
lines = []
|
|
266
|
+
header = "Precision and recall on the synthetic benchmark"
|
|
267
|
+
if date or commit:
|
|
268
|
+
header += f" ({date}{', ' if date and commit else ''}{commit})"
|
|
269
|
+
lines += [
|
|
270
|
+
f"**{header}.** `python -m dpdp_scan.bench`, seed {DEFAULT_SEED}, {N_PER_CLASS} per class.",
|
|
271
|
+
"",
|
|
272
|
+
]
|
|
273
|
+
lines += [
|
|
274
|
+
"| Detector | Recall (found / positives) | Precision (true / fired) "
|
|
275
|
+
"| Misses | False hits |",
|
|
276
|
+
"|---|---:|---:|---|---|",
|
|
277
|
+
]
|
|
278
|
+
for det, sc in scores.items():
|
|
279
|
+
missed = (
|
|
280
|
+
", ".join(f"{k.split(':', 1)[-1]} {v}" for k, v in sorted(sc.missed.items())) or "none"
|
|
281
|
+
)
|
|
282
|
+
false_hits = ", ".join(f"{k} {v}" for k, v in sorted(sc.false_hits.items())) or "none"
|
|
283
|
+
lines.append(
|
|
284
|
+
f"| `{det}` | {sc.tp}/{sc.positives} ({sc.recall:.0%}) | "
|
|
285
|
+
f"{sc.tp}/{sc.tp + sc.fp} ({sc.precision:.0%}) | {missed} | {false_hits} |"
|
|
286
|
+
)
|
|
287
|
+
lines += [
|
|
288
|
+
"",
|
|
289
|
+
"Recall counts a positive as found at any confidence. Precision counts every firing on a "
|
|
290
|
+
"negative as a false hit, including the ones the detector itself marks LOW. The random "
|
|
291
|
+
"12-digit class is the irreducible Verhoeff floor: about one in ten passes the checksum.",
|
|
292
|
+
]
|
|
293
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""``python -m dpdp_scan.bench [--seed N] [--n N] [--date D] [--commit C] [--json]``"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from dpdp_scan.bench import DEFAULT_SEED, N_PER_CLASS, markdown, run
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main(argv: list[str] | None = None) -> int:
|
|
13
|
+
parser = argparse.ArgumentParser(prog="python -m dpdp_scan.bench")
|
|
14
|
+
parser.add_argument("--seed", type=int, default=DEFAULT_SEED)
|
|
15
|
+
parser.add_argument("--n", type=int, default=N_PER_CLASS, help="samples per class")
|
|
16
|
+
parser.add_argument("--date", default="")
|
|
17
|
+
parser.add_argument("--commit", default="")
|
|
18
|
+
parser.add_argument("--json", action="store_true", help="machine-readable scores")
|
|
19
|
+
args = parser.parse_args(argv)
|
|
20
|
+
scores = run(args.seed, args.n)
|
|
21
|
+
if args.json:
|
|
22
|
+
out = {
|
|
23
|
+
det: {
|
|
24
|
+
"tp": sc.tp,
|
|
25
|
+
"fn": sc.fn,
|
|
26
|
+
"fp": sc.fp,
|
|
27
|
+
"positives": sc.positives,
|
|
28
|
+
"negatives": sc.negatives,
|
|
29
|
+
"precision": round(sc.precision, 4),
|
|
30
|
+
"recall": round(sc.recall, 4),
|
|
31
|
+
"missed": dict(sc.missed),
|
|
32
|
+
"false_hits": dict(sc.false_hits),
|
|
33
|
+
}
|
|
34
|
+
for det, sc in scores.items()
|
|
35
|
+
}
|
|
36
|
+
print(json.dumps(out, indent=2))
|
|
37
|
+
else:
|
|
38
|
+
print(markdown(scores, date=args.date, commit=args.commit))
|
|
39
|
+
return 0
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
if __name__ == "__main__":
|
|
43
|
+
sys.exit(main())
|
dpdp_scan/catalogue.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""The catalogue: every finding id, its reader-facing text and its provisions.
|
|
2
|
+
|
|
3
|
+
The engine emits ids and evidence; every sentence a reader sees comes from
|
|
4
|
+
here or from the rule pack's own metadata. Keeping the wording in one place
|
|
5
|
+
is what lets it be reviewed once (and legal-checked once) rather than
|
|
6
|
+
scattered across detectors.
|
|
7
|
+
|
|
8
|
+
Three families of id:
|
|
9
|
+
|
|
10
|
+
- ``in_*`` and ``email``: value detectors (``dpdp_scan.detectors``)
|
|
11
|
+
- ``schema_sql``, ``schema_prisma``, ``schema_openapi``: declared fields
|
|
12
|
+
- ``rule:<id>``: Semgrep rules, whose text is read from ``rules/dpdpa.yml``
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from functools import lru_cache
|
|
19
|
+
|
|
20
|
+
import yaml
|
|
21
|
+
|
|
22
|
+
from dpdp_scan.detectors.india import DETECTORS
|
|
23
|
+
from dpdp_scan.model import Category, Provision
|
|
24
|
+
from dpdp_scan.semgrep_runner import RULES_DIR
|
|
25
|
+
|
|
26
|
+
CATALOGUE_VERSION = "2026-11-06"
|
|
27
|
+
|
|
28
|
+
SAFEGUARDS = (
|
|
29
|
+
Provision("S.8(5)", "reasonable security safeguards to prevent a personal data breach"),
|
|
30
|
+
Provision("Rule 6(1)(a)", "security measures such as encryption, obfuscation or masking"),
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True, slots=True)
|
|
35
|
+
class RuleInfo:
|
|
36
|
+
id: str
|
|
37
|
+
name: str # short, title-case: "Aadhaar number in source"
|
|
38
|
+
description: str # one or two sentences on what was found and why it matters
|
|
39
|
+
remediation: str # one sentence on what to do
|
|
40
|
+
category: Category
|
|
41
|
+
provisions: tuple[Provision, ...]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
_VALUE_REMEDIATION = (
|
|
45
|
+
"Remove the value from the repository; use synthetic test data, and keep real "
|
|
46
|
+
"identifiers in a secret store or an encrypted datastore."
|
|
47
|
+
)
|
|
48
|
+
_VALUE_DESCRIPTION = {
|
|
49
|
+
"in_aadhaar": "A 12-digit value with a valid Verhoeff checksum, so almost certainly an "
|
|
50
|
+
"Aadhaar number, appears in the repository.",
|
|
51
|
+
"in_pan": "A value shaped like a Permanent Account Number appears in the repository.",
|
|
52
|
+
"in_gstin": "A GSTIN with a valid check character appears in the repository. A sole "
|
|
53
|
+
"proprietor's GSTIN embeds their PAN and identifies them.",
|
|
54
|
+
"in_ifsc": "An IFSC bank branch code appears in the repository, usually alongside an "
|
|
55
|
+
"account number.",
|
|
56
|
+
"in_upi": "A UPI payment address on a known payment-service handle appears in the repository.",
|
|
57
|
+
"in_mobile": "A value shaped like an Indian mobile number appears in the repository.",
|
|
58
|
+
"in_voter_epic": "A value shaped like a voter EPIC number appears in the repository.",
|
|
59
|
+
"in_passport": "A value shaped like an Indian passport number appears in the repository.",
|
|
60
|
+
"in_driving_licence": "A value shaped like a driving licence number appears in the repository.",
|
|
61
|
+
"email": "An email address appears in the repository.",
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
_SCHEMA_DESCRIPTION = (
|
|
65
|
+
"A field declared in a {what} is named like it holds personal data. Declared fields "
|
|
66
|
+
"are the start of a data inventory: know what is collected before deciding whether "
|
|
67
|
+
"it is needed, how long it is kept and how it is protected."
|
|
68
|
+
)
|
|
69
|
+
_SCHEMA_REMEDIATION = (
|
|
70
|
+
"Confirm the field is needed for a stated purpose (S.4, S.5), record it in the data "
|
|
71
|
+
"map, and apply field-level protection and a retention rule (S.8(7))."
|
|
72
|
+
)
|
|
73
|
+
_SCHEMA_WHAT = {
|
|
74
|
+
"schema_sql": "SQL table definition",
|
|
75
|
+
"schema_prisma": "Prisma model",
|
|
76
|
+
"schema_openapi": "OpenAPI or JSON Schema document",
|
|
77
|
+
}
|
|
78
|
+
_SCHEMA_PROVISIONS = (
|
|
79
|
+
Provision("S.4", "processing only for a lawful purpose"),
|
|
80
|
+
Provision("S.5", "the notice must say what data is collected and why"),
|
|
81
|
+
Provision("S.8(7)", "erase personal data once the purpose is served"),
|
|
82
|
+
*SAFEGUARDS,
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _value_rules() -> dict[str, RuleInfo]:
|
|
87
|
+
out: dict[str, RuleInfo] = {}
|
|
88
|
+
for det in DETECTORS:
|
|
89
|
+
out[det.id] = RuleInfo(
|
|
90
|
+
id=det.id,
|
|
91
|
+
name=f"{det.label} in source",
|
|
92
|
+
description=_VALUE_DESCRIPTION.get(det.id, f"A {det.label} appears in the repository."),
|
|
93
|
+
remediation=_VALUE_REMEDIATION,
|
|
94
|
+
category=det.category,
|
|
95
|
+
provisions=det.provisions,
|
|
96
|
+
)
|
|
97
|
+
return out
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _schema_rules() -> dict[str, RuleInfo]:
|
|
101
|
+
return {
|
|
102
|
+
rid: RuleInfo(
|
|
103
|
+
id=rid,
|
|
104
|
+
name=f"Personal data field declared in a {what}",
|
|
105
|
+
description=_SCHEMA_DESCRIPTION.format(what=what),
|
|
106
|
+
remediation=_SCHEMA_REMEDIATION,
|
|
107
|
+
category=Category.OTHER, # the finding's own category is per field
|
|
108
|
+
provisions=_SCHEMA_PROVISIONS,
|
|
109
|
+
)
|
|
110
|
+
for rid, what in _SCHEMA_WHAT.items()
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _semgrep_rules() -> dict[str, RuleInfo]:
|
|
115
|
+
out: dict[str, RuleInfo] = {}
|
|
116
|
+
for yml in sorted(RULES_DIR.glob("*.yml")):
|
|
117
|
+
data = yaml.safe_load(yml.read_text(encoding="utf-8")) or {}
|
|
118
|
+
for rule in data.get("rules", []):
|
|
119
|
+
rid = f"rule:{rule['id']}"
|
|
120
|
+
meta = rule.get("metadata", {})
|
|
121
|
+
message = " ".join(str(rule.get("message", "")).split())
|
|
122
|
+
# The last sentence of each rule message is its remediation.
|
|
123
|
+
parts = [p.strip() for p in message.split(". ") if p.strip()]
|
|
124
|
+
remediation = parts[-1] if len(parts) > 1 else ""
|
|
125
|
+
description = ". ".join(parts[:-1]) + "." if len(parts) > 1 else message
|
|
126
|
+
out[rid] = RuleInfo(
|
|
127
|
+
id=rid,
|
|
128
|
+
name=str(meta.get("label", rule["id"])).capitalize(),
|
|
129
|
+
description=description,
|
|
130
|
+
remediation=remediation.rstrip(".") + "." if remediation else "",
|
|
131
|
+
category=Category(meta.get("category", "other")),
|
|
132
|
+
provisions=tuple(Provision(str(ref)) for ref in meta.get("dpdpa", [])),
|
|
133
|
+
)
|
|
134
|
+
return out
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@lru_cache(maxsize=1)
|
|
138
|
+
def catalogue() -> dict[str, RuleInfo]:
|
|
139
|
+
return {**_value_rules(), **_schema_rules(), **_semgrep_rules()}
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def rule_info(detector_id: str) -> RuleInfo:
|
|
143
|
+
cat = catalogue()
|
|
144
|
+
if detector_id in cat:
|
|
145
|
+
return cat[detector_id]
|
|
146
|
+
return RuleInfo(
|
|
147
|
+
id=detector_id,
|
|
148
|
+
name=detector_id,
|
|
149
|
+
description="Finding from an unknown detector.",
|
|
150
|
+
remediation="",
|
|
151
|
+
category=Category.OTHER,
|
|
152
|
+
provisions=(),
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
CATEGORY_LABELS: dict[Category, str] = {
|
|
157
|
+
Category.IDENTITY: "Identity documents and names",
|
|
158
|
+
Category.CONTACT: "Contact details",
|
|
159
|
+
Category.FINANCIAL: "Financial identifiers",
|
|
160
|
+
Category.HEALTH: "Health data",
|
|
161
|
+
Category.BIOMETRIC: "Biometric data",
|
|
162
|
+
Category.LOCATION: "Location data",
|
|
163
|
+
Category.AGE_DOB: "Age and date of birth (children: S.9)",
|
|
164
|
+
Category.OTHER: "Other personal data and online identifiers",
|
|
165
|
+
}
|