piitrace 1.0.0__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.
piiscanner/__init__.py ADDED
@@ -0,0 +1,69 @@
1
+ """Find the personal data in a database, without writing to it or keeping any of it.
2
+
3
+ import piiscanner
4
+
5
+ result = piiscanner.scan("mysql://readonly:PASSWORD@host:3306/shop")
6
+ for f in result.findings:
7
+ print(f.collection, f.field, f.pii_type.value, f.confidence, f.evidence)
8
+
9
+ Works on MySQL, PostgreSQL and MongoDB. Every session is read-only, every
10
+ statement is checked to be a read before it is sent, and evidence is masked
11
+ when a finding is created (``9876543210`` becomes ``98XXXXXX10``): no raw
12
+ value is ever returned, stored or logged.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from collections.abc import Iterable
18
+
19
+ from piiscanner.models import Finding, PIIType, ScanResult
20
+
21
+ try:
22
+ from importlib.metadata import PackageNotFoundError, version
23
+
24
+ __version__ = version("piiscanner")
25
+ except PackageNotFoundError: # running from a source tree that was never installed
26
+ __version__ = "0+unknown"
27
+
28
+ __all__ = ["scan", "ScanResult", "Finding", "PIIType", "__version__"]
29
+
30
+
31
+ def scan(
32
+ source: str,
33
+ *,
34
+ sample_size: int = 500,
35
+ include: Iterable[str] | None = None,
36
+ exclude: Iterable[str] | None = None,
37
+ datasets: Iterable[str] | None = None,
38
+ ) -> ScanResult:
39
+ """Scan a database and return the personal data found in it.
40
+
41
+ ``source`` is a connection string: ``mysql://``, ``postgresql://`` or
42
+ ``mongodb://``. Use an account that can only read.
43
+
44
+ ``sample_size`` is how many values are read per column. ``include`` and
45
+ ``exclude`` are table-name patterns (``"prod_*"``). ``datasets`` names
46
+ the databases or schemas to scan; left out, it is the one named in
47
+ ``source``, or every one the account can see if ``source`` names none.
48
+
49
+ The result's ``findings`` are what was found; ``tables_not_read`` lists
50
+ tables that could not be read -- not covered, rather than clean.
51
+ """
52
+ from piiscanner.classify.engine import run_scan
53
+ from piiscanner.config import ScanConfig, build_connector
54
+
55
+ config = ScanConfig(
56
+ source=source,
57
+ sample_size=sample_size,
58
+ include=list(include or []),
59
+ exclude=list(exclude or []),
60
+ datasets=list(datasets or []),
61
+ )
62
+ connector = build_connector(config)
63
+ with connector:
64
+ # As on the command line: a connection string that names a database
65
+ # means that database, not every schema the account can see.
66
+ named = getattr(connector, "default_dataset", None)
67
+ if not config.datasets and named:
68
+ config.datasets = [named]
69
+ return run_scan(connector, config)
@@ -0,0 +1,55 @@
1
+ """Real-schema audit harness.
2
+
3
+ The synthetic benchmark scores 1.000 on both sources, which means it has stopped
4
+ discriminating: the detectors and the answer key were written together, so it
5
+ measures fit to fixtures rather than fitness for real data. Nothing in the
6
+ repository measures recall on a real schema.
7
+
8
+ This package closes that gap the only way it can be closed -- a human labels a
9
+ sample of real fields, blind to what the scanner decided, and the labels are
10
+ scored against the verdicts afterwards.
11
+
12
+ Three properties the design turns on:
13
+
14
+ *stratified, not random*
15
+ Uniform sampling over ~600 fields where 6 are flagged would return roughly
16
+ zero flagged fields, and precision would be unmeasurable. The flagged
17
+ stratum is taken as a census; the others are sampled.
18
+
19
+ *blind by construction*
20
+ The worksheet carries no confidence, no PII type, no verdict, and no
21
+ stratum, and the rows are shuffled. A labeller who can infer what the
22
+ scanner decided produces labels that agree with it, and the exercise
23
+ measures nothing.
24
+
25
+ *recall is an estimate and says so*
26
+ Precision comes from a census and is exact. Recall is extrapolated from a
27
+ 60-field sample and is reported with a confidence interval, every time.
28
+ """
29
+
30
+ from piiscanner.audit.sampling import (
31
+ STRATA,
32
+ AuditSample,
33
+ SampledField,
34
+ Stratum,
35
+ draw_sample,
36
+ )
37
+ from piiscanner.audit.scoring import AuditScore, RecallEstimate, score_audit
38
+ from piiscanner.audit.storage import load_audit, save_audit
39
+ from piiscanner.audit.worksheet import Label, read_labels, write_worksheet
40
+
41
+ __all__ = [
42
+ "STRATA",
43
+ "AuditSample",
44
+ "AuditScore",
45
+ "Label",
46
+ "RecallEstimate",
47
+ "SampledField",
48
+ "Stratum",
49
+ "draw_sample",
50
+ "load_audit",
51
+ "read_labels",
52
+ "save_audit",
53
+ "score_audit",
54
+ "write_worksheet",
55
+ ]
@@ -0,0 +1,151 @@
1
+ """``misses.md`` -- the work queue an audit produces.
2
+
3
+ A scorecard tells you how good the classifier is. This tells you what to do
4
+ next, which is the more useful artefact. Disagreements are grouped by *apparent
5
+ cause* rather than listed flat, because the grouping is the finding: twelve
6
+ misses sharing one cause is one fix, while twelve misses with twelve causes is a
7
+ detector-coverage problem.
8
+
9
+ Skip misses are kept in their own section throughout. A field that holds PII but
10
+ was excluded before classification is a bug in the skip rules, not a classifier
11
+ miss, and mixing the two would point the work at the wrong module.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections import defaultdict
17
+ from pathlib import Path
18
+
19
+ from piiscanner.audit.scoring import AuditScore, Disagreement
20
+ from piiscanner.audit.storage import MISSES_FILE
21
+
22
+ KIND_TITLES = {
23
+ "false_negative": "False negatives -- PII the scanner did not report",
24
+ "false_positive": "False positives -- reported but not personal data",
25
+ "wrong_type": "Wrong type -- field found, label incorrect",
26
+ "skip_miss": "Skip-rule misses -- PII excluded before classification",
27
+ }
28
+
29
+ KIND_NOTES = {
30
+ "false_negative": (
31
+ "Each of these is a recall failure. Grouped by apparent cause: a cause "
32
+ "mentioning a *name signal* means Layer 1 fired and something downstream "
33
+ "discarded it, which is a merge-logic fix. A cause mentioning *no name "
34
+ "signal* means nothing detected it at all, which needs a detector."
35
+ ),
36
+ "false_positive": (
37
+ "Each of these costs credibility directly -- a reviewer who chases one "
38
+ "down for nothing trusts the next finding less."
39
+ ),
40
+ "wrong_type": (
41
+ "The column was correctly identified as personal data but mislabelled. "
42
+ "Lower severity than a miss: the field still lands in the inventory."
43
+ ),
44
+ "skip_miss": (
45
+ "These are bugs in the skip rules, not the classifier. The field was "
46
+ "never sampled, so no detector had a chance."
47
+ ),
48
+ }
49
+
50
+
51
+ def _row_block(item: Disagreement) -> list[str]:
52
+ row = item.row
53
+ lines = [f"#### `{row.path}`", ""]
54
+
55
+ facts = [
56
+ f"- type `{row.native_type}`",
57
+ f"- sampled {row.sample_count}"
58
+ + (f" of ~{row.approx_row_count:,} rows" if row.approx_row_count else ""),
59
+ f"- blank {row.blank_rate:.0%}, distinct {row.distinct_ratio:.0%}",
60
+ ]
61
+ if row.evidence:
62
+ facts.append("- examples (masked): " + ", ".join(f"`{e}`" for e in row.evidence))
63
+ else:
64
+ facts.append("- no examples: field was not sampled")
65
+
66
+ if row.scanner_flagged:
67
+ verdict = row.scanner_pii_type.value if row.scanner_pii_type else "?"
68
+ facts.append(
69
+ f"- scanner said **{verdict}** at {row.scanner_confidence:.2f}"
70
+ + (" (unverified, name only)" if row.scanner_unverified else "")
71
+ )
72
+ elif row.skip_reason:
73
+ facts.append(f"- skipped because: {row.skip_reason}")
74
+ else:
75
+ facts.append("- scanner reported nothing")
76
+
77
+ if item.label.pii_type:
78
+ facts.append(f"- labelled as **{item.label.pii_type}**")
79
+ if item.label.notes:
80
+ facts.append(f"- auditor note: {item.label.notes}")
81
+
82
+ lines += facts + [""]
83
+ return lines
84
+
85
+
86
+ def render_misses(score: AuditScore) -> str:
87
+ """Build the markdown work queue."""
88
+ sample = score.sample
89
+ lines = [
90
+ f"# Audit work queue -- {sample.name}",
91
+ "",
92
+ f"Source `{sample.source_alias}` · scan `{sample.scan_run_id}` · "
93
+ f"classifier {sample.classifier_version} · ruleset {sample.ruleset_version}",
94
+ f"Sample seed `{sample.seed}`.",
95
+ "",
96
+ "Precision is exact (the flagged stratum is a census). Recall is an "
97
+ "extrapolation from a sample and carries the interval shown in the "
98
+ "scorecard -- do not quote it without one.",
99
+ "",
100
+ "## Summary",
101
+ "",
102
+ "| Class | Count |",
103
+ "|---|---|",
104
+ f"| False negatives (observed) | {len(score.false_negatives)} |",
105
+ f"| False positives | {len(score.false_positives)} |",
106
+ f"| Wrong type | {len(score.type_wrong)} |",
107
+ f"| Skip-rule misses | {len(score.skip_misses)} |",
108
+ f"| Unsure (excluded from all scores) | {len(score.unsure)} |",
109
+ f"| Unlabelled (excluded) | {len(score.unlabelled)} |",
110
+ "",
111
+ ]
112
+
113
+ if not score.disagreements:
114
+ lines += [
115
+ "No disagreements. Every label matched the scanner's verdict.",
116
+ "",
117
+ "Read that carefully: with a small unflagged sample, agreement is "
118
+ "consistent with good recall *and* with a sample that happened to "
119
+ "miss the failures. The scorecard's interval is the honest summary.",
120
+ "",
121
+ ]
122
+ return "\n".join(lines)
123
+
124
+ by_kind: dict[str, list[Disagreement]] = defaultdict(list)
125
+ for item in score.disagreements:
126
+ by_kind[item.kind].append(item)
127
+
128
+ for kind in ("false_negative", "false_positive", "wrong_type", "skip_miss"):
129
+ items = by_kind.get(kind)
130
+ if not items:
131
+ continue
132
+ lines += [f"## {KIND_TITLES[kind]}", "", KIND_NOTES[kind], ""]
133
+
134
+ by_cause: dict[str, list[Disagreement]] = defaultdict(list)
135
+ for item in items:
136
+ by_cause[item.cause].append(item)
137
+
138
+ # Biggest groups first: the largest shared cause is the best next fix.
139
+ for cause, group in sorted(by_cause.items(), key=lambda kv: -len(kv[1])):
140
+ lines += [f"### {cause} ({len(group)} field(s))", ""]
141
+ for item in sorted(group, key=lambda i: i.row.path):
142
+ lines += _row_block(item)
143
+
144
+ return "\n".join(lines)
145
+
146
+
147
+ def write_misses(score: AuditScore, directory: str | Path) -> Path:
148
+ target = Path(directory) / MISSES_FILE
149
+ target.parent.mkdir(parents=True, exist_ok=True)
150
+ target.write_text(render_misses(score), encoding="utf-8")
151
+ return target
@@ -0,0 +1,193 @@
1
+ """Terminal scorecard for a scored audit.
2
+
3
+ Written as plain text rather than a rich table so it can be pasted into a ticket
4
+ or a CI log unchanged. The layout deliberately puts precision and recall in
5
+ different blocks with different wording: one is measured, the other is
6
+ estimated, and a two-column table implies they are the same kind of number.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from pathlib import Path
13
+
14
+ from piiscanner.audit.scoring import AuditScore
15
+ from piiscanner.audit.sampling import Stratum
16
+ from piiscanner.audit.storage import SCORES_FILE
17
+
18
+ BAR = "=" * 72
19
+
20
+
21
+ def format_score(score: AuditScore) -> str:
22
+ sample = score.sample
23
+ tp, fp = len(score.true_positives), len(score.false_positives)
24
+ fn, tn = len(score.false_negatives), len(score.true_negatives)
25
+
26
+ lines = [
27
+ BAR,
28
+ f"AUDIT {sample.name}",
29
+ f" source {sample.source_alias} · classifier "
30
+ f"{sample.classifier_version} · ruleset {sample.ruleset_version}",
31
+ f" seed {sample.seed} · scan {sample.scan_run_id}",
32
+ BAR,
33
+ "",
34
+ "STRATA",
35
+ "-" * 72,
36
+ ]
37
+ for stratum in Stratum:
38
+ population = sample.population.get(stratum, 0)
39
+ drawn = sample.drawn.get(stratum, 0)
40
+ kind = "census" if drawn >= population and population else "sample"
41
+ lines.append(
42
+ f" {stratum.value:<10} {drawn:>4} labelled of {population:>4} "
43
+ f"in population ({kind})"
44
+ )
45
+
46
+ lines += [
47
+ "",
48
+ "PRECISION (exact -- the flagged stratum is a census, not a sample)",
49
+ "-" * 72,
50
+ f" precision {score.precision:.3f} ({tp} TP / {fp} FP)",
51
+ "",
52
+ "RECALL (estimated -- extrapolated from the unflagged sample)",
53
+ "-" * 72,
54
+ f" recall ~ {score.recall.describe()}",
55
+ "",
56
+ f" observed: {fn} miss(es) in {fn + tn} labelled unflagged field(s)",
57
+ "",
58
+ "TYPE ACCURACY (among true positives)",
59
+ "-" * 72,
60
+ f" accuracy {score.type_accuracy:.3f} "
61
+ f"({score.type_correct} correct / {len(score.type_wrong)} wrong)",
62
+ ]
63
+ if score.type_unspecified:
64
+ lines.append(
65
+ f" {score.type_unspecified} true positive(s) had no readable type "
66
+ "label and are excluded"
67
+ )
68
+
69
+ lines += [
70
+ "",
71
+ "SKIP AUDIT (a bug in the skip rules, not a classifier miss)",
72
+ "-" * 72,
73
+ ]
74
+ if not score.skipped_labelled:
75
+ lines.append(" no skipped fields were labelled")
76
+ else:
77
+ lines.append(
78
+ f" {len(score.skip_misses)} of {score.skipped_labelled} labelled "
79
+ f"skipped field(s) actually hold PII"
80
+ )
81
+ if score.skip_misses:
82
+ lines.append(
83
+ f" extrapolates to ~{score.estimated_skip_misses:.0f} across "
84
+ f"{sample.population.get(Stratum.SKIPPED, 0)} skipped field(s)"
85
+ )
86
+ lines.append(
87
+ " these are NOT in the recall figure above -- they never "
88
+ "reached the classifier"
89
+ )
90
+
91
+ lines += [
92
+ "",
93
+ "EXCLUSIONS",
94
+ "-" * 72,
95
+ f" unsure {len(score.unsure)} row(s) -- excluded from every "
96
+ "denominator",
97
+ f" unlabelled {len(score.unlabelled)} row(s) -- left blank, also "
98
+ "excluded",
99
+ ]
100
+ if score.unmatched_row_ids:
101
+ lines.append(
102
+ f" unmatched {len(score.unmatched_row_ids)} label(s) had a "
103
+ "row_id not in the sample"
104
+ )
105
+
106
+ lines += [
107
+ "",
108
+ f"F1 (on point estimates, inherits recall's uncertainty) {score.f1:.3f}",
109
+ "",
110
+ ]
111
+ return "\n".join(lines)
112
+
113
+
114
+ def _serialisable(score: AuditScore) -> dict:
115
+ recall = score.recall
116
+ lo, hi = recall.interval
117
+ rate_lo, rate_hi = recall.fn_rate_interval
118
+ return {
119
+ "audit": score.sample.name,
120
+ "source_alias": score.sample.source_alias,
121
+ "scan_run_id": score.sample.scan_run_id,
122
+ "classifier_version": score.sample.classifier_version,
123
+ "ruleset_version": score.sample.ruleset_version,
124
+ "seed": score.sample.seed,
125
+ "population": {s.value: n for s, n in score.sample.population.items()},
126
+ "drawn": {s.value: n for s, n in score.sample.drawn.items()},
127
+ "precision": {
128
+ "value": round(score.precision, 4),
129
+ "exact": True,
130
+ "true_positives": len(score.true_positives),
131
+ "false_positives": len(score.false_positives),
132
+ },
133
+ "recall": {
134
+ "estimate": round(recall.point, 4),
135
+ "exact": False,
136
+ "ci95": [round(lo, 4), round(hi, 4)],
137
+ "weak": recall.weak,
138
+ "observed_false_negatives": recall.observed_fn,
139
+ "labelled_unflagged": recall.sample_size,
140
+ "unflagged_population": recall.population,
141
+ "fn_rate": round(recall.fn_rate, 4),
142
+ "fn_rate_ci95": [round(rate_lo, 4), round(rate_hi, 4)],
143
+ "estimated_missed_fields": round(recall.estimated_fn, 1),
144
+ "method": (
145
+ "exact one-sided Clopper-Pearson bound (observed count too low "
146
+ "for the normal approximation)"
147
+ if recall.weak
148
+ else "normal approximation with finite-population correction"
149
+ ),
150
+ },
151
+ "type_accuracy": {
152
+ "value": round(score.type_accuracy, 4),
153
+ "correct": score.type_correct,
154
+ "wrong": len(score.type_wrong),
155
+ "unspecified": score.type_unspecified,
156
+ },
157
+ "skip_audit": {
158
+ "labelled": score.skipped_labelled,
159
+ "misses": len(score.skip_misses),
160
+ "estimated_misses": round(score.estimated_skip_misses, 1),
161
+ "fields": [r.path for r in score.skip_misses],
162
+ },
163
+ "exclusions": {
164
+ "unsure": len(score.unsure),
165
+ "unlabelled": len(score.unlabelled),
166
+ "unmatched_row_ids": score.unmatched_row_ids,
167
+ },
168
+ "f1_point": round(score.f1, 4),
169
+ "false_negatives": [
170
+ {"field": d.row.path, "cause": d.cause}
171
+ for d in score.disagreements
172
+ if d.kind == "false_negative"
173
+ ],
174
+ "false_positives": [
175
+ {
176
+ "field": d.row.path,
177
+ "reported": d.row.scanner_pii_type.value if d.row.scanner_pii_type else None,
178
+ "confidence": d.row.scanner_confidence,
179
+ "cause": d.cause,
180
+ }
181
+ for d in score.disagreements
182
+ if d.kind == "false_positive"
183
+ ],
184
+ }
185
+
186
+
187
+ def write_scores(score: AuditScore, directory: str | Path) -> Path:
188
+ target = Path(directory) / SCORES_FILE
189
+ target.parent.mkdir(parents=True, exist_ok=True)
190
+ target.write_text(
191
+ json.dumps(_serialisable(score), indent=2) + "\n", encoding="utf-8"
192
+ )
193
+ return target