From 012884087d5d88c88c245abac894672cdf5ee24a Mon Sep 17 00:00:00 2001 From: abrichr Date: Wed, 14 Oct 2026 03:20:05 -0400 Subject: [PATCH 1/6] fix: keep field labels readable and find addresses after any address label The spaCy model read common field labels as entities, so "SSN: 923-45-6789" came back as ": " and "Email: john@example.com" as ": ". The README showed this as a surprise to work around. A PERSON or ORGANIZATION span is now dropped when its whole text is a known label (SSN, Email, DOB, MRN, and similar) and another finding starts right after it. The identifier is still redacted; a label with nothing after it, and a name in front of an identifier, are still redacted. The street-address recognizer only fired after "Home address:" or "Mail to", so "Address: 42 Elm Road" passed through. It now fires after any label that ends in "address:". The synthetic recall set grows from 26 to 27 cases. Co-Authored-By: Claude Opus 5.5 --- openadapt_privacy/providers/presidio.py | 54 ++++++++++++++++++++++++- tests/test_phi_recall.py | 43 ++++++++++++++++++++ 2 files changed, 96 insertions(+), 1 deletion(-) diff --git a/openadapt_privacy/providers/presidio.py b/openadapt_privacy/providers/presidio.py index afb1dcf..c27cf2b 100644 --- a/openadapt_privacy/providers/presidio.py +++ b/openadapt_privacy/providers/presidio.py @@ -50,6 +50,35 @@ } ) +# Form-field labels that the small spaCy model reads as a name or an +# organization: "SSN: 923-45-6789" came back as ": " and +# "Email: ..." as ": ...". A label is not an identifier, and keeping it +# keeps the scrubbed text readable. Only a label that directly precedes another +# finding is kept, so the identifier it introduces is still redacted. +_FIELD_LABELS = frozenset( + { + "address", + "date of birth", + "dob", + "e-mail", + "email", + "email address", + "health card", + "ip", + "ip address", + "member id", + "mrn", + "name", + "patient id", + "phone", + "sin", + "social insurance number", + "social security number", + "ssn", + } +) +_FIELD_LABEL_SEPARATORS = " \t:#" + # Presidio scores an unvalidated, context-free digit run at 0.01-0.05. Below # this floor a pattern recognizer is guessing too, and must not take a label # away from the NER result. @@ -132,7 +161,8 @@ def _register_phi_recognizers(analyzer_engine) -> None: r"(?:\s+[NSEW])?" ) address_patterns = [ - Pattern("home-address", rf"(?i)(?<=Home address:\s){street}", 0.85), + # Any "...address: " label: "Address:", "Home address:", "Mailing address:". + Pattern("address-label", rf"(?i)(?<=address:\s){street}", 0.85), Pattern("mail-address", rf"(?i)(?<=Mail to\s){street}", 0.85), ] analyzer_engine.registry.add_recognizer( @@ -160,6 +190,27 @@ def _filter_automation_false_positives(text: str, analyzer_results: list) -> lis return filtered +def _keep_field_labels(text: str, analyzer_results: list) -> list: + """Drop NER findings that are a field label in front of an identifier. + + A PERSON or ORGANIZATION span is dropped only when its whole text is a + known label (``SSN``, ``Email``, ``DOB``) and another finding starts right + after it, past any spaces, ``:`` or ``#``. The identifier is still redacted; + only the label stays readable. + """ + starts = {result.start for result in analyzer_results} + kept = [] + for result in analyzer_results: + if result.entity_type in {"PERSON", "ORGANIZATION"}: + label = text[result.start : result.end].strip(_FIELD_LABEL_SEPARATORS).lower() + rest = text[result.end :] + next_start = result.end + len(rest) - len(rest.lstrip(_FIELD_LABEL_SEPARATORS)) + if label in _FIELD_LABELS and next_start in starts: + continue + kept.append(result) + return kept + + def _covers_every_digit(text: str, result, deterministic: list) -> bool: """Report whether pattern matches claim every digit inside `result`'s span. @@ -364,6 +415,7 @@ def scrub_text(self, text: str, is_separated: bool = False) -> str: ) analyzer_results = _filter_automation_false_positives(text, analyzer_results) analyzer_results = _prefer_deterministic_identifier_labels(text, analyzer_results) + analyzer_results = _keep_field_labels(text, analyzer_results) logger.debug(f"analyzer_results: {analyzer_results}") diff --git a/tests/test_phi_recall.py b/tests/test_phi_recall.py index 53892db..f7adc00 100644 --- a/tests/test_phi_recall.py +++ b/tests/test_phi_recall.py @@ -71,6 +71,7 @@ "STREET_ADDRESS", ), ("address", "Mail to 88 King St W, Toronto, ON M5H 1J9.", "88 King St W", "STREET_ADDRESS"), + ("address", "Address: 42 Elm Road", "42 Elm Road", "STREET_ADDRESS"), ("ip", "Last login from 192.168.10.22.", "192.168.10.22", "IP_ADDRESS"), ( "url", @@ -197,3 +198,45 @@ def test_a_low_confidence_pattern_does_not_take_a_label() -> None: kept = _prefer_deterministic_identifier_labels(text, [weak, date]) assert date in kept + + +@pytest.mark.parametrize( + ("text", "expected"), + [ + ("SSN: 923-45-6789", "SSN: "), + ("Email: john@example.com", "Email: "), + ("MRN: 00123456", "MRN: "), + ( + "Patient John Smith, john.smith@example.com, 555-123-4567, SSN 923-45-6789", + "Patient , , , SSN ", + ), + ], +) +def test_a_field_label_stays_readable_and_its_identifier_is_redacted( + scrubber, text: str, expected: str +) -> None: + assert scrubber.scrub_text(text) == expected + + +def test_a_label_shaped_span_with_nothing_after_it_is_still_redacted() -> None: + """A label is kept only when it introduces another finding.""" + from presidio_analyzer import RecognizerResult + + from openadapt_privacy.providers.presidio import _keep_field_labels + + text = "Ask Email" + alone = RecognizerResult(entity_type="PERSON", start=4, end=9, score=0.85) + + assert _keep_field_labels(text, [alone]) == [alone] + + +def test_a_name_in_front_of_an_identifier_is_still_redacted() -> None: + from presidio_analyzer import RecognizerResult + + from openadapt_privacy.providers.presidio import _keep_field_labels + + text = "John Smith: 555-123-4567" + person = RecognizerResult(entity_type="PERSON", start=0, end=10, score=0.85) + phone = RecognizerResult(entity_type="PHONE_NUMBER", start=12, end=24, score=0.75) + + assert _keep_field_labels(text, [person, phone]) == [person, phone] From 4cf355293dadc761be0fa73c3795cb8b0e9f7147 Mon Sep 17 00:00:00 2001 From: abrichr Date: Wed, 14 Oct 2026 03:20:05 -0400 Subject: [PATCH 2/6] fix: correct the fill colour docs and give the scan CLI real help text PrivacyConfig documented the default SCRUB_FILL_COLOR (0x0000FF) as blue. Pillow reads an integer colour as 0xBBGGRR, so the default fills red, which is what the demo screenshot shows. The docstring and comment now say so. openadapt-privacy-scan --help printed the module docstring, including notes for maintainers. It now describes what the scan checks and lists the exit codes. Co-Authored-By: Claude Opus 5.5 --- openadapt_privacy/config.py | 5 +++-- openadapt_privacy/scan.py | 12 +++++++++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/openadapt_privacy/config.py b/openadapt_privacy/config.py index c56a2ea..3a352ca 100644 --- a/openadapt_privacy/config.py +++ b/openadapt_privacy/config.py @@ -65,7 +65,8 @@ class PrivacyConfig: Attributes: SCRUB_CHAR: Character used to replace scrubbed text when using scrub_text_all. SCRUB_LANGUAGE: Language code for NLP analysis (default: "en"). - SCRUB_FILL_COLOR: BGR color value for image redaction (default: blue 0x0000FF). + SCRUB_FILL_COLOR: Image redaction color as a 0xBBGGRR integer + (default: red, 0x0000FF). SCRUB_KEYS_HTML: List of dict keys that should be scrubbed. SCRUB_KEYS_SEPARATED: Dict keys whose values may hold character-separated action text rather than prose. A value under one of these keys is @@ -87,7 +88,7 @@ class PrivacyConfig: # Language for NLP analysis SCRUB_LANGUAGE: str = "en" - # BGR color for image redaction (blue by default) + # Image redaction color as 0xBBGGRR (red by default) SCRUB_FILL_COLOR: int = 0x0000FF # Keys in dicts that should be scrubbed diff --git a/openadapt_privacy/scan.py b/openadapt_privacy/scan.py index f961b10..e6f888b 100644 --- a/openadapt_privacy/scan.py +++ b/openadapt_privacy/scan.py @@ -293,7 +293,17 @@ def self_test() -> int: def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__) + parser = argparse.ArgumentParser( + prog="openadapt-privacy-scan", + description=( + "Scan a git tree for health-data identifiers, remote-desktop hostnames, " + "UNC paths, and recording, screenshot, or database files." + ), + epilog=( + "Exit status: 0 clean, 1 a rule fired or a file couldn't be read, " + "2 the scan couldn't run." + ), + ) parser.add_argument( "--self-test", action="store_true", From e31ab7d2ba43b12e8916c83bd0d3182ebd77118c Mon Sep 17 00:00:00 2001 From: abrichr Date: Wed, 14 Oct 2026 03:20:06 -0400 Subject: [PATCH 3/6] docs: lead the README with what the package does and a quick start Rewrite the README for a developer who finds the package on GitHub or PyPI. The first screen says what it removes, who it is for, and a two-command install with a one-line example. Every Python example was run against the current code, and tests/test_readme.py checks the quick start, scrub_dict, and recording outputs against the scrubber. - Put the limits in one Limits section: synthetic test data, English only, context-dependent labels, labelled street addresses only, OCR misses, and a regex-only CI scan. - Move operator material (fail-closed behavior, the provenance record, review steps, and the repository lifecycle link) to docs/COMPLIANCE.md, linked once from the README. - Document configuration through the config object. The old example built a PrivacyConfig that nothing read. - Say that screenshot scrubbing needs the Tesseract binary. - Regenerate the scrubbed demo screenshot with the current code; the old one came from the first release and showed the card number unredacted. - Use absolute image and link URLs so they render on PyPI. - Replace the README text pin in tests/test_scan.py with tests/test_readme.py. - Fix the class name in CLAUDE.md (PresidioScrubber does not exist) and sharpen the PyPI summary. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 22 +-- README.md | 345 ++++++++++++++------------------- assets/screenshot_scrubbed.png | Bin 11381 -> 7508 bytes docs/COMPLIANCE.md | 83 ++++++++ pyproject.toml | 2 +- tests/test_readme.py | 159 +++++++++++++++ tests/test_scan.py | 8 - 7 files changed, 404 insertions(+), 215 deletions(-) create mode 100644 docs/COMPLIANCE.md create mode 100644 tests/test_readme.py diff --git a/CLAUDE.md b/CLAUDE.md index fb39e5e..35b130e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -26,16 +26,16 @@ uv run pytest tests/ -v # Scrub text uv run python -c " -from openadapt_privacy import PresidioScrubber -scrubber = PresidioScrubber() +from openadapt_privacy import PresidioScrubbingProvider +scrubber = PresidioScrubbingProvider() text = 'Contact John Smith at john@example.com or 555-123-4567' print(scrubber.scrub_text(text)) " # Scrub dictionary uv run python -c " -from openadapt_privacy import scrub_dict, PresidioScrubber -scrubber = PresidioScrubber() +from openadapt_privacy import scrub_dict, PresidioScrubbingProvider +scrubber = PresidioScrubbingProvider() data = {'name': 'John Smith', 'email': 'john@example.com'} print(scrub_dict(data, scrubber)) " @@ -45,16 +45,16 @@ print(scrub_dict(data, scrubber)) ``` openadapt_privacy/ - base.py # Base classes: Scrubber, ScrubbingProvider + base.py # Base classes: ScrubbingProvider, TextScrubbingMixin config.py # PrivacyConfig dataclass loaders.py # Recording/Action/Screenshot loaders pipelines/dicts.py # Dictionary scrubbing utilities - providers/presidio.py # PresidioScrubber (primary implementation) + providers/presidio.py # PresidioScrubbingProvider (primary implementation) ``` ## Key Components -### PresidioScrubber +### PresidioScrubbingProvider Primary scrubber using Presidio NER and spaCy: - Detects: PERSON, EMAIL_ADDRESS, PHONE_NUMBER, US_SSN, CREDIT_CARD, DATE_TIME, LOCATION - `scrub_text(text)` - Redact PII from text @@ -62,8 +62,8 @@ Primary scrubber using Presidio NER and spaCy: ### Text Scrubbing ```python -from openadapt_privacy import PresidioScrubber -scrubber = PresidioScrubber() +from openadapt_privacy import PresidioScrubbingProvider +scrubber = PresidioScrubbingProvider() text = "Contact John Smith at john@example.com" # Output: "Contact at " print(scrubber.scrub_text(text)) @@ -71,8 +71,8 @@ print(scrubber.scrub_text(text)) ### Dictionary Scrubbing ```python -from openadapt_privacy import scrub_dict, PresidioScrubber -scrubber = PresidioScrubber() +from openadapt_privacy import scrub_dict, PresidioScrubbingProvider +scrubber = PresidioScrubbingProvider() action = {"text": "Email john@example.com", "title": "User John Smith"} scrubbed = scrub_dict(action, scrubber) ``` diff --git a/README.md b/README.md index ec46f6c..b9aa61e 100644 --- a/README.md +++ b/README.md @@ -5,144 +5,49 @@ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue)](https://www.python.org/downloads/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -Finds and removes personal and health data from GUI automation artifacts: the -text a recording captured, the element trees around it, and the screenshots. -Presidio does the detection; this package wires it to the shapes a recording -actually has. +Remove names, email addresses, phone numbers, SSNs, card numbers, medical +record numbers, and other personal or health data from GUI recordings before +you store or share them. It scrubs typed text, window titles, accessibility +trees, event payloads, and screenshots. Detection uses +[Microsoft Presidio](https://github.com/microsoft/presidio) with a local spaCy +model, and scrubbing runs on your machine. -A demonstration recording contains everything that was on screen and everything -that was typed. So before you store one, share one, or export one, something -has to strip the identifiers out, and that something needs to fail loudly when -it can't. That's this. +Use it if you record desktop or browser sessions for test automation, RPA, or +training data. It also includes `openadapt-privacy-scan`, a CI check that needs +no other packages and fails when a git tree holds health-data identifiers or +recording files. -[Documentation](https://docs.openadapt.ai) · -[openadapt-flow](https://github.com/OpenAdaptAI/openadapt-flow) · -[Repository lifecycle](https://github.com/OpenAdaptAI/.github/blob/main/REPOSITORY_LIFECYCLE.md) - -## Install +## Quick start ```bash pip install "openadapt-privacy[presidio]" python -m spacy download en_core_web_sm ``` -The Presidio provider takes only the preinstalled, allowlisted `en_core_web_sm` -pipeline and never downloads a model at runtime. A missing model, an -unsupported language, or an inconsistent configuration raises -`PrivacyModelUnavailable` before analysis starts, rather than quietly scrubbing -worse than you expected. - -## Git / CI scan (`[scan]`) - -A regex gate for git trees. Clinic CI calls it so an OHIP-shaped number, a -chart id, an MRN, a UNC path, or an RDP hostname can't land in a commit. It -doesn't scrub recordings. It does not claim clinical validation. - -```bash -pip install "openadapt-privacy[scan]" -openadapt-privacy-scan -openadapt-privacy-scan --self-test -openadapt-privacy-scan --root /path/to/repo -``` - -The command exits with: - -- `0` when it read every file and no rule fired. -- `1` when a rule fired or a file couldn't be read. -- `2` when the scan couldn't run: the root is missing, isn't a directory, or - can't be accessed; a directory under it can't be listed; or it has no files. - Pass `--allow-empty` if an empty tree is expected. - -`[scan]` adds no packages. The scanner is stdlib, so `import openadapt_privacy.scan` -works on a bare `pip install openadapt-privacy` and does not load Presidio, -spaCy, or Pillow. `python -m openadapt_privacy.scan` is the same CLI. - -```python -from pathlib import Path -from openadapt_privacy.scan import scan_tree, self_test - -hits = scan_tree(Path(".")) # ["ohip-dashed\tfile.txt:3", ...] -self_test() # 0 ok, 1 a rule stayed silent -``` - -`scan_tree` raises `OSError` when the root is missing, isn't a directory, or has -a directory that can't be listed. It returns `[]` for a tree with no files, so -check `iter_scan_files(root)` first if an empty tree should fail. - -`--self-test` plants fixtures under `/tmp` and exits 1 if a rule does not fire. -Matching OHIP examples are not stored in the library; they're built at runtime. - -Forbidden directory names: `recordings`, `captures`, `screenshots`, -`retinology`, `.private`. Forbidden suffixes include `.rdp`, `.db`, and -common media (`.png`, `.mp4`, and the rest of the set in `scan.py`). - -`openadapt_privacy/gitleaks.toml` and `openadapt_privacy/phi-patterns.txt` -carry the same rules for gitleaks / git-secrets. - -## Read this before you rely on it - -Scrubbing is one control inside a reviewed egress process. It is not a -guarantee that an artifact is free of protected data, and the evidence behind -it is synthetic, not clinical. - -`tests/test_phi_recall.py` is the regression gate: 26 synthetic identifiers -across names, contact details, financial identifiers, dates of birth, -addresses, network identifiers, medical record numbers, member IDs, and -provider licenses. It requires 26 out of 26, it pins the entity type each one -must produce, and it also checks that ordinary operational UI text comes back -untouched. - -Detection is contextual, so the same value scrubs differently depending on what -surrounds it. Every output below was produced by running this code on -2026-08-28, not written by hand. Some of it will surprise you: - ```python ->>> from openadapt_privacy.providers.presidio import PresidioScrubbingProvider ->>> s = PresidioScrubbingProvider() - ->>> s.scrub_text("Patient John Smith, john.smith@example.com, 555-123-4567, SSN 923-45-6789") -'Patient , , , ' - ->>> s.scrub_text("SSN: 923-45-6789") -': ' +from openadapt_privacy import PresidioScrubbingProvider ->>> s.scrub_text("Card 4111111111111111 on file") -'Card on file' - ->>> s.scrub_text("Card: 4532-1234-5678-9012") -'Card: ' +scrubber = PresidioScrubbingProvider() +print(scrubber.scrub_text("Contact John Smith at john.smith@example.com or 555-123-4567")) +# Contact at or ``` -The last two are the interesting pair. Both card numbers get redacted, but only -the first is labelled `CREDIT_CARD`, because only the first passes a Luhn -check. An identifier that no recognizer can validate falls to whatever the -spaCy model makes of it, which for a run of digits is usually `DATE_TIME`. - -So: the redaction holds either way, and a validated identifier now carries its -own type. An unvalidated one does not. Measure the placeholder names against -your own data before you route on them. - -For production egress: scrub a copy, verify every output file, and bind the -human or policy approval to the verified artifact. A model that ran without -error is not evidence that the artifact is clean. +If the spaCy model or a Presidio package is missing, the scrubber raises +`PrivacyModelUnavailable` or `ImportError` instead of returning text. It does +not fall back to scrubbing less, and it never downloads a model at run time. -## Scrubbing text +You need Python 3.10 or later. Screenshot scrubbing also needs the +[Tesseract](https://github.com/tesseract-ocr/tesseract) OCR binary on your +`PATH`, for example from `brew install tesseract` or +`apt-get install tesseract-ocr`. -```python -from openadapt_privacy.providers.presidio import PresidioScrubbingProvider - -scrubber = PresidioScrubbingProvider() -scrubber.scrub_text("Contact John Smith at john.smith@example.com or 555-123-4567") -# 'Contact at or ' -``` +## Scrub element trees and event payloads -## Scrubbing nested dicts - -For element trees and event payloads: +`scrub_dict` walks nested dicts and lists and scrubs the string values of +known keys: ```python -from openadapt_privacy import scrub_dict -from openadapt_privacy.providers.presidio import PresidioScrubbingProvider +from openadapt_privacy import PresidioScrubbingProvider, scrub_dict scrubber = PresidioScrubbingProvider() scrub_dict( @@ -154,129 +59,179 @@ scrub_dict( }, scrubber, ) +# {'title': 'User Profile - ', +# 'tooltip': 'Click to contact ', +# 'value': 'Call ', +# 'coordinates': {'x': 100, 'y': 200}} ``` -```json -{ - "title": "User Profile - ", - "tooltip": "Click to contact ", - "value": "Call ", - "coordinates": {"x": 100, "y": 200} -} -``` - -Only the keys in `PrivacyConfig.SCRUB_KEYS_HTML` are scrubbed, and non-string -values pass through, which is why the coordinates survive. Pass `scrub_all=True` -to scrub every string regardless of key. +Only the keys in `config.SCRUB_KEYS_HTML` are scrubbed, and non-string values +pass through unchanged. Pass `scrub_all=True` to scrub every string. -The keys in `PrivacyConfig.SCRUB_KEYS_SEPARATED` (`text` and `canonical_text`) -can also hold recorded keystrokes: one typed character per `ACTION_TEXT_SEP`, -as in `j-o-h-n-@-e-x-a-m-p-l-e-.-c-o-m`. Those are reassembled before analysis, -scrubbed, and separated again, because the PII is invisible in the split form. -Whether that happens is decided by the value, not the key, so prose under -`text` is scrubbed as prose: +Recorded keystrokes often arrive one character at a time, as in +`j-o-h-n-@-e-x-a-m-p-l-e-.-c-o-m`, where no detector can see the address. Under +the `text` and `canonical_text` keys, the scrubber joins a value in that form, +scrubs it, and splits it again. Prose under the same keys is scrubbed as prose: ```python scrub_dict({"text": "Email: john@example.com"}, scrubber) -# {'text': ': '} +# {'text': 'Email: '} scrub_dict({"text": "-".join("john@example.com")}, scrubber) # {'text': '<-E-M-A-I-L-_-A-D-D-R-E-S-S->'} ``` -Pass `separated_keys=[]` to turn keystroke handling off for a call, or -`separated_keys=["keys"]` to move it to your own field name. +Pass `separated_keys=["keys"]` to use your own field name, or +`separated_keys=[]` to turn keystroke handling off. -## Scrubbing screenshots +## Scrub screenshots ```python from PIL import Image -from openadapt_privacy.providers.presidio import PresidioScrubbingProvider +from openadapt_privacy import PresidioScrubbingProvider scrubber = PresidioScrubbingProvider() -scrubbed = scrubber.scrub_image(Image.open("screenshot.png")) -scrubbed.save("screenshot_scrubbed.png") +scrubber.scrub_image(Image.open("screenshot.png")).save("screenshot_scrubbed.png") ``` -![Original screenshot with PII](assets/screenshot_original.png) -![Scrubbed screenshot with PII redacted](assets/screenshot_scrubbed.png) +Tesseract finds the text, Presidio classifies it, and each detected region is +filled with solid red. `scripts/generate_demo_images.py` produced this output: + +| Before | After | +| --- | --- | +| ![Synthetic profile form with a name, email address, phone number, SSN, and card number](https://raw.githubusercontent.com/OpenAdaptAI/openadapt-privacy/main/assets/screenshot_original.png) | ![The same form with the email address, phone number, SSN, card number, and two field labels covered in red; the name in the dark title bar is still visible](https://raw.githubusercontent.com/OpenAdaptAI/openadapt-privacy/main/assets/screenshot_scrubbed.png) | -OCR finds the text regions, the analyzer classifies them, and the detected -regions get filled with a solid colour (`SCRUB_FILL_COLOR`, red by default). -Anything OCR misses is not redacted. +The name in the dark title bar is still visible because Tesseract did not read +light text on a dark background. See [Limits](#limits). -## Whole recordings +## Scrub a whole recording -`DictRecordingLoader` takes a recording as a dict and scrubs the task -description and every action together: +`Recording.scrub` scrubs the task description, every action, and every +screenshot in one call: ```python -from openadapt_privacy import DictRecordingLoader -from openadapt_privacy.providers.presidio import PresidioScrubbingProvider +from openadapt_privacy import DictRecordingLoader, PresidioScrubbingProvider -recording = DictRecordingLoader().load_from_dict({ +loader = DictRecordingLoader() +recording = loader.load_from_dict({ "task_description": "Send email to John Smith at john@example.com", "actions": [ {"id": 1, "action_type": "click", "text": "Compose", "timestamp": 1000}, - {"id": 2, "action_type": "click", "text": "Send", - "window_title": "Email to john@example.com", "timestamp": 3000}, + {"id": 2, "action_type": "type", "text": "-".join("john@example.com"), "timestamp": 2000}, ], }) scrubbed = recording.scrub(PresidioScrubbingProvider()) +scrubbed.task_description +# 'Send email to at ' ``` -Subclass `RecordingLoader` for your own storage. Implement `load` and `save`, -and you get `load_and_scrub` for free: +A screenshot must have its pixels loaded in `Screenshot.image`. One that has +only a `path` raises `UnscrubbedScreenshot` instead of passing through +unredacted; pass `scrub_images=False` to leave screenshots out on purpose. The +scrubbed recording's `metadata["_openadapt_privacy"]` records the provider, the +package version, and a hash of the settings used. + +`DictRecordingLoader` also reads and writes JSON files with `load` and `save`. +For your own storage, subclass `RecordingLoader` and implement `load` and +`save`, and `load_and_scrub` works too: ```python -from openadapt_privacy import RecordingLoader, Recording +from openadapt_privacy import Recording, RecordingLoader class SQLiteRecordingLoader(RecordingLoader): - def load(self, recording_id: str) -> Recording: ... - def save(self, recording: Recording, recording_id: str) -> None: ... + def load(self, source: str) -> Recording: ... + def save(self, recording: Recording, destination: str) -> None: ... ``` -## Configuration +## Block identifiers in CI + +`openadapt-privacy-scan` checks a git tree for health-data identifiers (Ontario +health card numbers, chart IDs, and MRNs), remote-desktop hostnames, UNC +paths, and recording, screenshot, or database files. It uses only the Python +standard library, so the base package is enough: + +```bash +pip install openadapt-privacy +openadapt-privacy-scan --self-test # check that every rule fires on planted fixtures +openadapt-privacy-scan --root . # scan the tree +``` + +The scan exits with: + +- `0` when it read every file and no rule fired. +- `1` when a rule fired or a file couldn't be read. +- `2` when the scan couldn't run: the root is missing or unreadable, a + directory under it can't be listed, or it has no files. Pass `--allow-empty` + if an empty tree is expected. + +The same check is available from Python. Importing `openadapt_privacy.scan` +does not load Presidio, spaCy, or Pillow: ```python -from openadapt_privacy.config import PrivacyConfig +from pathlib import Path +from openadapt_privacy.scan import scan_tree -PrivacyConfig( - SCRUB_CHAR="X", # for scrub_text_all - SCRUB_FILL_COLOR=0xFF0000, # image redaction, BGR - SCRUB_KEYS_HTML=["text", "value", "title", "tooltip"], - SCRUB_PRESIDIO_IGNORE_ENTITIES=["DATE_TIME"], -) +hits = scan_tree(Path(".")) # for example ["mrn-assigned\tnotes.txt:3"] ``` -The full field list is `SCRUB_CHAR`, `SCRUB_LANGUAGE`, `SCRUB_FILL_COLOR`, -`SCRUB_KEYS_HTML`, `SCRUB_KEYS_SEPARATED`, `ACTION_TEXT_NAME_PREFIX`, -`ACTION_TEXT_NAME_SUFFIX`, `ACTION_TEXT_SEP`, `SCRUB_CONFIG_TRF`, -`SCRUB_PRESIDIO_IGNORE_ENTITIES`, and `SPACY_MODEL_NAME`. +`openadapt_privacy/gitleaks.toml` and `openadapt_privacy/phi-patterns.txt` +carry the same rules for gitleaks and git-secrets. -The analyzer's supported entity set comes from Presidio: `CREDIT_CARD`, -`CRYPTO`, `DATE_TIME`, `EMAIL_ADDRESS`, `IBAN_CODE`, `IP_ADDRESS`, `LOCATION`, -`MAC_ADDRESS`, `MEDICAL_LICENSE`, `NRP`, `PERSON`, `PHONE_NUMBER`, `UK_NHS`, -`URL`, `US_BANK_NUMBER`, `US_DRIVER_LICENSE`, `US_ITIN`, `US_PASSPORT`, -`US_SSN`, plus `ORGANIZATION` from the spaCy pipeline. Which one fires on a -given string depends on the text around it, so measure rather than assume. +## Configuration + +Settings live on the module-level `config` object. Change them before you +scrub: -## Layout +```python +from openadapt_privacy.config import config +config.SCRUB_PRESIDIO_IGNORE_ENTITIES = ["DATE_TIME"] # keep dates +config.SCRUB_FILL_COLOR = 0x000000 # black boxes; 0xBBGGRR, default red +config.SCRUB_KEYS_HTML = [*config.SCRUB_KEYS_HTML, "label"] ``` -openadapt_privacy/ -├── scan.py # git/CI regex gate (stdlib; no Presidio) -├── gitleaks.toml # same rules for gitleaks -├── phi-patterns.txt # same rules for git-secrets -├── base.py # ScrubbingProvider, TextScrubbingMixin -├── config.py # PrivacyConfig -├── loaders.py # Recording, Action, Screenshot, RecordingLoader -├── providers/ -│ └── presidio.py # PresidioScrubbingProvider -└── pipelines/ - └── dicts.py # scrub_dict, scrub_list_dicts + +The fields are `SCRUB_CHAR`, `SCRUB_LANGUAGE`, `SCRUB_FILL_COLOR`, +`SCRUB_KEYS_HTML`, `SCRUB_KEYS_SEPARATED`, `ACTION_TEXT_NAME_PREFIX`, +`ACTION_TEXT_NAME_SUFFIX`, `ACTION_TEXT_SEP`, `SCRUB_CONFIG_TRF`, +`SCRUB_PRESIDIO_IGNORE_ENTITIES`, and `SPACY_MODEL_NAME`. The entity types come +from Presidio (`PERSON`, `EMAIL_ADDRESS`, `PHONE_NUMBER`, `US_SSN`, +`CREDIT_CARD`, `DATE_TIME`, `LOCATION`, `IP_ADDRESS`, `URL`, and others), plus +`ORGANIZATION` from spaCy and `MEDICAL_RECORD_NUMBER` and `STREET_ADDRESS` from +this package. + +## Limits + +- The test set is 27 synthetic identifiers in `tests/test_phi_recall.py`. Every + one must be redacted with the right entity type. The data is synthetic, not + clinical, so measure recall on your own data before you rely on it. +- English only, with the `en_core_web_sm` spaCy model. +- Detection depends on context. A card number that fails the Luhn check is still + redacted, but as `` rather than ``. Check placeholder + names against your data before you route on them. +- Street addresses are found only after a label such as `Address:` or + `Mail to`. +- In screenshots, text that Tesseract can't read is not redacted. +- `openadapt-privacy-scan` matches regular expressions. It does not claim + clinical validation. + +If you deploy this where recordings can hold protected health information, read +[docs/COMPLIANCE.md](https://github.com/OpenAdaptAI/openadapt-privacy/blob/main/docs/COMPLIANCE.md) +for the fail-closed behavior, the provenance record each scrub writes, and the +review steps around it. + +## Development + +```bash +git clone https://github.com/OpenAdaptAI/openadapt-privacy +cd openadapt-privacy +uv sync --extra dev --extra presidio +uv pip install pip +uv run python -m spacy download en_core_web_sm +uv run pytest ``` ## License -[MIT](LICENSE) +[MIT](https://github.com/OpenAdaptAI/openadapt-privacy/blob/main/LICENSE). +openadapt-privacy is part of [OpenAdapt](https://github.com/OpenAdaptAI/OpenAdapt) +and works without it. diff --git a/assets/screenshot_scrubbed.png b/assets/screenshot_scrubbed.png index 01a0f8d48287413ed0b8b294317ec0851f9d6695..d9ef8b624e5665578015137f49b9b2142e600792 100644 GIT binary patch literal 7508 zcmdT}XH-*po4@F&s0i2vL@YBPf;15jBw#~C2vVe1>Ag3pD#}PzK`Eg*^e&RnAp#;I zQbUo@1ccB+sG)~_aCgq^yYKA2y65bN{hH+7`@c{5wLHCpzPWD?>mCF__T7@bu8bht zG!TUD8T~f+WJCRFGlH~)D&G|@JQv74(WchkX3i#;jJ;u1kuRLS5%}egS6VljZ~YoRa4CMk z&c~^)?H5H(ul_vz3$yqYRI}(MF3RPG&&TvUMh@>l{8agx`solP_9^o=9kAx9Ql}*voFyIwRIHNlI%<{{H@l z#-0*`QOjSqr{JGGdp1r;%hN96)jACwH+8hqS$}D|Pik|0 zUQud8HH^#}@*z3-*A&$NMs_~^%IrE$L@e$-GdljVM`O&zLc5@&{CYUcj*lNdhO$dM z2?(GNag%Elye}u)-2A+XoI;$q%i=_bTGm}|+*GBRQ1MysH7dD1Lq$!k^Wl!YKC9zt z4Uzn1Wo2F2n)8jK1J?cJEAJj`ClCnu)rqXM0cQM3>65wpGqba^+uPfBALKlK+5HZ8 zN2T|g*<#Ikwd^S6iLurstsS$*y}iBnm!@+fVg!voyftay(TzB*?VSwo=5X- za);%{U;xJnFXzGP$8s4$CZF0f?>6{ohjS_jv4(8l#V9W;`z7C~u1nvyFW=}U*_!mV z>Je^3US1yF&(URLbN)0HpSUtlvLfAhsXW=0r-(*Vsnn*;2)fJsvG$f&)ePmJBj?-D zY?i)JG)H||*^e!+ui5NUM4?c7kMPdS&bC&bSI^bKh}cwDSC2NuP1?J**3=lmX)aoI zs>-o2JW1=74A|?>#C};!%)K*Pb9#E3SfrqZz|eQ&M#CK79=hS@&uKVRYY~7iA5ZA8oYy^5!))Cm}%} zD$r^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6cps@e+m`--zUPipPpI$hrTXVh@)8_N?@}(@&fj1nXqvkQT#Q8)f zCME#^S8NDq3rX+DCd@4^T6bjhf*E4>W1^xw@Jv7;kPTlyKb#1JLj6=#g<+Qxq(Bpt zMxqnd^K=j`U>zt4*gx`Du3S-2fKx%r;bCQ`7pnoRCQaebj@~(-|sZ0`@;J8mk`Df!!7p&^3c!p=J`AU8=;(TLEz}cmY@xN=rksw7 zY82=~7~j^YF`!rm7EXv&S(vc(kG!N!Ma};}LN5 zrU=E7l#~SeIHsle!yR|b)K^&MjOeJzap~#KaXT`AZoR HH}3s6)+nV_ diff --git a/docs/COMPLIANCE.md b/docs/COMPLIANCE.md new file mode 100644 index 0000000..0c6aa5b --- /dev/null +++ b/docs/COMPLIANCE.md @@ -0,0 +1,83 @@ +# Compliance and operator notes + +This page is for people who deploy openadapt-privacy where recordings can hold +protected health information (PHI) or other personal data, and who need to +explain to a reviewer how the scrubbing is controlled. For installation and +usage, see the [README](../README.md). + +Scrubbing is one control inside a reviewed process for data leaving your +environment. It does not guarantee that an artifact is free of protected data. + +## Fail-closed behavior + +The package raises an error instead of returning output that looks scrubbed +but isn't. + +| Condition | Result | +| --- | --- | +| The spaCy model is not installed or not allowlisted (only `en_core_web_sm` is), the language is not `en`, or `SCRUB_CONFIG_TRF` names a different model | `PrivacyModelUnavailable` before any text is analyzed. The package never downloads a model at run time. | +| spaCy or a Presidio package is missing | `ImportError`, or `PrivacyModelUnavailable` when `validate_ready` finds a Presidio package missing. Nothing is scrubbed. | +| A built-in provider fails to import when you ask `ScrubbingProviderFactory` for one | `ScrubbingProviderUnavailable`, never an empty list. | +| A provider can't handle a modality the recording needs | `ScrubbingProviderUnavailable` from `validate_ready`, before `Recording.scrub` reads any content. | +| A screenshot names a file on disk but its pixels were never loaded | `UnscrubbedScreenshot`. A scrubbed `Screenshot` never keeps the `path` to the original file. | +| Code changes the scrub settings while `Recording.scrub` is running | `ScrubbingPolicyChanged`. Each recording is scrubbed under one snapshot of the settings. | + +The CI scanner fails closed too: it exits `2` when it can't read the tree or +the tree is empty, and `--self-test` exits `1` if any rule does not fire on its +planted fixtures. Run `--self-test` in CI before the scan, so a rule that stops +matching fails the build. + +## Provenance record + +`Recording.scrub` adds this entry to the scrubbed recording's metadata. It +holds no scrubbed content. + +```json +{ + "_openadapt_privacy": { + "schema_version": 1, + "provider": "PRESIDIO", + "provider_class": "openadapt_privacy.providers.presidio.PresidioScrubbingProvider", + "package_version": "", + "policy_sha256": "", + "modalities": ["TEXT"], + "status": "completed", + "omitted_modalities": [] + } +} +``` + +`omitted_modalities` is `["PIL_IMAGE"]` when you call +`scrub(..., scrub_images=False)`, so a reviewer can see that screenshots were +left out on purpose. For other workflows, `ScrubbingProvider.evidence()` +returns the same fields except `omitted_modalities`. + +## What the tests show + +- `tests/test_phi_recall.py` has 27 synthetic identifiers: names, email + addresses, phone numbers, an SSN, card numbers, a bank account number, dates + of birth, street addresses, an IP address, a URL, medical record numbers, a + member ID, and a provider license. The test requires all 27 to be redacted and + pins the entity type each one must produce. Nine ordinary UI strings, such as + `Click Save to continue.`, must come back unchanged. +- The data is synthetic, not clinical. No clinical validation is claimed. +- CI runs the suite on Python 3.10, 3.11, and 3.12 without Presidio, and the + full suite with Presidio on Python 3.12. +- `openadapt-privacy-scan` matches regular expressions for the shapes it names. + It does not claim clinical validation. + +## Recommended review steps + +1. Scrub a copy. Keep the original where it already is. +2. Check every output file. Re-run the text scrubber or the CI scanner on text + output, and look at every scrubbed screenshot, because OCR misses some text. +3. Tie the human or policy approval to the checked artifact, for example by its + hash, and not to the fact that the scrubber ran. A scrubber that finished + without an error is not evidence that the artifact is clean. +4. Keep the provenance record with the artifact. + +## Repository status + +How OpenAdapt classifies and supports its repositories is described in the +organization's +[repository lifecycle](https://github.com/OpenAdaptAI/.github/blob/main/REPOSITORY_LIFECYCLE.md). diff --git a/pyproject.toml b/pyproject.toml index 39e2dd4..012ed2b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,7 +1,7 @@ [project] name = "openadapt-privacy" version = "1.1.1" -description = "Privacy scrubbing for GUI automation data - PII/PHI detection and redaction" +description = "Find and redact personal and health data in GUI recordings: typed text, accessibility trees, and screenshots" readme = "README.md" requires-python = ">=3.10" license = "MIT" diff --git a/tests/test_readme.py b/tests/test_readme.py new file mode 100644 index 0000000..0029679 --- /dev/null +++ b/tests/test_readme.py @@ -0,0 +1,159 @@ +"""Keep the README honest: its limits stay stated and its examples stay real.""" + +from __future__ import annotations + +import ast +import re +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +README = (ROOT / "README.md").read_text(encoding="utf-8") +COMPLIANCE = (ROOT / "docs" / "COMPLIANCE.md").read_text(encoding="utf-8") + + +def _section(text: str, heading: str) -> str: + match = re.search(rf"(?ms)^## {re.escape(heading)}\n(.*?)(?=^## |\Z)", text) + assert match is not None, f"missing section: {heading}" + return " ".join(match.group(1).split()) + + +def test_readme_states_its_limits_in_one_section() -> None: + limits = _section(README, "Limits") + assert "synthetic, not clinical" in limits + assert "does not claim clinical validation" in limits + + +def test_readme_documents_the_scan_exit_codes() -> None: + scan = _section(README, "Block identifiers in CI") + assert "openadapt-privacy-scan --self-test" in scan + assert "--allow-empty" in scan + + +def test_readme_links_the_compliance_notes_once() -> None: + assert len(re.findall(r"\]\([^)]*docs/COMPLIANCE\.md\)", README)) == 1 + compliance = " ".join(COMPLIANCE.split()) + assert "does not claim clinical validation" in compliance + assert "synthetic, not clinical" in compliance + + +def test_readme_leaves_operator_language_to_the_compliance_notes() -> None: + lowered = README.lower() + for term in ("admission", "admitted", "ledger", "evidence authority", "product target"): + assert term not in lowered, term + assert "lifecycle" not in lowered + + +def test_readme_recall_count_matches_the_test_set() -> None: + # Read the count from source: importing the module skips it without spaCy. + tree = ast.parse((ROOT / "tests" / "test_phi_recall.py").read_text(encoding="utf-8")) + cases = next( + node.value + for node in tree.body + if isinstance(node, ast.Assign) + and any( + isinstance(target, ast.Name) and target.id == "PHI_CASES" for target in node.targets + ) + ) + assert isinstance(cases, ast.List) + + assert f"{len(cases.elts)} synthetic identifiers" in README + assert f"{len(cases.elts)} synthetic identifiers" in COMPLIANCE + + +try: + import spacy + + from openadapt_privacy.config import config + + _HAS_MODEL = spacy.util.is_package(config.SPACY_MODEL_NAME) +except ImportError: + _HAS_MODEL = False + +needs_model = pytest.mark.skipif(not _HAS_MODEL, reason="Presidio and the spaCy model are needed") + + +@pytest.fixture(scope="module") +def scrubber(): + from openadapt_privacy import PresidioScrubbingProvider + + return PresidioScrubbingProvider() + + +@needs_model +def test_quick_start_output_is_what_the_scrubber_returns(scrubber) -> None: + text = "Contact John Smith at john.smith@example.com or 555-123-4567" + output = "Contact at or " + assert f'print(scrubber.scrub_text("{text}"))' in README + assert f"# {output}" in README + assert scrubber.scrub_text(text) == output + + +@needs_model +@pytest.mark.parametrize( + ("call", "value", "output"), + [ + ( + 'scrub_dict({"text": "Email: john@example.com"}, scrubber)', + {"text": "Email: john@example.com"}, + {"text": "Email: "}, + ), + ( + 'scrub_dict({"text": "-".join("john@example.com")}, scrubber)', + {"text": "-".join("john@example.com")}, + {"text": "<-E-M-A-I-L-_-A-D-D-R-E-S-S->"}, + ), + ], +) +def test_keystroke_examples_are_what_scrub_dict_returns(scrubber, call, value, output) -> None: + from openadapt_privacy import scrub_dict + + assert f"{call}\n# {output!r}" in README + assert scrub_dict(value, scrubber) == output + + +@needs_model +def test_element_tree_example_is_what_scrub_dict_returns(scrubber) -> None: + from openadapt_privacy import scrub_dict + + scrubbed = scrub_dict( + { + "title": "User Profile - John Smith", + "tooltip": "Click to contact john@example.com", + "value": "Call 555-123-4567", + "coordinates": {"x": 100, "y": 200}, + }, + scrubber, + ) + assert scrubbed == { + "title": "User Profile - ", + "tooltip": "Click to contact ", + "value": "Call ", + "coordinates": {"x": 100, "y": 200}, + } + for key, value in scrubbed.items(): + assert f"{key!r}: {value!r}" in README + + +@needs_model +def test_recording_example_is_what_recording_scrub_returns(scrubber) -> None: + from openadapt_privacy import DictRecordingLoader + + recording = DictRecordingLoader().load_from_dict( + { + "task_description": "Send email to John Smith at john@example.com", + "actions": [ + {"id": 1, "action_type": "click", "text": "Compose", "timestamp": 1000}, + { + "id": 2, + "action_type": "type", + "text": "-".join("john@example.com"), + "timestamp": 2000, + }, + ], + } + ) + scrubbed = recording.scrub(scrubber) + assert scrubbed.task_description == "Send email to at " + assert f"# {scrubbed.task_description!r}" in README diff --git a/tests/test_scan.py b/tests/test_scan.py index 0aa0b9a..265e07b 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -396,11 +396,3 @@ def test_scan_is_not_reexported_from_package_init() -> None: assert "scan_tree" not in openadapt_privacy.__all__ assert "scan" not in openadapt_privacy._LAZY_EXPORTS assert "scan_tree" not in openadapt_privacy._LAZY_EXPORTS - - -def test_readme_keeps_presidio_caveat_and_has_scan_section() -> None: - readme = (ROOT / "README.md").read_text(encoding="utf-8") - assert "## Git / CI scan (`[scan]`)" in readme - assert "synthetic, not clinical" in readme - assert "does not claim clinical validation" in readme - assert "--allow-empty" in readme From cef1906af46e5496c19c8d7c49007f017cb99f92 Mon Sep 17 00:00:00 2001 From: abrichr Date: Wed, 14 Oct 2026 03:41:51 -0400 Subject: [PATCH 4/6] fix: keep a surname that matches a label abbreviation redacted The field-label filter dropped a PERSON span whose whole text was a label in front of another finding. "Ip" and "Sin" were in the label list, and both are surnames, so "Dr. Sin: 555-123-4567" came back as "Dr. Sin: " and "Sin john@example.com" as "Sin ". Release 1.1.1 redacted the name in both. Remove "ip" and "sin" from the list. "IP address" and "social insurance number" stay. "SIN:" and "IP:" labels go back to being redacted along with the identifier after them, which over-redacts but leaks nothing. Co-Authored-By: Claude Opus 5.5 --- openadapt_privacy/providers/presidio.py | 5 +++-- tests/test_phi_recall.py | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/openadapt_privacy/providers/presidio.py b/openadapt_privacy/providers/presidio.py index c27cf2b..b0e4552 100644 --- a/openadapt_privacy/providers/presidio.py +++ b/openadapt_privacy/providers/presidio.py @@ -55,6 +55,9 @@ # "Email: ..." as ": ...". A label is not an identifier, and keeping it # keeps the scrubbed text readable. Only a label that directly precedes another # finding is kept, so the identifier it introduces is still redacted. +# Leave out a label that is also a surname, such as "Ip" or "Sin": in +# "Dr. Sin: 555-123-4567" the name must stay redacted. Their longer forms +# ("IP address", "social insurance number") are listed. _FIELD_LABELS = frozenset( { "address", @@ -64,14 +67,12 @@ "email", "email address", "health card", - "ip", "ip address", "member id", "mrn", "name", "patient id", "phone", - "sin", "social insurance number", "social security number", "ssn", diff --git a/tests/test_phi_recall.py b/tests/test_phi_recall.py index f7adc00..8668719 100644 --- a/tests/test_phi_recall.py +++ b/tests/test_phi_recall.py @@ -240,3 +240,24 @@ def test_a_name_in_front_of_an_identifier_is_still_redacted() -> None: phone = RecognizerResult(entity_type="PHONE_NUMBER", start=12, end=24, score=0.75) assert _keep_field_labels(text, [person, phone]) == [person, phone] + + +@pytest.mark.parametrize("surname", ["Sin", "Ip"]) +def test_a_surname_that_spells_a_label_abbreviation_is_still_redacted(surname: str) -> None: + """The labels SIN and IP are also the surnames Sin and Ip.""" + from presidio_analyzer import RecognizerResult + + from openadapt_privacy.providers.presidio import _keep_field_labels + + text = f"Dr. {surname}: 555-123-4567" + person = RecognizerResult(entity_type="PERSON", start=4, end=4 + len(surname), score=0.85) + phone = RecognizerResult( + entity_type="PHONE_NUMBER", start=text.index("555"), end=len(text), score=0.75 + ) + + assert _keep_field_labels(text, [person, phone]) == [person, phone] + + +@pytest.mark.parametrize("text", ["Dr. Sin: 555-123-4567", "Sin john@example.com"]) +def test_a_surname_next_to_an_identifier_is_redacted_end_to_end(scrubber, text: str) -> None: + assert "Sin" not in scrubber.scrub_text(text) From acff349804c0eb1741d77e84ebe8b914aabe07c0 Mon Sep 17 00:00:00 2001 From: abrichr Date: Wed, 14 Oct 2026 03:41:51 -0400 Subject: [PATCH 5/6] fix: drop internal wording from the scan output and config docs openadapt-privacy-scan printed "PHI / clinic-path scan failed:" on a hit, and scan_tree's docstring referred to an internal scanner. The message is now "PHI scan failed:" and the docstring says what each line holds. The help text says the scan checks the files in a directory, since it also runs outside a git repository. The config module docstring still said you could create a new PrivacyConfig. Nothing reads one, so it now points to the module-level config instance. Co-Authored-By: Claude Opus 5.5 --- openadapt_privacy/config.py | 4 ++-- openadapt_privacy/scan.py | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/openadapt_privacy/config.py b/openadapt_privacy/config.py index 3a352ca..7cc977e 100644 --- a/openadapt_privacy/config.py +++ b/openadapt_privacy/config.py @@ -1,8 +1,8 @@ """Configuration for privacy scrubbing. This module provides configuration settings for PII/PHI scrubbing operations. -Settings can be customized by creating a new PrivacyConfig instance or modifying -the global `config` instance. +Change settings on the module-level `config` instance. The scrubbers read that +instance; a separate PrivacyConfig you create is not used. """ from __future__ import annotations diff --git a/openadapt_privacy/scan.py b/openadapt_privacy/scan.py index e6f888b..29821bc 100644 --- a/openadapt_privacy/scan.py +++ b/openadapt_privacy/scan.py @@ -216,7 +216,7 @@ def scan_contents(root: Path, files: list[Path]) -> list[str]: def scan_tree(root: Path, files: list[Path] | None = None) -> list[str]: - """Return the same hit lines the clinic git scanner printed. + """Return one tab-separated line per hit, starting with the rule ID. Raise ``OSError`` if ``root`` is missing, is not a directory, or has a directory that can't be listed. @@ -296,8 +296,8 @@ def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser( prog="openadapt-privacy-scan", description=( - "Scan a git tree for health-data identifiers, remote-desktop hostnames, " - "UNC paths, and recording, screenshot, or database files." + "Scan the files in a directory for health-data identifiers, remote-desktop " + "hostnames, UNC paths, and recording, screenshot, or database files." ), epilog=( "Exit status: 0 clean, 1 a rule fired or a file couldn't be read, " @@ -354,7 +354,7 @@ def main(argv: list[str] | None = None) -> int: return 2 hits = scan_tree(root, files) if hits: - print("PHI / clinic-path scan failed:", file=sys.stderr) + print("PHI scan failed:", file=sys.stderr) for hit in hits: print(hit, file=sys.stderr) return 1 From 56facf4b107d9fffcc4020c010b2fafbaf305e73 Mon Sep 17 00:00:00 2001 From: abrichr Date: Wed, 14 Oct 2026 03:41:51 -0400 Subject: [PATCH 6/6] docs: make the README's card, scan, and setup claims match the code - Limits said a card number that fails the Luhn check is still redacted as . "4111 1111 1111 1112" comes back as "4111 1111 ". The README now gives both cases, and tests/test_readme.py checks them. - The scan section said it checks "a git tree". It checks the files in a directory, and in a git repository the tracked and unignored untracked files, not the history. - gitleaks.toml and phi-patterns.txt carry the text patterns, not the file-type checks, so they aren't "the same rules". - Spell out RPA, say the scan runs without Presidio instead of "needs no other packages", and explain the `uv pip install pip` step. Co-Authored-By: Claude Opus 5.5 --- README.md | 35 ++++++++++++++++++++--------------- tests/test_readme.py | 13 +++++++++++++ 2 files changed, 33 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index b9aa61e..54e37d7 100644 --- a/README.md +++ b/README.md @@ -12,10 +12,10 @@ trees, event payloads, and screenshots. Detection uses [Microsoft Presidio](https://github.com/microsoft/presidio) with a local spaCy model, and scrubbing runs on your machine. -Use it if you record desktop or browser sessions for test automation, RPA, or -training data. It also includes `openadapt-privacy-scan`, a CI check that needs -no other packages and fails when a git tree holds health-data identifiers or -recording files. +Use it if you record desktop or browser sessions for test automation, robotic +process automation (RPA), or training data. It also includes +`openadapt-privacy-scan`, a CI check that runs without Presidio and fails when a +repository holds health-data identifiers or recording files. ## Quick start @@ -33,8 +33,8 @@ print(scrubber.scrub_text("Contact John Smith at john.smith@example.com or 555-1 ``` If the spaCy model or a Presidio package is missing, the scrubber raises -`PrivacyModelUnavailable` or `ImportError` instead of returning text. It does -not fall back to scrubbing less, and it never downloads a model at run time. +`PrivacyModelUnavailable` or `ImportError` instead of returning text. It doesn't +fall back to another model, and it never downloads a model at run time. You need Python 3.10 or later. Screenshot scrubbing also needs the [Tesseract](https://github.com/tesseract-ocr/tesseract) OCR binary on your @@ -145,10 +145,12 @@ class SQLiteRecordingLoader(RecordingLoader): ## Block identifiers in CI -`openadapt-privacy-scan` checks a git tree for health-data identifiers (Ontario -health card numbers, chart IDs, and MRNs), remote-desktop hostnames, UNC -paths, and recording, screenshot, or database files. It uses only the Python -standard library, so the base package is enough: +`openadapt-privacy-scan` checks the files in a directory for health-data +identifiers (Ontario health card numbers, chart IDs, and MRNs), remote-desktop +hostnames, UNC paths, and recording, screenshot, or database files. In a git +repository it checks tracked files and untracked files that aren't ignored; it +doesn't read the history. It uses only the Python standard library, so the base +package is enough: ```bash pip install openadapt-privacy @@ -175,7 +177,8 @@ hits = scan_tree(Path(".")) # for example ["mrn-assigned\tnotes.txt:3"] ``` `openadapt_privacy/gitleaks.toml` and `openadapt_privacy/phi-patterns.txt` -carry the same rules for gitleaks and git-secrets. +carry the same text patterns for gitleaks and git-secrets. They don't include +the file-type checks. ## Configuration @@ -205,9 +208,11 @@ this package. one must be redacted with the right entity type. The data is synthetic, not clinical, so measure recall on your own data before you rely on it. - English only, with the `en_core_web_sm` spaCy model. -- Detection depends on context. A card number that fails the Luhn check is still - redacted, but as `` rather than ``. Check placeholder - names against your data before you route on them. +- Detection depends on context. A card number that fails the Luhn check is not + labeled ``, and other detectors decide how much of it is + redacted. `4532-1234-5678-9012` becomes ``, but + `4111 1111 1111 1112` keeps its first eight digits. If your code acts on + placeholder names, check them against your own data. - Street addresses are found only after a label such as `Address:` or `Mail to`. - In screenshots, text that Tesseract can't read is not redacted. @@ -225,7 +230,7 @@ review steps around it. git clone https://github.com/OpenAdaptAI/openadapt-privacy cd openadapt-privacy uv sync --extra dev --extra presidio -uv pip install pip +uv pip install pip # spacy download installs the model with pip uv run python -m spacy download en_core_web_sm uv run pytest ``` diff --git a/tests/test_readme.py b/tests/test_readme.py index 0029679..54d3f1f 100644 --- a/tests/test_readme.py +++ b/tests/test_readme.py @@ -157,3 +157,16 @@ def test_recording_example_is_what_recording_scrub_returns(scrubber) -> None: scrubbed = recording.scrub(scrubber) assert scrubbed.task_description == "Send email to at " assert f"# {scrubbed.task_description!r}" in README + + +@needs_model +def test_luhn_limit_examples_are_what_the_scrubber_returns(scrubber) -> None: + limits = _section(README, "Limits") + assert "`4532-1234-5678-9012` becomes ``" in limits + assert "`4111 1111 1111 1112` keeps its first eight digits" in limits + + assert scrubber.scrub_text("4532-1234-5678-9012") == "" + partial = scrubber.scrub_text("4111 1111 1111 1112") + assert partial.startswith("4111 1111 ") + assert "1111 1112" not in partial + assert "" not in partial