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
 
 
 
d80907b
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
"""
PHI Field-Level Encryption — Envelope Encryption (DEK / KEK)
=============================================================

Architecture
------------
  KEK (Key-Encryption Key)
    Stored outside the application: AWS KMS, HashiCorp Vault, or env var for dev.
    Never held in memory longer than needed for a single encrypt/decrypt call.

  DEK (Data-Encryption Key)
    One 256-bit random DEK per PII field *instance*, generated at write time.
    Encrypted with the KEK → stored alongside the ciphertext as a small blob.
    DEK plaintext exists only in RAM during the encrypt/decrypt operation.

  Ciphertext envelope layout (base64url-encoded JSON):
    {
      "v":    1,                    # envelope version for rotation
      "kid":  "kek-2026-05",        # KEK key-id (which KEK sealed the DEK)
      "edek": "<base64>",           # AES-256-GCM encrypted DEK (12-byte nonce prepended)
      "iv":   "<base64>",           # 12-byte nonce for field ciphertext
      "ct":   "<base64>",           # AES-256-GCM ciphertext of the PHI value
      "tag":  "<base64>"            # 16-byte GCM authentication tag
    }

Key Rotation
------------
  1. Generate new KEK, register it in Vault/KMS with a new kid.
  2. Call `rotate_field_encryption(old_envelope, old_kek, new_kid)`:
       - Decrypt edek with old KEK
       - Re-encrypt DEK with new KEK
       - Returns new envelope (same DEK → ciphertext unchanged)
  3. Optionally run a background job to rotate persisted rows.

PHI Fields covered (Surgio)
---------------------------
  patient_mrn, patient_name, patient_dob, patient_contact

Masking
-------
  `mask_mrn(mrn)` → "***-XXXX" showing only last 4 characters.
  Safe for UI display and non-sensitive log correlation.

Standards
---------
  HIPAA §164.312(a)(2)(iv) — Encryption/Decryption (addressable safeguard)
  NIST SP 800-57 — Key management best practices
  AES-256-GCM   — Provides authenticated encryption (integrity + confidentiality)

Performance
-----------
  encrypt / decrypt < 2ms per field (hardware AES-NI)
  DEK derivation overhead: < 1ms (random bytes, no KDF for DEK itself)
"""

from __future__ import annotations

import base64
import json
import os
import re
import secrets
from typing import Any, Optional

import structlog
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.keywrap import aes_key_wrap, aes_key_unwrap
from cryptography.hazmat.backends import default_backend

logger = structlog.get_logger(__name__)

# ── Envelope version ──────────────────────────────────────────────────────────
_ENV_VERSION = 1
_DEK_LENGTH = 32  # 256-bit DEK
_NONCE_LENGTH = 12  # 96-bit GCM nonce (NIST recommended)

# ── PHI field names (used by the log scrubber) ────────────────────────────────
PHI_FIELD_NAMES: frozenset[str] = frozenset(
    {
        "patient_mrn",
        "mrn",
        "patient_name",
        "patient_dob",
        "dob",
        "patient_contact",
        "contact",
        "phone",
        "email",
        "address",
        "ssn",
        "national_id",
        "passport",
        # Add domain-specific PHI identifiers here
    }
)


# ─────────────────────────────────────────────────────────────────────────────
# KEK provider
# ─────────────────────────────────────────────────────────────────────────────


class KEKProvider:
    """
    Retrieves the Key-Encryption Key (KEK) from the configured secret store.

    Priority order:
      1. HashiCorp Vault (VAULT_ADDR + VAULT_TOKEN env vars)
      2. AWS KMS (AWS_KMS_KEY_ID env var)
      3. Environment variable PHI_KEK (base64url bytes) — dev / test only

    For production, always use option 1 or 2 so the KEK never touches
    application server disk.
    """

    def __init__(self) -> None:
        self._kek: Optional[bytes] = None
        self._kid: str = "env-kek"

    def get_kek(self) -> tuple[bytes, str]:
        """
        Returns (kek_bytes: bytes, kid: str).

        The KEK is a 32-byte (256-bit) raw key for AES-256 key-wrap operations.
        """
        if self._kek is not None:
            return self._kek, self._kid

        # ── Option 1: Vault ──────────────────────────────────────────────────
        vault_addr = os.getenv("VAULT_ADDR")
        vault_token = os.getenv("VAULT_TOKEN")
        vault_key_path = os.getenv("VAULT_PHI_KEY_PATH", "secret/data/yaz/phi_kek")
        if vault_addr and vault_token:
            try:
                kek, kid = self._fetch_from_vault(vault_addr, vault_token, vault_key_path)
                self._kek = kek
                self._kid = kid
                logger.info("phi_kek.loaded", source="vault", kid=kid)
                return self._kek, self._kid
            except Exception as exc:
                logger.warning("phi_kek.vault_failed", error=str(exc))

        # ── Option 2: AWS KMS ────────────────────────────────────────────────
        kms_key_id = os.getenv("AWS_KMS_KEY_ID")
        if kms_key_id:
            try:
                kek, kid = self._fetch_from_kms(kms_key_id)
                self._kek = kek
                self._kid = kid
                logger.info("phi_kek.loaded", source="aws_kms", kid=kid)
                return self._kek, self._kid
            except Exception as exc:
                logger.warning("phi_kek.kms_failed", error=str(exc))

        # ── Option 3: Environment variable — dev/test ONLY ──────────────────
        env_kek = os.getenv("PHI_KEK")
        if env_kek:
            raw = base64.urlsafe_b64decode(env_kek + "==")
            if len(raw) != 32:
                raise ValueError("PHI_KEK must be exactly 32 bytes (256 bits) base64url-encoded")
            self._kek = raw
            self._kid = "env-kek"
            logger.warning(
                "phi_kek.loaded",
                source="env",
                kid="env-kek",
                warning="env KEK is for dev/test ONLY — use Vault or KMS in production",
            )
            return self._kek, self._kid

        # ── Fallback: generate ephemeral key (single process lifetime) ───────
        self._kek = secrets.token_bytes(32)
        self._kid = "ephemeral"
        logger.error(
            "phi_kek.ephemeral",
            warning=(
                "No KEK configured — using ephemeral key. "
                "ENCRYPTED DATA WILL BE UNRECOVERABLE AFTER PROCESS RESTART. "
                "Set PHI_KEK, VAULT_ADDR, or AWS_KMS_KEY_ID."
            ),
        )
        return self._kek, self._kid

    # ── Private helpers ───────────────────────────────────────────────────────

    @staticmethod
    def _fetch_from_vault(addr: str, token: str, path: str) -> tuple[bytes, str]:
        """Fetch KEK from HashiCorp Vault KV v2."""
        import urllib.request

        url = f"{addr}/v1/{path}"
        req = urllib.request.Request(
            url,
            headers={"X-Vault-Token": token},
            method="GET",
        )
        with urllib.request.urlopen(req, timeout=3) as resp:  # noqa: S310
            data = json.loads(resp.read())
        kek_b64 = data["data"]["data"]["kek"]
        kid = data["data"]["data"].get("kid", "vault-kek")
        return base64.urlsafe_b64decode(kek_b64 + "=="), kid

    @staticmethod
    def _fetch_from_kms(key_id: str) -> tuple[bytes, str]:
        """Generate a data key via AWS KMS GenerateDataKey."""
        import boto3  # type: ignore[import]

        kms = boto3.client("kms")
        resp = kms.generate_data_key(KeyId=key_id, KeySpec="AES_256")
        return resp["Plaintext"], key_id


# Module-level singleton
_kek_provider = KEKProvider()


# ─────────────────────────────────────────────────────────────────────────────
# Core encrypt / decrypt
# ─────────────────────────────────────────────────────────────────────────────


def encrypt_phi_field(plaintext: str) -> str:
    """
    Encrypt a PHI field value using envelope encryption (DEK wrapped by KEK).

    Args:
        plaintext: Raw PHI string (MRN, name, DoB, contact, etc.)

    Returns:
        Compact base64url-encoded JSON envelope (safe for VARCHAR DB columns).

    Raises:
        ValueError: if plaintext is empty.
        RuntimeError: if encryption fails.
    """
    if not plaintext:
        raise ValueError("Cannot encrypt empty PHI value")

    kek, kid = _kek_provider.get_kek()

    # 1. Generate a fresh DEK for this field instance
    dek = secrets.token_bytes(_DEK_LENGTH)

    # 2. Wrap the DEK with the KEK using AES-256-CBC key-wrap (RFC 3394)
    #    aes_key_wrap uses the key-wrap algorithm which adds 8-byte integrity check
    edek_raw = aes_key_wrap(kek, dek, default_backend())

    # 3. Encrypt the plaintext with the DEK (AES-256-GCM)
    nonce = secrets.token_bytes(_NONCE_LENGTH)
    aesgcm = AESGCM(dek)
    ciphertext_with_tag = aesgcm.encrypt(nonce, plaintext.encode("utf-8"), None)
    # AESGCM appends 16-byte tag to ciphertext
    ciphertext = ciphertext_with_tag[:-16]
    tag = ciphertext_with_tag[-16:]

    # 4. Build envelope
    envelope = {
        "v": _ENV_VERSION,
        "kid": kid,
        "edek": base64.urlsafe_b64encode(edek_raw).decode(),
        "iv": base64.urlsafe_b64encode(nonce).decode(),
        "ct": base64.urlsafe_b64encode(ciphertext).decode(),
        "tag": base64.urlsafe_b64encode(tag).decode(),
    }

    # 5. Zero-wipe DEK from memory (best-effort in Python)
    del dek

    return base64.urlsafe_b64encode(json.dumps(envelope, separators=(",", ":")).encode()).decode()


def decrypt_phi_field(envelope_b64: str) -> str:
    """
    Decrypt an envelope-encrypted PHI field.

    Args:
        envelope_b64: Output of encrypt_phi_field().

    Returns:
        Plaintext string.

    Raises:
        ValueError: if envelope is malformed or version mismatch.
        cryptography.exceptions.InvalidTag: if ciphertext has been tampered.
    """
    try:
        envelope = json.loads(base64.urlsafe_b64decode(envelope_b64 + "=="))
    except Exception as exc:
        raise ValueError(f"Malformed PHI envelope: {exc}") from exc

    if envelope.get("v") != _ENV_VERSION:
        raise ValueError(f"Unknown envelope version: {envelope.get('v')}")

    kek, _ = _kek_provider.get_kek()

    # 1. Unwrap DEK
    edek_raw = base64.urlsafe_b64decode(envelope["edek"] + "==")
    dek = aes_key_unwrap(kek, edek_raw, default_backend())

    # 2. Decrypt ciphertext
    nonce = base64.urlsafe_b64decode(envelope["iv"] + "==")
    ciphertext = base64.urlsafe_b64decode(envelope["ct"] + "==")
    tag = base64.urlsafe_b64decode(envelope["tag"] + "==")

    aesgcm = AESGCM(dek)
    plaintext_bytes = aesgcm.decrypt(nonce, ciphertext + tag, None)
    del dek

    return plaintext_bytes.decode("utf-8")


def rotate_field_encryption(envelope_b64: str, new_kid: Optional[str] = None) -> str:
    """
    Re-wrap the DEK under a new KEK without re-encrypting the data ciphertext.

    This enables zero-downtime key rotation:
      - The DEK (and therefore the ciphertext) is unchanged.
      - Only the edek blob is re-encrypted under the new KEK.

    Args:
        envelope_b64: Existing envelope from encrypt_phi_field().
        new_kid: Optional new KEK kid. If None, uses the current active KEK.

    Returns:
        New envelope_b64 with updated edek and kid.

    Typical workflow:
        rotated = rotate_field_encryption(row.patient_mrn_encrypted)
        row.patient_mrn_encrypted = rotated
        db.commit()
    """
    try:
        envelope = json.loads(base64.urlsafe_b64decode(envelope_b64 + "=="))
    except Exception as exc:
        raise ValueError(f"Malformed PHI envelope: {exc}") from exc

    # 1. Decrypt with current KEK
    old_kek, _ = _kek_provider.get_kek()
    edek_raw = base64.urlsafe_b64decode(envelope["edek"] + "==")
    dek = aes_key_unwrap(old_kek, edek_raw, default_backend())

    # 2. Re-encrypt DEK with (new) KEK
    new_kek, new_kid_resolved = _kek_provider.get_kek()
    new_edek_raw = aes_key_wrap(new_kek, dek, default_backend())
    del dek

    # 3. Return updated envelope (ciphertext/iv/tag unchanged)
    envelope["edek"] = base64.urlsafe_b64encode(new_edek_raw).decode()
    envelope["kid"] = new_kid if new_kid else new_kid_resolved

    return base64.urlsafe_b64encode(json.dumps(envelope, separators=(",", ":")).encode()).decode()


# ─────────────────────────────────────────────────────────────────────────────
# UI masking helpers
# ─────────────────────────────────────────────────────────────────────────────

_MRN_LAST_CHARS = 4


def mask_mrn(mrn: str) -> str:
    """
    Return a masked MRN for safe UI display, showing only the last 4 characters.

    Examples:
        mask_mrn("MRN-12345678")  →  "***-5678"
        mask_mrn("123456")        →  "**3456"
        mask_mrn("AB1")           →  "**1"  (shorter than 4 → mask all but last)
    """
    if not mrn:
        return "****"
    visible = min(_MRN_LAST_CHARS, len(mrn))
    return "*" * (len(mrn) - visible) + mrn[-visible:]


def mask_name(name: str) -> str:
    """
    Mask a patient name for audit logs: keep first initial + last name initial.
    "Ahmed El Amrani" → "A. E."

    Usage: log lines, error messages, non-clinical views.
    """
    if not name:
        return "**"
    parts = name.split()
    return " ".join(f"{p[0]}." for p in parts if p)


def mask_contact(contact: str) -> str:
    """
    Mask phone / email: show only last 4 digits or domain.
    "+212-661-234567"  → "+212-***-4567"
    "patient@gmail.com" → "***@gmail.com"
    """
    if not contact:
        return "****"
    if "@" in contact:
        local, domain = contact.split("@", 1)
        return f"***@{domain}"
    digits_only = re.sub(r"\D", "", contact)
    return "***-" + digits_only[-4:] if len(digits_only) >= 4 else "****"


# ─────────────────────────────────────────────────────────────────────────────
# Convenience wrapper for Surgio model integration
# ─────────────────────────────────────────────────────────────────────────────


class SurgioPatientPHI:
    """
    Typed wrapper for encrypting/decrypting Surgio patient PHI fields.

    Intended to be used by SurgicalCase model and CaseService:

        phi = SurgioPatientPHI(
            mrn="MRN-00127",
            name="Ahmed El Amrani",
            dob="1975-03-12",
            contact="+212-661-000-000",
        )
        # encrypt all fields at once:
        enc = phi.encrypt()
        # → {patient_mrn_enc, patient_name_enc, patient_dob_enc, patient_contact_enc}

        # decrypt all fields:
        dec = SurgioPatientPHI.decrypt(enc)
        # → SurgioPatientPHI(mrn="MRN-00127", ...)
    """

    __slots__ = ("mrn", "name", "dob", "contact")

    def __init__(
        self,
        mrn: str,
        name: str = "",
        dob: str = "",
        contact: str = "",
    ) -> None:
        self.mrn = mrn
        self.name = name
        self.dob = dob
        self.contact = contact

    def encrypt(self) -> dict[str, str]:
        """Return dict of envelope-encrypted PHI fields for DB storage."""
        result: dict[str, str] = {
            "patient_mrn_encrypted": encrypt_phi_field(self.mrn),
        }
        if self.name:
            result["patient_name_encrypted"] = encrypt_phi_field(self.name)
        if self.dob:
            result["patient_dob_encrypted"] = encrypt_phi_field(self.dob)
        if self.contact:
            result["patient_contact_encrypted"] = encrypt_phi_field(self.contact)
        return result

    @classmethod
    def decrypt(cls, fields: dict[str, str]) -> "SurgioPatientPHI":
        """Reconstruct from a dict of encrypted field values."""
        return cls(
            mrn=decrypt_phi_field(fields["patient_mrn_encrypted"]),
            name=(
                decrypt_phi_field(fields["patient_name_encrypted"])
                if fields.get("patient_name_encrypted")
                else ""
            ),
            dob=(
                decrypt_phi_field(fields["patient_dob_encrypted"])
                if fields.get("patient_dob_encrypted")
                else ""
            ),
            contact=(
                decrypt_phi_field(fields["patient_contact_encrypted"])
                if fields.get("patient_contact_encrypted")
                else ""
            ),
        )

    @property
    def masked_mrn(self) -> str:
        return mask_mrn(self.mrn)

    @property
    def masked_name(self) -> str:
        return mask_name(self.name)