phiguard-audit 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Arpita Haque
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.4
2
+ Name: phiguard-audit
3
+ Version: 0.1.0
4
+ Summary: HIPAA-aligned database security and audit toolkit: RBAC, break-glass access, hash-chained audit log, Safe Harbor de-identification and anomaly detection.
5
+ Author-email: Arpita Haque <arpitakaiser@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/arpitahaque/phi-guard
8
+ Project-URL: Repository, https://github.com/arpitahaque/phi-guard
9
+ Project-URL: Issues, https://github.com/arpitahaque/phi-guard/issues
10
+ Project-URL: Changelog, https://github.com/arpitahaque/phi-guard/blob/main/CHANGELOG.md
11
+ Keywords: hipaa,database-security,audit-logging,de-identification,healthcare,rbac
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Security
14
+ Classifier: Topic :: Database
15
+ Classifier: Intended Audience :: Healthcare Industry
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest>=7; extra == "test"
21
+ Dynamic: license-file
22
+
23
+ # PHI-Guard
24
+
25
+ [![tests](https://github.com/arpitahaque/phi-guard/actions/workflows/tests.yml/badge.svg)](https://github.com/arpitahaque/phi-guard/actions/workflows/tests.yml)
26
+ [![PyPI](https://img.shields.io/pypi/v/phiguard-audit)](https://pypi.org/project/phiguard-audit/)
27
+ ![Python](https://img.shields.io/badge/python-3.10%2B-blue)
28
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/arpitahaque/phi-guard/blob/main/LICENSE)
29
+
30
+ **A HIPAA-aligned database security and auditing toolkit, demonstrated on a synthetic mental-health clinic database.**
31
+
32
+ Healthcare data breaches are often caused by insiders who can see more than they need or who browse records they have no reason to open. PHI-Guard shows how a small clinic database can enforce the HIPAA "minimum necessary" standard, keep a tamper-evident record of every access, flag suspicious behavior for review, and release research data that meets the HIPAA Safe Harbor de-identification standard.
33
+
34
+ > All data in this project is **synthetic**. Do not load real patient information into it.
35
+
36
+ ## What it does
37
+
38
+ | Feature | HIPAA reference | How |
39
+ |---|---|---|
40
+ | Role-based access control | 45 CFR 164.312(a)(1), 164.502(b) | Each role (clinician, billing, front desk, admin, researcher) can read only the columns it needs. Clinicians can open only their own patients' notes unless they use logged "break-the-glass" emergency access. |
41
+ | Tamper-evident audit log | 164.312(b), 164.312(c)(1) | Every read, write and denied attempt is appended to an audit table. Triggers block edits and deletes, and each row stores a SHA-256 hash of the previous row, so any change to history breaks the chain. |
42
+ | Access-anomaly detection | 164.308(a)(1)(ii)(D) | Rules flag bulk access (20+ patients/day), after-hours PHI reads, break-the-glass use and repeated denied attempts. |
43
+ | Safe Harbor de-identification | 164.514(b)(2) | Research export replaces patient IDs with keyed pseudonyms, reduces dates to year, groups ages 90+, truncates ZIP codes to 3 digits (or `000` for small areas), and scrubs names, SSNs, phones, emails, MRNs, dates, URLs and IPs from free-text notes. A verification pass checks for residual identifiers. |
44
+ | Compliance report | Security Rule mapping | Generates a Markdown report summarizing audit integrity, flagged events and de-identification results. |
45
+
46
+ ## Quick start
47
+
48
+ Requires Python 3.10+. No third-party packages are needed to run it (pytest only for tests).
49
+
50
+ Install from PyPI:
51
+
52
+ ```bash
53
+ pip install phiguard-audit
54
+ phiguard demo
55
+ ```
56
+
57
+ Or run from source:
58
+
59
+ ```bash
60
+ git clone https://github.com/arpitahaque/phi-guard.git
61
+ cd phi-guard
62
+ pip install -e . # optional: adds the `phiguard` command
63
+ python -m phiguard demo # build synthetic clinic, simulate a week, print report
64
+ python -m phiguard verify # check audit-log integrity
65
+ python -m phiguard anomalies # list flagged access events
66
+ python -m phiguard export # write de-identified research_export.csv
67
+ ```
68
+
69
+ The demo simulates one week of normal clinic activity plus three planted insider-threat scenarios:
70
+
71
+ 1. A billing user opens 25+ patient records late one evening (bulk + after-hours access).
72
+ 2. A clinician is denied three times on a chart that is not theirs, then uses break-the-glass.
73
+ 3. A researcher tries to read identified clinical notes directly.
74
+
75
+ All three are caught. See [`docs/sample_compliance_report.md`](https://github.com/arpitahaque/phi-guard/blob/main/docs/sample_compliance_report.md) for the output.
76
+
77
+ ## Run the tests
78
+
79
+ ```bash
80
+ pip install -e ".[test]"
81
+ python -m pytest -q
82
+ ```
83
+
84
+ GitHub Actions runs the tests and the end-to-end demo on Python 3.10 to 3.13 for every push.
85
+
86
+ Tests cover column-level access, denial logging, the clinician care-relationship rule, append-only enforcement, tamper detection on the hash chain, Safe Harbor helpers, residual-identifier checks and detection of each planted threat.
87
+
88
+ ## Project structure
89
+
90
+ ```
91
+ phiguard/
92
+ schema.py tables + append-only audit triggers
93
+ access.py role policy and audited access layer
94
+ audit.py hash-chained audit logging and verification
95
+ anomaly.py insider-threat detection rules
96
+ deidentify.py HIPAA Safe Harbor export and text scrubbing
97
+ synthetic.py synthetic clinic data and simulated activity
98
+ report.py compliance report mapped to the Security Rule
99
+ cli.py command-line interface
100
+ tests/ pytest suite
101
+ docs/ sample report
102
+ ```
103
+
104
+ ## Limitations and future work
105
+
106
+ - The rule-based text scrubber catches structured identifiers and known names but is not a substitute for a validated clinical de-identification model; a next step is comparing it with NLP-based PHI detection.
107
+ - The restricted 3-digit ZIP list is an illustrative subset; production use should load the current U.S. Census list.
108
+ - Anomaly thresholds are fixed; future work could learn per-role baselines from historical audit data.
109
+ - Hash-chaining detects tampering inside the database; anchoring periodic chain hashes to external storage would also protect against full-table replacement.
110
+
111
+ ## Author
112
+
113
+ Arpita Haque, B.S. Computer Information Technology (Cybersecurity minor), Minnesota State University Moorhead.
114
+ Related prior work: SecurePsych AI, a privacy-focused on-premise AI assistant for mental-health documentation.
115
+
116
+ ## Contributing and security
117
+
118
+ See [CONTRIBUTING.md](https://github.com/arpitahaque/phi-guard/blob/main/CONTRIBUTING.md) and [SECURITY.md](https://github.com/arpitahaque/phi-guard/blob/main/SECURITY.md). Release notes are in [CHANGELOG.md](https://github.com/arpitahaque/phi-guard/blob/main/CHANGELOG.md).
119
+
120
+ ## License
121
+
122
+ [MIT](https://github.com/arpitahaque/phi-guard/blob/main/LICENSE)
@@ -0,0 +1,100 @@
1
+ # PHI-Guard
2
+
3
+ [![tests](https://github.com/arpitahaque/phi-guard/actions/workflows/tests.yml/badge.svg)](https://github.com/arpitahaque/phi-guard/actions/workflows/tests.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/phiguard-audit)](https://pypi.org/project/phiguard-audit/)
5
+ ![Python](https://img.shields.io/badge/python-3.10%2B-blue)
6
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/arpitahaque/phi-guard/blob/main/LICENSE)
7
+
8
+ **A HIPAA-aligned database security and auditing toolkit, demonstrated on a synthetic mental-health clinic database.**
9
+
10
+ Healthcare data breaches are often caused by insiders who can see more than they need or who browse records they have no reason to open. PHI-Guard shows how a small clinic database can enforce the HIPAA "minimum necessary" standard, keep a tamper-evident record of every access, flag suspicious behavior for review, and release research data that meets the HIPAA Safe Harbor de-identification standard.
11
+
12
+ > All data in this project is **synthetic**. Do not load real patient information into it.
13
+
14
+ ## What it does
15
+
16
+ | Feature | HIPAA reference | How |
17
+ |---|---|---|
18
+ | Role-based access control | 45 CFR 164.312(a)(1), 164.502(b) | Each role (clinician, billing, front desk, admin, researcher) can read only the columns it needs. Clinicians can open only their own patients' notes unless they use logged "break-the-glass" emergency access. |
19
+ | Tamper-evident audit log | 164.312(b), 164.312(c)(1) | Every read, write and denied attempt is appended to an audit table. Triggers block edits and deletes, and each row stores a SHA-256 hash of the previous row, so any change to history breaks the chain. |
20
+ | Access-anomaly detection | 164.308(a)(1)(ii)(D) | Rules flag bulk access (20+ patients/day), after-hours PHI reads, break-the-glass use and repeated denied attempts. |
21
+ | Safe Harbor de-identification | 164.514(b)(2) | Research export replaces patient IDs with keyed pseudonyms, reduces dates to year, groups ages 90+, truncates ZIP codes to 3 digits (or `000` for small areas), and scrubs names, SSNs, phones, emails, MRNs, dates, URLs and IPs from free-text notes. A verification pass checks for residual identifiers. |
22
+ | Compliance report | Security Rule mapping | Generates a Markdown report summarizing audit integrity, flagged events and de-identification results. |
23
+
24
+ ## Quick start
25
+
26
+ Requires Python 3.10+. No third-party packages are needed to run it (pytest only for tests).
27
+
28
+ Install from PyPI:
29
+
30
+ ```bash
31
+ pip install phiguard-audit
32
+ phiguard demo
33
+ ```
34
+
35
+ Or run from source:
36
+
37
+ ```bash
38
+ git clone https://github.com/arpitahaque/phi-guard.git
39
+ cd phi-guard
40
+ pip install -e . # optional: adds the `phiguard` command
41
+ python -m phiguard demo # build synthetic clinic, simulate a week, print report
42
+ python -m phiguard verify # check audit-log integrity
43
+ python -m phiguard anomalies # list flagged access events
44
+ python -m phiguard export # write de-identified research_export.csv
45
+ ```
46
+
47
+ The demo simulates one week of normal clinic activity plus three planted insider-threat scenarios:
48
+
49
+ 1. A billing user opens 25+ patient records late one evening (bulk + after-hours access).
50
+ 2. A clinician is denied three times on a chart that is not theirs, then uses break-the-glass.
51
+ 3. A researcher tries to read identified clinical notes directly.
52
+
53
+ All three are caught. See [`docs/sample_compliance_report.md`](https://github.com/arpitahaque/phi-guard/blob/main/docs/sample_compliance_report.md) for the output.
54
+
55
+ ## Run the tests
56
+
57
+ ```bash
58
+ pip install -e ".[test]"
59
+ python -m pytest -q
60
+ ```
61
+
62
+ GitHub Actions runs the tests and the end-to-end demo on Python 3.10 to 3.13 for every push.
63
+
64
+ Tests cover column-level access, denial logging, the clinician care-relationship rule, append-only enforcement, tamper detection on the hash chain, Safe Harbor helpers, residual-identifier checks and detection of each planted threat.
65
+
66
+ ## Project structure
67
+
68
+ ```
69
+ phiguard/
70
+ schema.py tables + append-only audit triggers
71
+ access.py role policy and audited access layer
72
+ audit.py hash-chained audit logging and verification
73
+ anomaly.py insider-threat detection rules
74
+ deidentify.py HIPAA Safe Harbor export and text scrubbing
75
+ synthetic.py synthetic clinic data and simulated activity
76
+ report.py compliance report mapped to the Security Rule
77
+ cli.py command-line interface
78
+ tests/ pytest suite
79
+ docs/ sample report
80
+ ```
81
+
82
+ ## Limitations and future work
83
+
84
+ - The rule-based text scrubber catches structured identifiers and known names but is not a substitute for a validated clinical de-identification model; a next step is comparing it with NLP-based PHI detection.
85
+ - The restricted 3-digit ZIP list is an illustrative subset; production use should load the current U.S. Census list.
86
+ - Anomaly thresholds are fixed; future work could learn per-role baselines from historical audit data.
87
+ - Hash-chaining detects tampering inside the database; anchoring periodic chain hashes to external storage would also protect against full-table replacement.
88
+
89
+ ## Author
90
+
91
+ Arpita Haque, B.S. Computer Information Technology (Cybersecurity minor), Minnesota State University Moorhead.
92
+ Related prior work: SecurePsych AI, a privacy-focused on-premise AI assistant for mental-health documentation.
93
+
94
+ ## Contributing and security
95
+
96
+ See [CONTRIBUTING.md](https://github.com/arpitahaque/phi-guard/blob/main/CONTRIBUTING.md) and [SECURITY.md](https://github.com/arpitahaque/phi-guard/blob/main/SECURITY.md). Release notes are in [CHANGELOG.md](https://github.com/arpitahaque/phi-guard/blob/main/CHANGELOG.md).
97
+
98
+ ## License
99
+
100
+ [MIT](https://github.com/arpitahaque/phi-guard/blob/main/LICENSE)
@@ -0,0 +1,15 @@
1
+ """PHI-Guard: HIPAA-aligned database security and auditing toolkit.
2
+
3
+ A teaching/research toolkit that demonstrates, on a synthetic mental-health
4
+ clinic database:
5
+
6
+ * role-based access control (minimum-necessary principle),
7
+ * tamper-evident audit logging of every read and write,
8
+ * access-anomaly detection over the audit trail,
9
+ * HIPAA Safe Harbor de-identification of records and free-text notes,
10
+ * a compliance report mapped to the HIPAA Security Rule (45 CFR 164.312).
11
+
12
+ All data is synthetic. Never load real patient data into this project.
13
+ """
14
+
15
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,99 @@
1
+ """Role-based access control enforcing the 'minimum necessary' standard.
2
+
3
+ HIPAA 164.312(a)(1) Access control and 164.502(b) minimum necessary.
4
+ Every request goes through `AccessLayer`, which checks the role policy,
5
+ returns only the columns that role may see, and writes an audit event
6
+ (including denied attempts).
7
+ """
8
+
9
+ import sqlite3
10
+
11
+ from .audit import log_event
12
+
13
+ # Columns each role may read, per table. Anything not listed is hidden.
14
+ POLICY = {
15
+ "clinician": {
16
+ "patients": ["patient_id", "mrn", "full_name", "birth_date", "phone",
17
+ "assigned_clinician"],
18
+ "clinical_notes": ["note_id", "patient_id", "provider_id", "note_date", "note_text"],
19
+ "appointments": ["appointment_id", "patient_id", "provider_id", "visit_date",
20
+ "diagnosis_code"],
21
+ },
22
+ "billing": {
23
+ "patients": ["patient_id", "mrn", "full_name", "street", "city", "state",
24
+ "zip", "insurance_id"],
25
+ "appointments": ["appointment_id", "patient_id", "visit_date",
26
+ "diagnosis_code", "billed_amount"],
27
+ },
28
+ "front_desk": {
29
+ "patients": ["patient_id", "full_name", "phone", "email"],
30
+ "appointments": ["appointment_id", "patient_id", "provider_id", "visit_date"],
31
+ },
32
+ "admin": {}, # administers the system, does not need PHI
33
+ "researcher": {}, # must use the de-identified export instead
34
+ }
35
+
36
+
37
+ class AccessDenied(Exception):
38
+ pass
39
+
40
+
41
+ class AccessLayer:
42
+ def __init__(self, conn: sqlite3.Connection, actor_id: int, ts=None):
43
+ self.conn = conn
44
+ row = conn.execute("SELECT role FROM providers WHERE provider_id=?",
45
+ (actor_id,)).fetchone()
46
+ if row is None:
47
+ raise AccessDenied(f"unknown user {actor_id}")
48
+ self.actor_id = actor_id
49
+ self.role = row["role"]
50
+ self.ts = ts # allow simulated timestamps
51
+
52
+ def _deny(self, table, patient_id, reason):
53
+ log_event(self.conn, actor_id=self.actor_id, actor_role=self.role,
54
+ action="DENIED", table_name=table, patient_id=patient_id,
55
+ reason=reason, ts=self.ts)
56
+ self.conn.commit()
57
+ raise AccessDenied(reason)
58
+
59
+ def read_patient_record(self, table: str, patient_id: int,
60
+ reason: str = "treatment",
61
+ break_glass: bool = False) -> list[dict]:
62
+ cols = POLICY.get(self.role, {}).get(table)
63
+ if not cols:
64
+ self._deny(table, patient_id, f"role '{self.role}' has no access to {table}")
65
+
66
+ # Clinicians may only open charts of their own patients unless they
67
+ # explicitly 'break the glass' (emergency access), which is flagged.
68
+ if self.role == "clinician" and table == "clinical_notes" and not break_glass:
69
+ owner = self.conn.execute(
70
+ "SELECT assigned_clinician FROM patients WHERE patient_id=?",
71
+ (patient_id,)).fetchone()
72
+ if owner is None or owner["assigned_clinician"] != self.actor_id:
73
+ self._deny(table, patient_id, "not the assigned clinician")
74
+
75
+ rows = self.conn.execute(
76
+ f"SELECT {', '.join(cols)} FROM {table} WHERE patient_id=?",
77
+ (patient_id,)).fetchall()
78
+ for r in rows or [None]:
79
+ log_event(self.conn, actor_id=self.actor_id, actor_role=self.role,
80
+ action="READ", table_name=table,
81
+ record_id=(r[cols[0]] if r else None),
82
+ patient_id=patient_id,
83
+ reason=("BREAK_GLASS: " + reason) if break_glass else reason,
84
+ ts=self.ts)
85
+ self.conn.commit()
86
+ return [dict(r) for r in rows]
87
+
88
+ def add_note(self, patient_id: int, note_date: str, text: str) -> int:
89
+ if self.role != "clinician":
90
+ self._deny("clinical_notes", patient_id, "only clinicians may write notes")
91
+ cur = self.conn.execute(
92
+ "INSERT INTO clinical_notes (patient_id, provider_id, note_date, note_text) "
93
+ "VALUES (?,?,?,?)", (patient_id, self.actor_id, note_date, text))
94
+ log_event(self.conn, actor_id=self.actor_id, actor_role=self.role,
95
+ action="INSERT", table_name="clinical_notes",
96
+ record_id=cur.lastrowid, patient_id=patient_id,
97
+ reason="documentation", ts=self.ts)
98
+ self.conn.commit()
99
+ return cur.lastrowid
@@ -0,0 +1,57 @@
1
+ """Rule-based detection of suspicious access in the audit trail.
2
+
3
+ These rules model common insider-threat patterns seen in healthcare
4
+ breach reports: snooping on charts outside one's care relationship,
5
+ bulk record access, after-hours access, emergency-access overuse and
6
+ repeated denied attempts.
7
+ """
8
+
9
+ import sqlite3
10
+ from collections import defaultdict
11
+ from datetime import datetime
12
+
13
+ BUSINESS_HOURS = range(7, 19) # 07:00-18:59 local
14
+ BULK_THRESHOLD = 20 # distinct patients per user per day
15
+ DENIED_THRESHOLD = 3 # denied attempts per user per day
16
+
17
+
18
+ def detect(conn: sqlite3.Connection) -> list[dict]:
19
+ findings = []
20
+ per_day_patients = defaultdict(set)
21
+ per_day_denied = defaultdict(int)
22
+
23
+ rows = conn.execute(
24
+ "SELECT * FROM audit_log ORDER BY audit_id").fetchall()
25
+ for r in rows:
26
+ ts = datetime.fromisoformat(r["ts"])
27
+ day = ts.date().isoformat()
28
+ key = (r["actor_id"], day)
29
+
30
+ if r["action"] == "READ" and r["patient_id"] is not None:
31
+ per_day_patients[key].add(r["patient_id"])
32
+ if ts.hour not in BUSINESS_HOURS:
33
+ findings.append(_f("AFTER_HOURS", "medium", r,
34
+ f"PHI read at {ts.strftime('%H:%M')}"))
35
+ if r["reason"] and r["reason"].startswith("BREAK_GLASS"):
36
+ findings.append(_f("BREAK_GLASS", "high", r,
37
+ "emergency access used; requires review"))
38
+ if r["action"] == "DENIED":
39
+ per_day_denied[key] += 1
40
+
41
+ for (actor, day), patients in per_day_patients.items():
42
+ if len(patients) >= BULK_THRESHOLD:
43
+ findings.append({"rule": "BULK_ACCESS", "severity": "high",
44
+ "actor_id": actor, "day": day,
45
+ "detail": f"{len(patients)} distinct patients in one day"})
46
+ for (actor, day), n in per_day_denied.items():
47
+ if n >= DENIED_THRESHOLD:
48
+ findings.append({"rule": "REPEATED_DENIALS", "severity": "high",
49
+ "actor_id": actor, "day": day,
50
+ "detail": f"{n} denied access attempts"})
51
+ return findings
52
+
53
+
54
+ def _f(rule, severity, r, detail):
55
+ return {"rule": rule, "severity": severity, "actor_id": r["actor_id"],
56
+ "day": r["ts"][:10], "audit_id": r["audit_id"],
57
+ "patient_id": r["patient_id"], "detail": detail}
@@ -0,0 +1,45 @@
1
+ """Tamper-evident audit logging (HIPAA 164.312(b) Audit controls)."""
2
+
3
+ import hashlib
4
+ import sqlite3
5
+ from datetime import datetime, timezone
6
+
7
+ GENESIS = "0" * 64
8
+
9
+
10
+ def _hash_row(fields: tuple) -> str:
11
+ payload = "|".join("" if f is None else str(f) for f in fields)
12
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()
13
+
14
+
15
+ def log_event(conn: sqlite3.Connection, *, actor_id, actor_role, action, table_name,
16
+ record_id=None, patient_id=None, reason=None, ts=None) -> None:
17
+ """Append one event to the hash-chained audit log."""
18
+ ts = ts or datetime.now(timezone.utc).isoformat(timespec="seconds")
19
+ last = conn.execute(
20
+ "SELECT row_hash FROM audit_log ORDER BY audit_id DESC LIMIT 1"
21
+ ).fetchone()
22
+ prev_hash = last["row_hash"] if last else GENESIS
23
+ fields = (ts, actor_id, actor_role, action, table_name, record_id,
24
+ patient_id, reason, prev_hash)
25
+ row_hash = _hash_row(fields)
26
+ conn.execute(
27
+ """INSERT INTO audit_log
28
+ (ts, actor_id, actor_role, action, table_name, record_id,
29
+ patient_id, reason, prev_hash, row_hash)
30
+ VALUES (?,?,?,?,?,?,?,?,?,?)""",
31
+ fields + (row_hash,),
32
+ )
33
+
34
+
35
+ def verify_chain(conn: sqlite3.Connection) -> tuple[bool, int | None]:
36
+ """Recompute the hash chain. Returns (ok, first_bad_audit_id)."""
37
+ prev = GENESIS
38
+ for r in conn.execute("SELECT * FROM audit_log ORDER BY audit_id"):
39
+ fields = (r["ts"], r["actor_id"], r["actor_role"], r["action"],
40
+ r["table_name"], r["record_id"], r["patient_id"],
41
+ r["reason"], r["prev_hash"])
42
+ if r["prev_hash"] != prev or _hash_row(fields) != r["row_hash"]:
43
+ return False, r["audit_id"]
44
+ prev = r["row_hash"]
45
+ return True, None
@@ -0,0 +1,72 @@
1
+ """Command-line interface: python -m phiguard <command>."""
2
+
3
+ import argparse
4
+ import csv
5
+ import os
6
+ import sys
7
+ from datetime import date
8
+
9
+ from . import anomaly, audit, deidentify, report, schema, synthetic
10
+
11
+
12
+ def _key() -> bytes:
13
+ # Pseudonymization key. In practice keep it in a secrets manager, not the code.
14
+ return os.environ.get("PHIGUARD_KEY", "demo-key-change-me").encode()
15
+
16
+
17
+ def main(argv=None) -> int:
18
+ p = argparse.ArgumentParser(prog="phiguard",
19
+ description="HIPAA-aligned database security & audit toolkit")
20
+ p.add_argument("--db", default="clinic.db", help="SQLite database path")
21
+ sub = p.add_subparsers(dest="cmd", required=True)
22
+ sub.add_parser("demo", help="create synthetic clinic, simulate a week, write report")
23
+ sub.add_parser("verify", help="verify the audit log hash chain")
24
+ sub.add_parser("anomalies", help="list flagged access events")
25
+ ex = sub.add_parser("export", help="write a de-identified research CSV")
26
+ ex.add_argument("--out", default="research_export.csv")
27
+ rp = sub.add_parser("report", help="write the compliance report")
28
+ rp.add_argument("--out", default="compliance_report.md")
29
+ args = p.parse_args(argv)
30
+
31
+ if args.cmd == "demo":
32
+ if os.path.exists(args.db):
33
+ os.remove(args.db)
34
+ conn = schema.connect(args.db)
35
+ schema.create_schema(conn)
36
+ synthetic.seed(conn)
37
+ synthetic.simulate_activity(conn)
38
+ md = report.build(conn, _key(), as_of=date(2026, 11, 30))
39
+ with open("compliance_report.md", "w") as f:
40
+ f.write(md)
41
+ print(md)
42
+ print(f"Database: {args.db} Report: compliance_report.md")
43
+ return 0
44
+
45
+ conn = schema.connect(args.db)
46
+ if args.cmd == "verify":
47
+ ok, bad = audit.verify_chain(conn)
48
+ print("Audit chain VERIFIED" if ok else f"Audit chain BROKEN at audit_id {bad}")
49
+ return 0 if ok else 1
50
+ if args.cmd == "anomalies":
51
+ for f in anomaly.detect(conn):
52
+ print(f"[{f['severity'].upper()}] {f['rule']} user={f['actor_id']} "
53
+ f"day={f['day']} {f['detail']}")
54
+ return 0
55
+ if args.cmd == "export":
56
+ rows = deidentify.export_research_dataset(conn, _key())
57
+ with open(args.out, "w", newline="") as fh:
58
+ w = csv.DictWriter(fh, fieldnames=list(rows[0].keys()))
59
+ w.writeheader()
60
+ w.writerows(rows)
61
+ print(f"Wrote {len(rows)} de-identified rows to {args.out}")
62
+ return 0
63
+ if args.cmd == "report":
64
+ with open(args.out, "w") as fh:
65
+ fh.write(report.build(conn, _key()))
66
+ print(f"Wrote {args.out}")
67
+ return 0
68
+ return 1
69
+
70
+
71
+ if __name__ == "__main__":
72
+ sys.exit(main())
@@ -0,0 +1,88 @@
1
+ """HIPAA Safe Harbor de-identification (45 CFR 164.514(b)(2)).
2
+
3
+ Removes or generalizes the 18 Safe Harbor identifiers that appear in this
4
+ schema, and scrubs common identifiers from free-text clinical notes.
5
+ Patient IDs are replaced with keyed pseudonyms (HMAC-SHA256) so records can
6
+ still be linked inside a research dataset without revealing identity.
7
+ """
8
+
9
+ import hashlib
10
+ import hmac
11
+ import re
12
+ import sqlite3
13
+ from datetime import date
14
+
15
+ # 3-digit ZIP prefixes with population <= 20,000 must become "000".
16
+ # (Illustrative subset; a real deployment should load the current Census list.)
17
+ RESTRICTED_ZIP3 = {"036", "059", "063", "102", "203", "556", "692", "790",
18
+ "821", "823", "830", "831", "878", "879", "884", "890", "893"}
19
+
20
+ TEXT_PATTERNS = [
21
+ (re.compile(r"\b\d{3}-\d{2}-\d{4}\b"), "[SSN]"),
22
+ (re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.]+\b"), "[EMAIL]"),
23
+ (re.compile(r"\(?\b\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b"), "[PHONE]"),
24
+ (re.compile(r"\bMRN[-:\s]*\w+\b", re.I), "[MRN]"),
25
+ (re.compile(r"\b\d{1,2}/\d{1,2}/\d{2,4}\b"), "[DATE]"),
26
+ (re.compile(r"\b\d{4}-\d{2}-\d{2}\b"), "[DATE]"),
27
+ (re.compile(r"\bhttps?://\S+"), "[URL]"),
28
+ (re.compile(r"\b\d{1,3}(?:\.\d{1,3}){3}\b"), "[IP]"),
29
+ ]
30
+
31
+
32
+ def pseudonym(patient_id: int, key: bytes) -> str:
33
+ return "P-" + hmac.new(key, str(patient_id).encode(), hashlib.sha256).hexdigest()[:12]
34
+
35
+
36
+ def generalize_zip(zip_code: str | None) -> str | None:
37
+ if not zip_code:
38
+ return None
39
+ z3 = zip_code[:3]
40
+ return "000" if z3 in RESTRICTED_ZIP3 else z3
41
+
42
+
43
+ def age_bucket(birth_date: str, as_of: date) -> str:
44
+ b = date.fromisoformat(birth_date)
45
+ age = as_of.year - b.year - ((as_of.month, as_of.day) < (b.month, b.day))
46
+ return "90+" if age >= 90 else str(age)
47
+
48
+
49
+ def scrub_text(text: str, names: list[str]) -> str:
50
+ for pattern, token in TEXT_PATTERNS:
51
+ text = pattern.sub(token, text)
52
+ for name in names:
53
+ for part in name.split():
54
+ if len(part) > 1:
55
+ text = re.sub(rf"\b{re.escape(part)}\b", "[NAME]", text)
56
+ return text
57
+
58
+
59
+ def export_research_dataset(conn: sqlite3.Connection, key: bytes,
60
+ as_of: date | None = None) -> list[dict]:
61
+ """Return one de-identified row per clinical note, ready for research use."""
62
+ as_of = as_of or date.today()
63
+ all_names = [r["full_name"] for r in conn.execute("SELECT full_name FROM patients")]
64
+ all_names += [r["name"] for r in conn.execute("SELECT name FROM providers")]
65
+ out = []
66
+ q = """SELECT n.note_id, n.note_date, n.note_text, p.patient_id, p.birth_date,
67
+ p.zip, p.state
68
+ FROM clinical_notes n JOIN patients p USING (patient_id)"""
69
+ for r in conn.execute(q):
70
+ out.append({
71
+ "subject": pseudonym(r["patient_id"], key),
72
+ "age": age_bucket(r["birth_date"], as_of),
73
+ "zip3": generalize_zip(r["zip"]),
74
+ "state": r["state"], # state level is permitted
75
+ "note_year": r["note_date"][:4], # dates reduced to year
76
+ "note_text": scrub_text(r["note_text"], all_names),
77
+ })
78
+ return out
79
+
80
+
81
+ def residual_identifier_check(rows: list[dict]) -> list[str]:
82
+ """Simple verification pass: flag any row that still looks identifying."""
83
+ problems = []
84
+ for i, row in enumerate(rows):
85
+ for pattern, token in TEXT_PATTERNS:
86
+ if pattern.search(row["note_text"]):
87
+ problems.append(f"row {i}: residual {token}")
88
+ return problems
@@ -0,0 +1,63 @@
1
+ """Generate a Markdown compliance report mapped to the HIPAA Security Rule."""
2
+
3
+ import sqlite3
4
+ from collections import Counter
5
+ from datetime import date
6
+
7
+ from .anomaly import detect
8
+ from .audit import verify_chain
9
+ from .deidentify import export_research_dataset, residual_identifier_check
10
+
11
+ CONTROLS = [
12
+ ("164.312(a)(1)", "Access control",
13
+ "Role-based policy limits each role to the minimum necessary columns; "
14
+ "researchers and admins get no direct PHI access."),
15
+ ("164.312(b)", "Audit controls",
16
+ "Every read, write and denied attempt is recorded in an append-only, "
17
+ "SHA-256 hash-chained audit log."),
18
+ ("164.312(c)(1)", "Integrity",
19
+ "Triggers block UPDATE/DELETE on the audit log; the hash chain detects tampering."),
20
+ ("164.308(a)(1)(ii)(D)", "Information system activity review",
21
+ "Automated rules flag bulk access, after-hours access, break-the-glass use "
22
+ "and repeated denials for human review."),
23
+ ("164.514(b)(2)", "De-identification (Safe Harbor)",
24
+ "Research export removes direct identifiers, keyed-pseudonymizes subjects, "
25
+ "reduces dates to year, ages 90+ to '90+', ZIP to 3 digits, and scrubs notes."),
26
+ ]
27
+
28
+
29
+ def build(conn: sqlite3.Connection, key: bytes, as_of: date | None = None) -> str:
30
+ ok, bad = verify_chain(conn)
31
+ actions = Counter(r["action"] for r in conn.execute("SELECT action FROM audit_log"))
32
+ findings = detect(conn)
33
+ rows = export_research_dataset(conn, key, as_of=as_of)
34
+ residual = residual_identifier_check(rows)
35
+ by_rule = Counter(f["rule"] for f in findings)
36
+
37
+ lines = ["# PHI-Guard Compliance Report", "",
38
+ "_Synthetic data only. Mapped to the HIPAA Security Rule (45 CFR Part 164)._", "",
39
+ "## Summary", "",
40
+ f"- Audit events: **{sum(actions.values())}** "
41
+ f"({', '.join(f'{k} {v}' for k, v in sorted(actions.items()))})",
42
+ f"- Audit chain integrity: **{'VERIFIED' if ok else f'BROKEN at audit_id {bad}'}**",
43
+ f"- Access anomalies flagged: **{len(findings)}** "
44
+ f"({', '.join(f'{k} {v}' for k, v in sorted(by_rule.items())) or 'none'})",
45
+ f"- De-identified research rows: **{len(rows)}**, residual identifiers found: "
46
+ f"**{len(residual)}**", "",
47
+ "## Control mapping", "",
48
+ "| HIPAA reference | Safeguard | How PHI-Guard implements it |",
49
+ "|---|---|---|"]
50
+ lines += [f"| {ref} | {name} | {how} |" for ref, name, how in CONTROLS]
51
+ lines += ["", "## Flagged access for review", "",
52
+ "| Rule | Severity | User | Day | Detail |", "|---|---|---|---|---|"]
53
+ seen = set()
54
+ for f in findings:
55
+ k = (f["rule"], f["actor_id"], f["day"])
56
+ if k in seen and f["rule"] == "AFTER_HOURS":
57
+ continue # collapse repeated after-hours rows per user/day
58
+ seen.add(k)
59
+ lines.append(f"| {f['rule']} | {f['severity']} | {f['actor_id']} | {f['day']} | {f['detail']} |")
60
+ lines += ["", "## Sample de-identified record", ""]
61
+ if rows:
62
+ lines += ["```", str(rows[0]), "```"]
63
+ return "\n".join(lines) + "\n"
@@ -0,0 +1,87 @@
1
+ """Database schema for the synthetic clinic, plus write-audit triggers."""
2
+
3
+ import sqlite3
4
+
5
+ SCHEMA = """
6
+ PRAGMA foreign_keys = ON;
7
+
8
+ CREATE TABLE IF NOT EXISTS providers (
9
+ provider_id INTEGER PRIMARY KEY,
10
+ name TEXT NOT NULL,
11
+ role TEXT NOT NULL CHECK (role IN ('clinician','billing','front_desk','admin','researcher'))
12
+ );
13
+
14
+ CREATE TABLE IF NOT EXISTS patients (
15
+ patient_id INTEGER PRIMARY KEY,
16
+ mrn TEXT NOT NULL UNIQUE, -- medical record number (identifier)
17
+ full_name TEXT NOT NULL,
18
+ birth_date TEXT NOT NULL, -- YYYY-MM-DD
19
+ ssn TEXT, -- identifier
20
+ phone TEXT,
21
+ email TEXT,
22
+ street TEXT,
23
+ city TEXT,
24
+ state TEXT,
25
+ zip TEXT,
26
+ insurance_id TEXT,
27
+ assigned_clinician INTEGER REFERENCES providers(provider_id)
28
+ );
29
+
30
+ CREATE TABLE IF NOT EXISTS appointments (
31
+ appointment_id INTEGER PRIMARY KEY,
32
+ patient_id INTEGER NOT NULL REFERENCES patients(patient_id),
33
+ provider_id INTEGER NOT NULL REFERENCES providers(provider_id),
34
+ visit_date TEXT NOT NULL,
35
+ diagnosis_code TEXT, -- ICD-10 style code
36
+ billed_amount REAL
37
+ );
38
+
39
+ CREATE TABLE IF NOT EXISTS clinical_notes (
40
+ note_id INTEGER PRIMARY KEY,
41
+ patient_id INTEGER NOT NULL REFERENCES patients(patient_id),
42
+ provider_id INTEGER NOT NULL REFERENCES providers(provider_id),
43
+ note_date TEXT NOT NULL,
44
+ note_text TEXT NOT NULL
45
+ );
46
+
47
+ -- Append-only audit trail. Each row stores the hash of the previous row,
48
+ -- forming a hash chain so tampering can be detected.
49
+ CREATE TABLE IF NOT EXISTS audit_log (
50
+ audit_id INTEGER PRIMARY KEY AUTOINCREMENT,
51
+ ts TEXT NOT NULL,
52
+ actor_id INTEGER,
53
+ actor_role TEXT,
54
+ action TEXT NOT NULL, -- READ / INSERT / UPDATE / DELETE / DENIED
55
+ table_name TEXT NOT NULL,
56
+ record_id INTEGER,
57
+ patient_id INTEGER,
58
+ reason TEXT,
59
+ prev_hash TEXT NOT NULL,
60
+ row_hash TEXT NOT NULL
61
+ );
62
+
63
+ -- Block edits/deletes on the audit trail itself.
64
+ CREATE TRIGGER IF NOT EXISTS audit_no_update
65
+ BEFORE UPDATE ON audit_log
66
+ BEGIN
67
+ SELECT RAISE(ABORT, 'audit_log is append-only');
68
+ END;
69
+
70
+ CREATE TRIGGER IF NOT EXISTS audit_no_delete
71
+ BEFORE DELETE ON audit_log
72
+ BEGIN
73
+ SELECT RAISE(ABORT, 'audit_log is append-only');
74
+ END;
75
+ """
76
+
77
+
78
+ def connect(path: str) -> sqlite3.Connection:
79
+ conn = sqlite3.connect(path)
80
+ conn.row_factory = sqlite3.Row
81
+ conn.execute("PRAGMA foreign_keys = ON")
82
+ return conn
83
+
84
+
85
+ def create_schema(conn: sqlite3.Connection) -> None:
86
+ conn.executescript(SCHEMA)
87
+ conn.commit()
@@ -0,0 +1,128 @@
1
+ """Synthetic clinic data and a simulated week of access activity.
2
+
3
+ Everything here is fake. Names are drawn from small generic lists and
4
+ numbers are random, so the data cannot identify a real person.
5
+ """
6
+
7
+ import random
8
+ import sqlite3
9
+ from datetime import date, datetime, timedelta
10
+
11
+ from .access import AccessDenied, AccessLayer
12
+
13
+ FIRST = ["Alex", "Jordan", "Taylor", "Morgan", "Casey", "Riley", "Avery",
14
+ "Jamie", "Quinn", "Rowan", "Skyler", "Parker", "Reese", "Drew"]
15
+ LAST = ["Smith", "Lee", "Garcia", "Nguyen", "Patel", "Brown", "Khan",
16
+ "Olsen", "Miller", "Davis", "Lopez", "Wilson", "Ahmed", "Novak"]
17
+ CITIES = [("St. Cloud", "MN", "56301"), ("Fargo", "ND", "58102"),
18
+ ("Moorhead", "MN", "56560"), ("Mankato", "MN", "56001"),
19
+ ("Duluth", "MN", "55802")]
20
+ DX = ["F32.1", "F41.1", "F43.10", "F33.0", "F90.0", "F41.0"]
21
+ NOTE_TEMPLATES = [
22
+ "Patient {name} reports improved sleep. Follow-up on {d}. Call {phone} if worse.",
23
+ "{name} (MRN {mrn}) discussed anxiety triggers at work. Continue CBT plan.",
24
+ "Session with {name}; mood stable. Emailed worksheet to {email}.",
25
+ "Reviewed safety plan with {name}. Next visit {d}. SSN on file {ssn} verified for billing.",
26
+ "{name} completed PHQ-9. Score decreased since last visit.",
27
+ "{name} completed GAD-7; score in moderate range. Practiced box breathing in session.",
28
+ "Intake for {name}, MRN {mrn}. Presenting concern: low mood and poor concentration for six weeks.",
29
+ "{name} missed last appointment. Left voicemail at {phone} to reschedule.",
30
+ "Medication check-in with {name}. Reports mild nausea; will reassess on {d}.",
31
+ "{name} reports conflict with roommate. Worked on assertive communication skills.",
32
+ "Telehealth session with {name}. Link sent to {email}. Connection stable throughout.",
33
+ "{name} denies suicidal ideation today. Safety plan reviewed and unchanged.",
34
+ "Family session requested by {name}. Scheduled for {d}; consent form signed.",
35
+ "{name} journaling three times per week. Noted fewer panic episodes than last month.",
36
+ "Insurance pre-authorization for {name} (SSN {ssn}) submitted; awaiting response.",
37
+ "{name} discussed grief following a recent loss. Plan: weekly sessions for one month.",
38
+ "Sleep hygiene education provided to {name}. Handout emailed to {email}.",
39
+ "{name} reports stress about final exams. Introduced a study-break routine.",
40
+ "Care coordination: spoke with {name}'s primary care office about lab results. Callback {phone}.",
41
+ "{name} (MRN {mrn}) reached treatment goals; discussed step-down to biweekly visits.",
42
+ ]
43
+
44
+
45
+ def seed(conn: sqlite3.Connection, n_patients: int = 60, rng_seed: int = 7) -> None:
46
+ rng = random.Random(rng_seed)
47
+ providers = [
48
+ (1, "Dr. Casey Lee", "clinician"), (2, "Dr. Avery Patel", "clinician"),
49
+ (3, "Dr. Rowan Khan", "clinician"), (4, "Jordan Billing", "billing"),
50
+ (5, "Riley Desk", "front_desk"), (6, "Sam Admin", "admin"),
51
+ (7, "Quinn Research", "researcher"),
52
+ ]
53
+ conn.executemany("INSERT INTO providers VALUES (?,?,?)", providers)
54
+
55
+ for pid in range(1, n_patients + 1):
56
+ name = f"{rng.choice(FIRST)} {rng.choice(LAST)}"
57
+ city, state, z = rng.choice(CITIES)
58
+ bdate = date(rng.randint(1932, 2006), rng.randint(1, 12), rng.randint(1, 28))
59
+ conn.execute(
60
+ """INSERT INTO patients VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)""",
61
+ (pid, f"MRN{100000 + pid}", name, bdate.isoformat(),
62
+ f"{rng.randint(100,899)}-{rng.randint(10,99)}-{rng.randint(1000,9999)}",
63
+ f"320-555-{rng.randint(1000,9999)}",
64
+ f"{name.split()[0].lower()}{pid}@example.com",
65
+ f"{rng.randint(10,999)} Main St", city, state, z,
66
+ f"INS-{rng.randint(10**6, 10**7)}", rng.choice([1, 2, 3])))
67
+
68
+ note_id = 1
69
+ for pid in range(1, n_patients + 1):
70
+ p = conn.execute("SELECT * FROM patients WHERE patient_id=?", (pid,)).fetchone()
71
+ for k in range(rng.randint(1, 3)):
72
+ d = date(2026, rng.randint(1, 10), rng.randint(1, 28)).isoformat()
73
+ conn.execute("INSERT INTO appointments VALUES (?,?,?,?,?,?)",
74
+ (None, pid, p["assigned_clinician"], d, rng.choice(DX),
75
+ round(rng.uniform(90, 250), 2)))
76
+ text = rng.choice(NOTE_TEMPLATES).format(
77
+ name=p["full_name"], d=d, phone=p["phone"], mrn=p["mrn"],
78
+ email=p["email"], ssn=p["ssn"])
79
+ conn.execute("INSERT INTO clinical_notes VALUES (?,?,?,?,?)",
80
+ (note_id, pid, p["assigned_clinician"], d, text))
81
+ note_id += 1
82
+ conn.commit()
83
+
84
+
85
+ def simulate_activity(conn: sqlite3.Connection, rng_seed: int = 11) -> None:
86
+ """A week of mostly normal access plus a few planted insider-threat cases."""
87
+ rng = random.Random(rng_seed)
88
+ start = datetime(2026, 11, 2, 8, 0)
89
+ patients = [r["patient_id"] for r in conn.execute("SELECT patient_id FROM patients")]
90
+
91
+ def at(day, hour, minute=0):
92
+ return (start + timedelta(days=day)).replace(hour=hour, minute=minute).isoformat()
93
+
94
+ # Normal daytime work.
95
+ for day in range(5):
96
+ for clin in (1, 2, 3):
97
+ own = [r["patient_id"] for r in conn.execute(
98
+ "SELECT patient_id FROM patients WHERE assigned_clinician=?", (clin,))]
99
+ for pid in rng.sample(own, k=min(4, len(own))):
100
+ AccessLayer(conn, clin, ts=at(day, rng.randint(8, 16), rng.randint(0, 59))
101
+ ).read_patient_record("clinical_notes", pid)
102
+ for pid in rng.sample(patients, 5):
103
+ AccessLayer(conn, 4, ts=at(day, rng.randint(9, 16))).read_patient_record(
104
+ "appointments", pid, reason="billing")
105
+ AccessLayer(conn, 5, ts=at(day, rng.randint(8, 17))).read_patient_record(
106
+ "patients", pid, reason="scheduling")
107
+
108
+ # Planted case 1: billing user pulls many charts in one evening (bulk + after hours).
109
+ for pid in patients[:25]:
110
+ AccessLayer(conn, 4, ts=at(3, 21, rng.randint(0, 59))).read_patient_record(
111
+ "patients", pid, reason="billing")
112
+
113
+ # Planted case 2: clinician tries to open a chart that isn't theirs, then breaks glass.
114
+ other = conn.execute(
115
+ "SELECT patient_id FROM patients WHERE assigned_clinician != 2 LIMIT 1").fetchone()[0]
116
+ for _ in range(3):
117
+ try:
118
+ AccessLayer(conn, 2, ts=at(2, 13)).read_patient_record("clinical_notes", other)
119
+ except AccessDenied:
120
+ pass
121
+ AccessLayer(conn, 2, ts=at(2, 13, 30)).read_patient_record(
122
+ "clinical_notes", other, reason="patient in crisis", break_glass=True)
123
+
124
+ # Planted case 3: researcher tries to read identified notes.
125
+ try:
126
+ AccessLayer(conn, 7, ts=at(4, 10)).read_patient_record("clinical_notes", patients[0])
127
+ except AccessDenied:
128
+ pass
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.4
2
+ Name: phiguard-audit
3
+ Version: 0.1.0
4
+ Summary: HIPAA-aligned database security and audit toolkit: RBAC, break-glass access, hash-chained audit log, Safe Harbor de-identification and anomaly detection.
5
+ Author-email: Arpita Haque <arpitakaiser@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/arpitahaque/phi-guard
8
+ Project-URL: Repository, https://github.com/arpitahaque/phi-guard
9
+ Project-URL: Issues, https://github.com/arpitahaque/phi-guard/issues
10
+ Project-URL: Changelog, https://github.com/arpitahaque/phi-guard/blob/main/CHANGELOG.md
11
+ Keywords: hipaa,database-security,audit-logging,de-identification,healthcare,rbac
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Security
14
+ Classifier: Topic :: Database
15
+ Classifier: Intended Audience :: Healthcare Industry
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest>=7; extra == "test"
21
+ Dynamic: license-file
22
+
23
+ # PHI-Guard
24
+
25
+ [![tests](https://github.com/arpitahaque/phi-guard/actions/workflows/tests.yml/badge.svg)](https://github.com/arpitahaque/phi-guard/actions/workflows/tests.yml)
26
+ [![PyPI](https://img.shields.io/pypi/v/phiguard-audit)](https://pypi.org/project/phiguard-audit/)
27
+ ![Python](https://img.shields.io/badge/python-3.10%2B-blue)
28
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/arpitahaque/phi-guard/blob/main/LICENSE)
29
+
30
+ **A HIPAA-aligned database security and auditing toolkit, demonstrated on a synthetic mental-health clinic database.**
31
+
32
+ Healthcare data breaches are often caused by insiders who can see more than they need or who browse records they have no reason to open. PHI-Guard shows how a small clinic database can enforce the HIPAA "minimum necessary" standard, keep a tamper-evident record of every access, flag suspicious behavior for review, and release research data that meets the HIPAA Safe Harbor de-identification standard.
33
+
34
+ > All data in this project is **synthetic**. Do not load real patient information into it.
35
+
36
+ ## What it does
37
+
38
+ | Feature | HIPAA reference | How |
39
+ |---|---|---|
40
+ | Role-based access control | 45 CFR 164.312(a)(1), 164.502(b) | Each role (clinician, billing, front desk, admin, researcher) can read only the columns it needs. Clinicians can open only their own patients' notes unless they use logged "break-the-glass" emergency access. |
41
+ | Tamper-evident audit log | 164.312(b), 164.312(c)(1) | Every read, write and denied attempt is appended to an audit table. Triggers block edits and deletes, and each row stores a SHA-256 hash of the previous row, so any change to history breaks the chain. |
42
+ | Access-anomaly detection | 164.308(a)(1)(ii)(D) | Rules flag bulk access (20+ patients/day), after-hours PHI reads, break-the-glass use and repeated denied attempts. |
43
+ | Safe Harbor de-identification | 164.514(b)(2) | Research export replaces patient IDs with keyed pseudonyms, reduces dates to year, groups ages 90+, truncates ZIP codes to 3 digits (or `000` for small areas), and scrubs names, SSNs, phones, emails, MRNs, dates, URLs and IPs from free-text notes. A verification pass checks for residual identifiers. |
44
+ | Compliance report | Security Rule mapping | Generates a Markdown report summarizing audit integrity, flagged events and de-identification results. |
45
+
46
+ ## Quick start
47
+
48
+ Requires Python 3.10+. No third-party packages are needed to run it (pytest only for tests).
49
+
50
+ Install from PyPI:
51
+
52
+ ```bash
53
+ pip install phiguard-audit
54
+ phiguard demo
55
+ ```
56
+
57
+ Or run from source:
58
+
59
+ ```bash
60
+ git clone https://github.com/arpitahaque/phi-guard.git
61
+ cd phi-guard
62
+ pip install -e . # optional: adds the `phiguard` command
63
+ python -m phiguard demo # build synthetic clinic, simulate a week, print report
64
+ python -m phiguard verify # check audit-log integrity
65
+ python -m phiguard anomalies # list flagged access events
66
+ python -m phiguard export # write de-identified research_export.csv
67
+ ```
68
+
69
+ The demo simulates one week of normal clinic activity plus three planted insider-threat scenarios:
70
+
71
+ 1. A billing user opens 25+ patient records late one evening (bulk + after-hours access).
72
+ 2. A clinician is denied three times on a chart that is not theirs, then uses break-the-glass.
73
+ 3. A researcher tries to read identified clinical notes directly.
74
+
75
+ All three are caught. See [`docs/sample_compliance_report.md`](https://github.com/arpitahaque/phi-guard/blob/main/docs/sample_compliance_report.md) for the output.
76
+
77
+ ## Run the tests
78
+
79
+ ```bash
80
+ pip install -e ".[test]"
81
+ python -m pytest -q
82
+ ```
83
+
84
+ GitHub Actions runs the tests and the end-to-end demo on Python 3.10 to 3.13 for every push.
85
+
86
+ Tests cover column-level access, denial logging, the clinician care-relationship rule, append-only enforcement, tamper detection on the hash chain, Safe Harbor helpers, residual-identifier checks and detection of each planted threat.
87
+
88
+ ## Project structure
89
+
90
+ ```
91
+ phiguard/
92
+ schema.py tables + append-only audit triggers
93
+ access.py role policy and audited access layer
94
+ audit.py hash-chained audit logging and verification
95
+ anomaly.py insider-threat detection rules
96
+ deidentify.py HIPAA Safe Harbor export and text scrubbing
97
+ synthetic.py synthetic clinic data and simulated activity
98
+ report.py compliance report mapped to the Security Rule
99
+ cli.py command-line interface
100
+ tests/ pytest suite
101
+ docs/ sample report
102
+ ```
103
+
104
+ ## Limitations and future work
105
+
106
+ - The rule-based text scrubber catches structured identifiers and known names but is not a substitute for a validated clinical de-identification model; a next step is comparing it with NLP-based PHI detection.
107
+ - The restricted 3-digit ZIP list is an illustrative subset; production use should load the current U.S. Census list.
108
+ - Anomaly thresholds are fixed; future work could learn per-role baselines from historical audit data.
109
+ - Hash-chaining detects tampering inside the database; anchoring periodic chain hashes to external storage would also protect against full-table replacement.
110
+
111
+ ## Author
112
+
113
+ Arpita Haque, B.S. Computer Information Technology (Cybersecurity minor), Minnesota State University Moorhead.
114
+ Related prior work: SecurePsych AI, a privacy-focused on-premise AI assistant for mental-health documentation.
115
+
116
+ ## Contributing and security
117
+
118
+ See [CONTRIBUTING.md](https://github.com/arpitahaque/phi-guard/blob/main/CONTRIBUTING.md) and [SECURITY.md](https://github.com/arpitahaque/phi-guard/blob/main/SECURITY.md). Release notes are in [CHANGELOG.md](https://github.com/arpitahaque/phi-guard/blob/main/CHANGELOG.md).
119
+
120
+ ## License
121
+
122
+ [MIT](https://github.com/arpitahaque/phi-guard/blob/main/LICENSE)
@@ -0,0 +1,20 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ phiguard/__init__.py
5
+ phiguard/__main__.py
6
+ phiguard/access.py
7
+ phiguard/anomaly.py
8
+ phiguard/audit.py
9
+ phiguard/cli.py
10
+ phiguard/deidentify.py
11
+ phiguard/report.py
12
+ phiguard/schema.py
13
+ phiguard/synthetic.py
14
+ phiguard_audit.egg-info/PKG-INFO
15
+ phiguard_audit.egg-info/SOURCES.txt
16
+ phiguard_audit.egg-info/dependency_links.txt
17
+ phiguard_audit.egg-info/entry_points.txt
18
+ phiguard_audit.egg-info/requires.txt
19
+ phiguard_audit.egg-info/top_level.txt
20
+ tests/test_phiguard.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ phiguard = phiguard.cli:main
@@ -0,0 +1,3 @@
1
+
2
+ [test]
3
+ pytest>=7
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "phiguard-audit"
7
+ version = "0.1.0"
8
+ description = "HIPAA-aligned database security and audit toolkit: RBAC, break-glass access, hash-chained audit log, Safe Harbor de-identification and anomaly detection."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Arpita Haque", email = "arpitakaiser@gmail.com" }]
14
+ keywords = ["hipaa", "database-security", "audit-logging", "de-identification", "healthcare", "rbac"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Topic :: Security",
18
+ "Topic :: Database",
19
+ "Intended Audience :: Healthcare Industry",
20
+ ]
21
+
22
+ [project.optional-dependencies]
23
+ test = ["pytest>=7"]
24
+
25
+ [project.scripts]
26
+ phiguard = "phiguard.cli:main"
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/arpitahaque/phi-guard"
30
+ Repository = "https://github.com/arpitahaque/phi-guard"
31
+ Issues = "https://github.com/arpitahaque/phi-guard/issues"
32
+ Changelog = "https://github.com/arpitahaque/phi-guard/blob/main/CHANGELOG.md"
33
+
34
+ [tool.setuptools]
35
+ packages = ["phiguard"]
36
+
37
+ [tool.pytest.ini_options]
38
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,85 @@
1
+ import sqlite3
2
+ from datetime import date
3
+
4
+ import pytest
5
+
6
+ from phiguard import anomaly, audit, deidentify, schema, synthetic
7
+ from phiguard.access import AccessDenied, AccessLayer
8
+
9
+ KEY = b"test-key"
10
+
11
+
12
+ @pytest.fixture
13
+ def conn():
14
+ c = schema.connect(":memory:")
15
+ schema.create_schema(c)
16
+ synthetic.seed(c, n_patients=30)
17
+ return c
18
+
19
+
20
+ def test_role_sees_only_allowed_columns(conn):
21
+ rows = AccessLayer(conn, 5).read_patient_record("patients", 1, reason="scheduling")
22
+ assert set(rows[0]) == {"patient_id", "full_name", "phone", "email"}
23
+ assert "ssn" not in rows[0]
24
+
25
+
26
+ def test_researcher_denied_and_logged(conn):
27
+ with pytest.raises(AccessDenied):
28
+ AccessLayer(conn, 7).read_patient_record("clinical_notes", 1)
29
+ last = conn.execute("SELECT action FROM audit_log ORDER BY audit_id DESC").fetchone()
30
+ assert last["action"] == "DENIED"
31
+
32
+
33
+ def test_clinician_blocked_from_unassigned_chart(conn):
34
+ pid = conn.execute(
35
+ "SELECT patient_id FROM patients WHERE assigned_clinician != 1").fetchone()[0]
36
+ with pytest.raises(AccessDenied):
37
+ AccessLayer(conn, 1).read_patient_record("clinical_notes", pid)
38
+ rows = AccessLayer(conn, 1).read_patient_record(
39
+ "clinical_notes", pid, reason="emergency", break_glass=True)
40
+ assert rows
41
+
42
+
43
+ def test_audit_log_is_append_only(conn):
44
+ AccessLayer(conn, 5).read_patient_record("patients", 1)
45
+ with pytest.raises(sqlite3.DatabaseError):
46
+ conn.execute("DELETE FROM audit_log")
47
+ with pytest.raises(sqlite3.DatabaseError):
48
+ conn.execute("UPDATE audit_log SET actor_id = 99")
49
+
50
+
51
+ def test_hash_chain_detects_tampering(conn):
52
+ for pid in (1, 2, 3):
53
+ AccessLayer(conn, 5).read_patient_record("patients", pid)
54
+ assert audit.verify_chain(conn) == (True, None)
55
+ # Simulate an attacker who drops the triggers and edits history.
56
+ conn.execute("DROP TRIGGER audit_no_update")
57
+ conn.execute("UPDATE audit_log SET patient_id = 999 WHERE audit_id = 2")
58
+ ok, bad = audit.verify_chain(conn)
59
+ assert not ok and bad == 2
60
+
61
+
62
+ def test_deidentified_export_has_no_identifiers(conn):
63
+ rows = deidentify.export_research_dataset(conn, KEY, as_of=date(2026, 11, 30))
64
+ assert rows
65
+ assert deidentify.residual_identifier_check(rows) == []
66
+ names = [r["full_name"] for r in conn.execute("SELECT full_name FROM patients")]
67
+ for row in rows:
68
+ assert len(row["note_year"]) == 4
69
+ assert row["subject"].startswith("P-")
70
+ for n in names:
71
+ assert n not in row["note_text"]
72
+
73
+
74
+ def test_safe_harbor_helpers():
75
+ assert deidentify.generalize_zip("03601") == "000"
76
+ assert deidentify.generalize_zip("56301") == "563"
77
+ assert deidentify.age_bucket("1930-01-01", date(2026, 11, 30)) == "90+"
78
+ assert deidentify.pseudonym(1, KEY) == deidentify.pseudonym(1, KEY)
79
+ assert deidentify.pseudonym(1, KEY) != deidentify.pseudonym(1, b"other")
80
+
81
+
82
+ def test_planted_threats_are_detected(conn):
83
+ synthetic.simulate_activity(conn)
84
+ rules = {f["rule"] for f in anomaly.detect(conn)}
85
+ assert {"BULK_ACCESS", "AFTER_HOURS", "BREAK_GLASS", "REPEATED_DENIALS"} <= rules