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..54e37d7 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, 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. -[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 doesn't +fall back to another model, 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,184 @@ 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 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 +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 text patterns for gitleaks and git-secrets. They don't include +the file-type checks. -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 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. +- `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 # spacy download installs the model with 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 01a0f8d..d9ef8b6 100644 Binary files a/assets/screenshot_scrubbed.png and b/assets/screenshot_scrubbed.png differ 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/openadapt_privacy/config.py b/openadapt_privacy/config.py index c56a2ea..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 @@ -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/providers/presidio.py b/openadapt_privacy/providers/presidio.py index afb1dcf..b0e4552 100644 --- a/openadapt_privacy/providers/presidio.py +++ b/openadapt_privacy/providers/presidio.py @@ -50,6 +50,36 @@ } ) +# 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. +# 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", + "date of birth", + "dob", + "e-mail", + "email", + "email address", + "health card", + "ip address", + "member id", + "mrn", + "name", + "patient id", + "phone", + "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 +162,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 +191,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 +416,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/openadapt_privacy/scan.py b/openadapt_privacy/scan.py index f961b10..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. @@ -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 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, " + "2 the scan couldn't run." + ), + ) parser.add_argument( "--self-test", action="store_true", @@ -344,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 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_phi_recall.py b/tests/test_phi_recall.py index 53892db..8668719 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,66 @@ 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] + + +@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) diff --git a/tests/test_readme.py b/tests/test_readme.py new file mode 100644 index 0000000..54d3f1f --- /dev/null +++ b/tests/test_readme.py @@ -0,0 +1,172 @@ +"""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 + + +@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 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