Privacy + AI

Week 5 · ~10 h

A leaked log line can be a reportable breach, and AI tools are a new way to leak. Privacy has to live in your code, logs and habits. Picture an ordinary morning: a message failed overnight, so someone pastes it into the ticket, commits it as a test fixture, and asks a chat assistant about the stack trace. Nobody meant harm, and the patient's name, birth date, address and MRN now live in three new places that were never designed to hold them.

Patients tell clinicians things they tell no one else. When the record escapes, the harm is concrete: a diagnosis seen by an employer, an address found by an abusive ex-partner. The systems you build decide how many copies of that information exist, who can read them, and whether anyone can tell who did.

This lecture covers what counts as health information, minimum necessary, audit logs and snooping, leak paths, transport security for HL7 v2, breach duties and de-identification. We add an audit log to the week-3 bridge, write canary tests that fail CI when identifiers escape, break a naive MRN pseudonym in half a second, and finish with rules for AI coding tools.

Done when

This week you build a PHI canary test, an audit log and an AGENTS.md. You are done when:

What counts as PHI

PHI is protected (US) or personal (Canada) health information, including in logs, screenshots and test data. In the US the term comes from HIPAA: health information that identifies a person, held by a covered entity (a provider, a health plan, a clearinghouse) or by a business associate working for one. Ontario's PHIPA says personal health information, and the other provinces have their own acts and their own definitions. The details differ; the engineering consequence doesn't. If a piece of data says something about someone's health or care and can be tied back to them, treat it as PHI wherever it ends up.

“Wherever it ends up” is the part engineers miss. The rules don't care whether the data sits in the EHR's database or in /var/log, a CI artifact, a ticket attachment or a screenshot. An ADT message is PHI from first byte to last: name, birth date, MRN, address, even the bed (4W^401^A says this person was an inpatient on that unit that day). A resource id like Patient/1000 says much less, which is why we log ids, not names.

Test data counts too, which is why this course uses only synthetic patients. For privacy testing we go one step further and use canaries: identifiers so obviously fake and so distinctive that if one appears anywhere it shouldn't, a plain substring search will find it. Here is our canary admission. Every identifying field of PID is filled, including the ones people forget:

$ tr '\r' '\n' < canary.hl7
MSH|^~\&|REGADT|GENHOSP|BRIDGE|LAB|20261031093000||ADT^A01^ADT_A01|MSG00501|T|2.5.1
EVN|A01|20261031093000
PID|1||987650^^^GENHOSP^MR||ZZCANARY^TWEETY|ZZMAIDEN|19610704|F|||1 CANARY LANE^^SPRINGFIELD^IL^62701||555-0142|||||A5550142|999-55-0142|D5550142^IL^20300101
PV1|1|I|4W^401^A
$ export PSEUDONYM_KEY=$(openssl rand -hex 32)
$ python3 redact.py allowlist canary.hl7
PID|1||9d37895e0d23fc92^^^GENHOSP^MR||||1961|F||||||||||||
$ python3 redact.py blocklist canary.hl7
PID|1||9d37895e0d23fc92^^^GENHOSP^MR||||1961|F||||||||||||D5550142^IL^20300101

Field by field: PID-3 MRN 987650, PID-5 name, PID-6 mother's maiden name, PID-7 birth date, PID-11 address, PID-13 home phone (a 555-01xx number), PID-18 account number, PID-19 social security number, and PID-20 driver's licence number. The two redact.py lines at the end are this week's first bug; we'll come back to them.

Canada: there is no single law. Each province has its own health-privacy act (PHIPA in Ontario, HIA in Alberta, Law 5 in Quebec), and First Nations data follows the OCAP® principles. Find out which act applies before you design storage or logging.

Minimum necessary

The minimum-necessary rule says: use, disclose and request only the health information needed for the job at hand. In HIPAA it's 45 CFR 164.502(b): “reasonable efforts to limit protected health information to the minimum necessary to accomplish the intended purpose”. It doesn't apply to disclosures to a provider for treatment, because a clinician treating you may need anything in the chart. It does apply to the reports, extracts and feeds that engineers build all day.

For an interface, minimum necessary is a mapping decision. The week-3 bridge receives a full PID segment, address included, and maps only what the downstream system needs: identifier, name, sex and birth date. The address is discarded, so the FHIR server never has it:

$ curl -s localhost:8080/fhir/Patient/1001 | jq -c 'del(.meta)'
{"resourceType":"Patient","id":"1001","identifier":[{"system":"https://genhosp.example.org/mrn","value":"100236"}],"active":true,"name":[{"family":"TREMBLAY","given":["LUC"]}],"gender":"male","birthDate":"1980-02-14"}
$ curl -s 'localhost:8080/fhir/Patient?_elements=gender,birthDate' | jq -c '.entry[].resource | {id, gender, birthDate}'
{"id":"1000","gender":"female","birthDate":"1980-02-14"}
{"id":"1001","gender":"male","birthDate":"1980-02-14"}
{"id":"1002","gender":"female","birthDate":"1980-02-14"}

The second command is a report that needs only sex and birth date, so it asks for only those with FHIR's _elements parameter, and names never travel to the reporting job. Every field you don't copy is a field you never have to protect, purge or explain.

Audit logs and snooping

Access control decides who can open a chart, and in a hospital that's a lot of people: anyone who might treat you tonight must be able to open your chart without asking. So access control can't stop a nurse on another ward from reading a celebrity's chart. Snooping is a violation even with valid access: the question isn't “could they?” but “did they have a reason?”

The control for that is the audit log. HIPAA's Security Rule requires audit controls, mechanisms “that record and examine activity in information systems that contain or use electronic protected health information”. We build an audit log of every patient write: who, what, when, why. Here it is in the week-3 bridge:

def audit(who, action, ref, why):
    """Append who, what, when, why as one JSON line. No PHI."""
    now = datetime.datetime.now(datetime.timezone.utc)
    entry = {"when": now.isoformat(timespec="seconds"),
             "who": who, "action": action, "patient": ref,
             "why": why}
    with open(AUDIT, "a") as f:
        f.write(json.dumps(entry) + "\n")

# in process(), after the write, before the AA:
# an audit failure is an OSError too: no ACK, so it retries
audit("svc-adt-bridge",
      "create" if status == 201 else "update",
      "/".join(location.split("/")[-4:-2]),
      f"{msg.segment('MSH')[9]} {ctl}")

Two choices matter. The record names the patient by resource id, not name or MRN, because the audit log is sensitive too (who read which oncology charts says a lot). And the audit write sits inside the same try as the FHIR write: if we can't record it, we don't send AA, and the sender retries. The write is idempotent, so retrying is safe; an unaudited write is not.

Download the week-5 bridge.py, the read tool chart.py, and the samples from week 3 (adt.hl7, adt-on.hl7, adt-amp.hl7). With the bridge running (we start it in the canary section below), we send two more admissions. The bridge's log shows every write so far, including two copies of Jane Doe's admission that went through the network tunnels in the transport section:

$ for f in adt-on.hl7 adt-amp.hl7; do mllp_send --loose -f $f -p 2575 localhost | tr '\r' '\n' | grep MSA; done
MSA|AA|MSG00006
MSA|AA|MSG00005
$ cat bridge.log
listening for MLLP on port 2575
MSG00001 AA after HTTP 201 http://localhost:8080/fhir/Patient/1000/_history/1
MSG00001 AA after HTTP 200 http://localhost:8080/fhir/Patient/1000/_history/1
MSG00006 AA after HTTP 201 http://localhost:8080/fhir/Patient/1001/_history/1
MSG00005 AA after HTTP 201 http://localhost:8080/fhir/Patient/1002/_history/1

Now some people read charts. chart.py stands in for an EHR screen: it fetches a patient as a named user, records why, and audits the read before it shows anything:

$ python3 chart.py dr.lee Patient/1000 treatment
Patient/1000 DOE JANE 1980-02-14
$ python3 chart.py nurse.ng Patient/1000 treatment
Patient/1000 DOE JANE 1980-02-14
$ python3 chart.py dr.lee Patient/1001 treatment
Patient/1001 TREMBLAY LUC 1980-02-14
$ python3 chart.py it.sam Patient/1001 testing
Patient/1001 TREMBLAY LUC 1980-02-14
$ python3 chart.py it.sam Patient/1002 testing
Patient/1002 DOE&SMITH JANE 1980-02-14
$ python3 chart.py it.sam Patient/1000 testing
Patient/1000 DOE JANE 1980-02-14
$ wc -l audit.jsonl
10 audit.jsonl

The audit log can now answer the question from the “Done when” list. jq handles JSON lines directly, one object per line:

$ head -n 1 audit.jsonl | jq .
{
  "when": "2026-10-31T22:13:09+00:00",
  "who": "svc-adt-bridge",
  "action": "create",
  "patient": "Patient/1000",
  "why": "ADT^A01^ADT_A01 MSG00001"
}
$ jq -r 'select(.patient == "Patient/1001") | [.when, .who, .action, .why] | @tsv' audit.jsonl
2026-10-31T22:13:09+00:00	svc-adt-bridge	create	ADT^A01^ADT_A01 MSG00006
2026-10-31T22:13:10+00:00	dr.lee	read	treatment
2026-10-31T22:13:10+00:00	it.sam	read	testing
$ jq -s -r 'map(select(.action == "read")) | group_by(.who)[] | "\(length) \(.[0].who)"' audit.jsonl
2 dr.lee
3 it.sam
1 nurse.ng
$ jq -r --arg u it.sam 'select(.who == $u) | "\(.patient) \(.why)"' audit.jsonl
Patient/1001 testing
Patient/1002 testing
Patient/1000 testing

The first query is what a privacy officer runs when Luc Tremblay asks who looked at his record: the bridge created it, Dr. Lee read it for treatment, and it.sam read it for “testing”. The others show the pattern: someone in IT with valid production access reading three real charts. That's what snooping often looks like in a log. The audit log doesn't prevent the read; it makes it findable, and people behave differently when they know reads are reviewed.

In production, ship audit records off the box as they're written, to a store the application can append to but not edit, and audit reads of the audit log too. We didn't build that here; the JSON-lines file is the shape, not the storage.

Leak paths

PHI escapes through six everyday routes: logs, git history, tickets, screenshots, crash dumps and AI prompts. None of them is a database, so none of them is protected like one, and each is copied, retained and shared by default. Here is how each one happens and what stops it:

Leak pathHow PHI gets thereWhat stops it
LogsA debug line prints the message; an exception message includes a field value; a server logs query stringsLog control IDs and resource ids only; canary test in CI; treat every log store as PHI
Git historyA sample message, export or log committed “just to reproduce the bug”Synthetic fixtures only; review diffs; report, then purge history
TicketsThe failing message or a log excerpt pasted into the ticket or chatReference the control ID or resource id; attach synthetic repros
ScreenshotsA chart, a worklist or an integration engine's message browser in the corner of a pictureSynthetic test environment for demos; crop or redact before sharing
Crash dumpsCore dumps, heap dumps and error-reporting services capture memory and local variables, which hold whole messagesDumps stay inside the trust boundary; scrub or disable variable capture
AI promptsA log, ticket or screenshot pasted into a chat to ask for helpApproved tools, synthetic data, an AGENTS.md the tools read

Structured logs

Log the message's control ID (MSH-10) and the FHIR resource id, never a name or an MRN. The bridge log above does exactly that. It has a control ID, an ACK code and a resource URL per line: enough to trace a message end to end, through the FHIR server where access is controlled and audited, and nothing about the patient.

The PHI canary test

“Never log PHI” is a policy, and policies decay one debug line at a time, so we make it a test. A PHI canary test sends messages full of fake identifiers through the code and fails CI if any of them shows up in a log. Ours drives the bridge's process() with the canary message along every path (accepted, missing MRN, bad birth date, unknown authority, production ID, FHIR down) and searches everything logged at DEBUG, plus the audit file:

GOOD = open("canary.hl7", newline="").read()
CASES = {  # one message per path through process()
    "accepted": GOOD,
    "no-mrn": GOOD.replace("987650^^^GENHOSP^MR", ""),
    "bad-dob": GOOD.replace("19610704", "1961070X"),
    "unknown-authority": GOOD.replace("GENHOSP^MR", "OTHER^MR"),
    "production": GOOD.replace("|T|2.5.1", "|P|2.5.1"),
    "fhir-down": GOOD,
}


@pytest.mark.parametrize("case", CASES)
def test_no_canary_in_logs(case, caplog, monkeypatch, tmp_path):
    caplog.set_level(logging.DEBUG)  # incidents turn debug on
    audit_file = tmp_path / "audit.jsonl"
    monkeypatch.setattr(bridge, "AUDIT", audit_file)
    if case == "fhir-down":  # nothing listens on port 9
        monkeypatch.setattr(bridge, "FHIR", "http://localhost:9/fhir")
    else:
        monkeypatch.setattr(bridge, "upsert", lambda p: (
            201, "http://fhir.example.org/fhir/Patient/1/_history/1"))
    bridge.process(hl7.parse(CASES[case]))
    logged = caplog.text
    if audit_file.exists():  # the audit log is a log too
        logged += audit_file.read_text()
    leaked = [c for c in CANARIES if c in logged]
    if leaked:
        pytest.fail(f"{len(leaked)} canaries in logs, first {leaked[0]}")

The FHIR write is replaced by a stub, so the test needs no server and runs in any CI job; the “FHIR down” case points the bridge at a port where nothing listens, so the real exception text goes through the real logging code. The list of canaries and pytest.ini are shared with the redaction tests below. Download test_canary_logs.py and canary.hl7.

Start the lab first: the FHIR server, then the bridge in the background with its log in a file:

$ docker run -d --name hapi -p 8080:8080 hapiproject/hapi:latest
a6c1614f4850014a564374435c90c7aba5693c37936a8d45f61973beb65210cd
$ timeout 120 bash -c 'until curl -sf -o /dev/null localhost:8080/fhir/metadata; do sleep 5; done'
$ python3 bridge.py > bridge.log 2>&1 &
$ sleep 1; cat bridge.log
listening for MLLP on port 2575

Now the test, first against the bridge as it is, then after a well-meant patch that someone might add at 2 a.m. while chasing an incident:

$ pytest test_canary_logs.py
......                                                                   [100%]
6 passed in 0.04s
$ cat debug.patch
--- bridge.py
+++ bridge.py
@@ -108,6 +108,7 @@
 
 def process(msg):
     ctl = field(msg, "MSH.F10")
+    log.debug("%s received %r", ctl, str(msg))  # for INC-1234
     try:
         status, location = upsert(to_patient(msg))
         # an audit failure is an OSError too: no ACK, so it retries
$ patch bridge.py debug.patch
patching file bridge.py
$ pytest --tb=no -rf test_canary_logs.py
FFFFFF                                                                   [100%]
=========================== short test summary info ============================
FAILED test_canary_logs.py::test_no_canary_in_logs[accepted] - Failed: 10 canaries in logs, first 987650
FAILED test_canary_logs.py::test_no_canary_in_logs[no-mrn] - Failed: 9 canaries in logs, first ZZCANARY
FAILED test_canary_logs.py::test_no_canary_in_logs[bad-dob] - Failed: 9 canaries in logs, first 987650
FAILED test_canary_logs.py::test_no_canary_in_logs[unknown-authority] - Failed: 10 canaries in logs, first 987650
FAILED test_canary_logs.py::test_no_canary_in_logs[production] - Failed: 10 canaries in logs, first 987650
FAILED test_canary_logs.py::test_no_canary_in_logs[fhir-down] - Failed: 10 canaries in logs, first 987650
6 failed in 0.04s
$ patch -R bridge.py debug.patch
patching file bridge.py

Six paths, six passes; one innocent log.debug, six failures. The failure message itself prints a canary into the CI log, which is fine because it's fake, and is why canaries must never be real data. The test runs at DEBUG because someone will turn debug on during an incident, exactly when logs get copied into tickets.

Logs you don't write

Our bridge passes its canary test. Is the system clean? Ask every component the data passes through. We grep the bridge's log and the audit log for names and MRNs, and then the FHIR server's log:

$ grep -c -E 'DOE|TREMBLAY|10023[456]' bridge.log audit.jsonl
bridge.log:0
audit.jsonl:0
$ docker logs hapi 2>&1 | grep -c 'mrn%7C100234'
2
$ docker logs hapi 2>&1 | grep -o 'Params\[[^]]*100234\]' | head -n 1
Params[?identifier=https%3A%2F%2Fgenhosp.example.org%2Fmrn%7C100234]

Nothing in the files we write, but the FHIR server's access log holds the MRN of every patient we upserted: the conditional PUT puts the identifier in the query string, and HAPI logs every request's parameters, as many proxies and gateways do. Treat those logs as PHI (restricted, short retention, never pasted) or stop them logging parameters, and add them to what your canary test checks.

Tested: HAPI FHIR 8.12.0's default access log (fhirtest.access) recorded Params[?identifier=…mrn%7C100234] for each conditional PUT. Our bridge's own log and the audit log had no names or MRNs.

Git history

The fixture problem from the introduction, as it actually happens. A developer commits the failing message to reproduce a bug, a reviewer spots it, and the next commit deletes it:

$ git init -q incident && cd incident
$ cp ../adt.hl7 inc-1234-repro.hl7
$ git add . && git commit -qm 'INC-1234: add failing message'
$ git rm -q inc-1234-repro.hl7 && git commit -qm 'Remove PHI'
$ ls; git grep -c JANE
$ git log --oneline
cd6549b Remove PHI
691fc11 INC-1234: add failing message
$ git log -S 'DOE^JANE' --oneline
cd6549b Remove PHI
691fc11 INC-1234: add failing message
$ git show HEAD~1:inc-1234-repro.hl7 | tr '\r' '\n' | grep PID
PID|1||100234^^^GENHOSP^MR||DOE^JANE||19800214|F|||12 MAIN ST^^SPRINGFIELD^IL^62701

The file is gone from the working tree, and git grep on the current commit finds nothing. But git log -S (the “pickaxe”) finds both commits that touched the string, and git show prints the patient from history. Anyone who cloned or forked in between has a copy, and so does every CI cache and backup of the repo.

The order matters: report first, then purge. Rewriting history (with git filter-repo, plus the host's own cleanup, as in GitHub's guide) destroys the evidence of what was exposed, for how long and to whom, which the privacy office needs to judge whether it's a reportable breach. We didn't run a purge here.

MLLP on the wire

MLLP sends everything as plain text, so it must run inside TLS or a VPN. In week 3 we watched the MLLP bytes go by; this time we look at what an eavesdropper on the network sees. socat -v sits between the sender and the bridge and writes everything that passes to a file:

$ socat -v TCP-LISTEN:2576,reuseaddr TCP:localhost:2575 2> wire.txt &
$ sleep 0.5; mllp_send --loose -f adt.hl7 -p 2576 localhost > /dev/null
$ grep -a -o 'PID|[^\]*' wire.txt
PID|1||100234^^^GENHOSP^MR||DOE^JANE||19800214|F|||12 MAIN ST^^SPRINGFIELD^IL^62701

The whole PID segment, name, MRN, birth date and address, in clear text, for anyone who can see the network: a compromised switch, a mirrored port, a misconfigured cloud network. HIPAA's Security Rule lists transmission security among its technical safeguards; for v2 that means a VPN between sites or TLS around the connection.

Now the same message through a TLS tunnel. One socat on the sending side wraps the connection in TLS, one on the receiving side unwraps it, and a third in the middle plays the network and dumps the bytes in hex:

$ openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj /CN=localhost -addext subjectAltName=DNS:localhost -keyout lab.key -out lab.crt 2> /dev/null
$ cat lab.key lab.crt > lab.pem
$ socat OPENSSL-LISTEN:2577,reuseaddr,cert=lab.pem,verify=0 TCP:localhost:2575 &  # receiving site
$ socat -x TCP-LISTEN:2578,reuseaddr TCP:localhost:2577 2> tls.txt &  # the network
$ socat TCP-LISTEN:2579,reuseaddr OPENSSL:localhost:2578,cafile=lab.crt 2> /dev/null &  # sending site
$ sleep 0.5; mllp_send --loose -f adt.hl7 -p 2579 localhost | tr '\r' '\n' | grep MSA
MSA|AA|MSG00001
$ grep -a -c JANE tls.txt
0
$ sed -n 2p tls.txt | cut -c1-48
 16 03 01 01 99 01 00 01 95 03 03 f1 47 6c 3d 1d

The ACK came back, and the bytes in the middle contain no JANE: the first record starts 16 03 01, a TLS handshake. In production use the engine's built-in TLS, stunnel or a site-to-site VPN, and require a client certificate too (our receiver accepts anyone, verify=0), so only the known sender can connect. Write the choice in the interface spec.

Redaction: allowlist, not blocklist

Sometimes data must leave the hospital in reduced form: to a vendor debugging an interface, to an analytics team, to a test environment. We redact with an allowlist: keep only the set ID, a pseudonym for the MRN, the birth year and the sex. Here is the first version, using python-hl7:

KEEP = {1, 3, 7, 8}  # set ID, MRN, birth date, sex
for n in range(1, len(msg.segment("PID"))):
    if n not in KEEP:
        msg[f"PID.F{n}"] = ""
mrn = str(msg["PID.F3.R1.C1"])
msg["PID.F3.R1.C1"] = pseudonym(mrn)  # salted SHA-256
msg["PID.F7"] = str(msg["PID.F7"])[:4]  # birth year

It names what to keep and blanks everything else. The tempting alternative is a blocklist naming what to remove. Both are in redact.py, and the first commands on this page already showed the difference: the blocklist output still ends with D5550142^IL^20300101, the driver's licence number in PID-20. test_redact.py runs every canary message through both:

CANARIES = ["987650", "ZZCANARY", "TWEETY", "ZZMAIDEN", "19610704",
            "CANARY LANE", "555-0142", "A5550142", "999-55-0142",
            "D5550142", "9990001425"]


@pytest.mark.parametrize("path", sorted(glob.glob("canary*.hl7")))
@pytest.mark.parametrize("how", ["allowlist", "blocklist"])
def test_no_canary_survives(how, path, monkeypatch):
    monkeypatch.setenv("PSEUDONYM_KEY", "test-key-not-a-secret")
    msg = hl7.parse(open(path, newline="").read())
    out = str(getattr(redact, how)(msg))
    leaked = [c for c in CANARIES if c in out]
    if leaked:
        pytest.fail(f"{path}: {leaked} survived {how}")
$ pytest --tb=no -rf test_redact.py
.F                                                                       [100%]
=========================== short test summary info ============================
FAILED test_redact.py::test_no_canary_survives[blocklist-canary.hl7] - Failed: canary.hl7: ['D5550142'] survived blocklist
1 failed, 1 passed in 0.01s

A blocklist misses every field you didn't think of. PID has dozens of fields in 2.5.1, senders put things in unexpected places, and Z-segments can carry anything. An allowlist fails safe: a field you forgot is a field you dropped, and someone will ask for it, which is a much better failure than a breach.

Tested: an allowlist redaction passed; a blocklist version leaked a driver's licence number (PID-20) and the canary caught it.

Repeating fields

Our allowlist works field by field, and keeps PID-3 whole. In week 3 we met an Ontario feed whose PID-3 repeats: the MRN, then the provincial health card number, typed JHN. Add a canary like that and run the tests again:

$ sed 's/GENHOSP^MR/GENHOSP^MR~9990001425^^^ON^JHN/' canary.hl7 > canary-on.hl7
$ tr '\r' '\n' < canary-on.hl7 | grep PID | cut -d'|' -f1-4
PID|1||987650^^^GENHOSP^MR~9990001425^^^ON^JHN
$ pytest --tb=no -rf test_redact.py
F.FF                                                                     [100%]
=========================== short test summary info ============================
FAILED test_redact.py::test_no_canary_survives[allowlist-canary-on.hl7] - Failed: canary-on.hl7: ['9990001425'] survived allowlist
FAILED test_redact.py::test_no_canary_survives[blocklist-canary-on.hl7] - Failed: canary-on.hl7: ['D5550142', '9990001425'] survived blocklist
FAILED test_redact.py::test_no_canary_survives[blocklist-canary.hl7] - Failed: canary.hl7: ['D5550142'] survived blocklist
3 failed, 1 passed in 0.01s

The allowlist leaked the health card number: it pseudonymized the first repetition and kept the second untouched. An allowlist at field level is only as good as your idea of what a field contains. The fix keeps only the first repetition (repeats.patch):

$ cat repeats.patch
--- redact.py
+++ redact.py
@@ -23,6 +23,7 @@
             msg[f"PID.F{n}"] = ""
     mrn = str(msg["PID.F3.R1.C1"])
     msg["PID.F3.R1.C1"] = pseudonym(mrn)  # salted SHA-256
+    del msg.segment("PID")[3][1:]  # first repetition only
     msg["PID.F7"] = str(msg["PID.F7"])[:4]  # birth year
     return msg
 
$ patch redact.py repeats.patch
patching file redact.py
$ pytest --tb=no -rf test_redact.py
..FF                                                                     [100%]
=========================== short test summary info ============================
FAILED test_redact.py::test_no_canary_survives[blocklist-canary-on.hl7] - Failed: canary-on.hl7: ['D5550142', '9990001425'] survived blocklist
FAILED test_redact.py::test_no_canary_survives[blocklist-canary.hl7] - Failed: canary.hl7: ['D5550142'] survived blocklist
2 failed, 2 passed in 0.01s

The allowlist passes both canaries again; the blocklist still leaks, as it should, because nothing in it changed. The lesson is the one the canary is for: you don't find these by reading code, you find them by putting a distinctive fake value into every place a real one could be and checking that it never comes out.

Tested: that allowlist logic kept a second PID-3 repetition (an Ontario health card number) and the canary caught it; deleting repetitions after the first fixed it.

Pseudonyms need a secret

The redacted message keeps a pseudonym in place of the MRN, so that records from the same patient can still be linked. The obvious way to make one is to hash the MRN. That fails: without a secret, anyone can hash every possible MRN and look for a match. MRNs at our hospital have six digits, so there are a million candidates, and crack.py tries them all:

$ printf 100234 | sha256sum
4bfcc4d35d88fbc17a18388d85ad2c6fc407db7c4214b53c306af0f366529b06  -
$ time python3 crack.py 4bfcc4d35d88fbc1
MRN 100234

real	0m0.056s
user	0m0.053s
sys	0m0.003s
$ export PSEUDONYM_KEY=$(openssl rand -hex 32)
$ p=$(python3 -c 'import redact; print(redact.pseudonym("100234"))')
$ echo $p
d3fdb263de229958
$ time python3 crack.py $p
no match in 1,000,000 candidates

real	0m0.486s
user	0m0.482s
sys	0m0.004s

The unsalted SHA-256 of MRN 100234 fell in 57 milliseconds (the search starts at 000000), and the whole space took under half a second. Health card numbers, phone numbers and birth dates are small spaces too. The fix is a keyed hash, HMAC (RFC 2104), with a random 256-bit key; without the key the same search finds nothing:

def pseudonym(mrn):
    """Keyed hash (HMAC-SHA-256): same MRN, same pseudonym."""
    key = os.environ["PSEUDONYM_KEY"].encode()  # never in git
    return hmac.new(key, mrn.encode(), hashlib.sha256).hexdigest()[:16]

The same MRN gives the same pseudonym under the same key, so linking still works. But anyone holding the key can reverse every pseudonym just as fast, so it belongs in a secrets manager, never in the repo, a ticket or a prompt. People often call this a “salted” hash. An ordinary salt is not secret; here you need a secret key, and HMAC is the standard way to key a hash.

De-identification

Redacted or pseudonymized data is still PHI, as long as someone (you, holding the key) can link it back. De-identified data is no longer PHI under HIPAA, and 45 CFR 164.514 gives two ways to get there.

Safe Harbor means removing all 18 listed identifiers, of the individual and of relatives, employers or household members, and having no actual knowledge that what's left could identify someone. The 18 are:

  1. names
  2. geographic subdivisions smaller than a state (street, city, county, ZIP code, with an exception for the first three ZIP digits of areas over 20,000 people)
  3. all elements of dates except the year, and all ages over 89
  4. telephone numbers
  5. fax numbers
  6. email addresses
  7. social security numbers
  8. medical record numbers
  9. health plan beneficiary numbers
  10. account numbers
  11. certificate and licence numbers
  12. vehicle identifiers, including licence plates
  13. device identifiers and serial numbers
  14. URLs
  15. IP addresses
  16. biometric identifiers, such as finger and voice prints
  17. full-face photographs and comparable images
  18. any other unique identifying number, characteristic or code

Compare our allowlist output. Birth year is allowed (except for ages over 89), and sex is. The pseudonym is the problem: §164.514(c) allows a re-identification code only if it is “not derived from or related to information about the individual”, and ours is derived from the MRN. Read literally, our feed is pseudonymized PHI, not Safe Harbor data; a random code with a lookup table would qualify. Ask your privacy office, not the code reviewer.

Expert determination is the other route: a qualified expert shows, with documented statistical methods, that the re-identification risk is very small. HHS's de-identification guidance explains both routes. Canadian acts use their own definitions.

Free text is hardest: notes, NTE comments and text OBX results have no fields to blank. “Seen with her daughter Maria, who works at the pharmacy on King St” holds a relative, an employer and a place. Drop free text from extracts unless the purpose truly needs it.

Breach duties

What do you do the moment PHI shows up in a log? Stop copying it (not into the ticket that reports it either), tell your privacy or security contact where it is and since when, preserve what they need, then fix and clean up. Whether it's a breach is their call, under deadlines, so the clock starts when you notice.

Under HIPAA's breach notification rule, a covered entity that discovers a breach of unsecured PHI must tell:

Who is toldWhen
Each affected individualWithout unreasonable delay, and no later than 60 calendar days after discovery
HHS, when 500 or more people are affectedAt the same time as the individuals
Prominent media, when more than 500 residents of one state are affectedAt the same time as the individuals
HHS, for smaller breachesLogged, then reported within 60 days after the end of the calendar year

A breach counts as discovered on the first day it is known, or would have been known with reasonable diligence, which is why “I noticed it on Friday but wanted to check first” is a problem. Ontario's PHIPA requires notifying the affected patients, and in some circumstances the Information and Privacy Commissioner as well; other provinces have their own rules.

Regulation moves, too. HIPAA's Security Rule overhaul (proposed 2025) isn't final: the proposed rule was published in January 2025. Build to the current rule, and read what changed before you quote either.

AI tools

AI prompts are the newest leak path: whatever you paste is sent to a service, may be stored there, and stays in your chat history. Pasting a failing message into an unapproved assistant is a disclosure. “Approved” means your organization has a contract covering health data (in the US, usually a business associate agreement) and has configured the tool; your personal account is not approved.

Coding agents add a twist: they read your repo, run your tests and see your logs on their own. So write your PHI rules where the agent will read them. Many agents look for an AGENTS.md file at the root of the repository; here is ours:

# Rules for AI coding tools in this repo

This repo moves patient data. These rules apply to every AI tool
and every person using one.

## Data
- Use approved tools only (see the team wiki). No personal accounts.
- Synthetic data only: Synthea output, the canary messages in this
  repo, or hand-made samples with example.org identifier systems.
- Never paste logs, tickets, screenshots, crash dumps or database
  rows into a prompt, even "just one line". Describe the problem.
- Do not open or read files under `data/`, `exports/` or `*.log`.

## Code
- Never log message bodies, names, birth dates, MRNs, health card
  numbers or addresses. Log MSH-10 control IDs and resource ids.
- Redaction is allowlist-only: name the fields you keep.
- Pseudonyms use HMAC with `PSEUDONYM_KEY` from the environment.
  Never hard-code the key, print it, or commit it.
- Any change to logging, redaction or error handling must keep
  `pytest test_redact.py test_canary_logs.py` passing.

## If you see PHI
Stop. Do not copy it anywhere, including into the prompt.
Tell the privacy contact, then follow the incident runbook.

It says what data the tool may see, which files it must not open, what code must never log, and which tests guard that. It doesn't replace the controls: a model can ignore an instruction file, which is why the canary tests run in CI anyway.

AI this week: approved tools and synthetic data only; never paste logs, tickets or screenshots.

Exercises

  1. Why does a blocklist fail where an allowlist works? Add a ZPI segment with a canary value to canary.hl7 and run both redactors. What should a redactor do with segments it doesn't know?
  2. Why must an MRN pseudonym use a secret salt? Change crack.py to attack HMAC pseudonyms when the key is known, and time it. What does that tell you about where the key may live?
  3. What do you do the moment PHI shows up in a log? Write the first five steps as a runbook for your team, including who you tell and what you must not copy.
  4. Make the canary test fail in three different ways besides debug.patch: an exception message that includes a field value, a log line that prints the FHIR Patient, and an f-string in the Reject reason. Did the test catch all three?
  5. Extend the canary test to check the FHIR server's log as well (start HAPI in CI, send the canary, grep docker logs). Then make it pass, either by changing what the server logs or by changing how the bridge finds the patient. Which did you choose, and why?
  6. Add reads to the audit trail properly: give chart.py a required reason from a fixed list, and write a jq query that lists every read by a user who never read that patient for treatment before. What would a real system compare reads against?
  7. Our allowlist assumes the MRN is the first repetition of PID-3. Make it pick the repetition whose type is MR and whose assigning authority is GENHOSP, and add a canary message where the health card number comes first.
  8. Write ten short synthetic clinical notes in the style of a discharge summary, then try to de-identify them with regular expressions for names, dates and places. Count what you missed by reading the result. What does that say about free text?
  9. Canada track: the Ontario sample carries a health card number. Look up whether your province's act treats the health card number specially, and write the rule your interface spec should state about logging and storing it.

For more drill on this week's skills, work through the week 5 practice problems.

Read

Tested with

Every command on this page was run on 31 Oct 2026 against the course lab: a local HAPI FHIR 8.12.0 server in Docker, python-hl7 0.4.5, pytest 9.2.0, socat 1.8.0.0, OpenSSL 3.0.13, git 2.43.0 and jq 1.7. The outputs are copied from those runs. Yours will differ in timestamps, keys, hashes and server ids. All patient data on this page is made up.


Course content © 2026 HeyItWorked. All rights reserved.

Site design adapted from The Missing Semester of Your CS Education under CC BY-NC-SA 4.0. See copyright and license.