Skip to main content

Technical Safeguards

1. Access Control (§164.312(a)(1))

Requirement: Implement technical policies and procedures for electronic information systems that maintain ePHI to allow access only to those persons or software programs that have been granted access rights.

MCP Server Implementation

  • Authentication
  • Authorization
  • Session Management
JWT-Based Authentication:
# config/auth.yaml
authentication:
  jwt:
    enabled: true
    secret: ${JWT_SECRET}  # Stored in Infisical
    issuer: "mcp-server-prod"
    audience: "healthcare-agents"
    expiration: 3600  # 1 hour
    refresh_enabled: true
    refresh_expiration: 86400  # 24 hours

  mfa:
    enabled: true  # REQUIRED for HIPAA
    providers:
      - totp
      - webauthn
    grace_period: 0  # No grace period
Keycloak SSO Integration:
# config/keycloak.yaml
keycloak:
  realm: healthcare
  server_url: https://auth.healthcare.example.com
  client_id: mcp-server
  client_secret: ${KEYCLOAK_CLIENT_SECRET}

  # HIPAA requirements
  require_mfa: true
  session_timeout: 900  # 15 minutes
  idle_timeout: 300  # 5 minutes
  max_sessions_per_user: 1  # Single session

2. Audit Controls (§164.312(b))

Requirement: Implement hardware, software, and/or procedural mechanisms that record and examine activity in information systems that contain or use ePHI.

Comprehensive Audit Logging

  • Audit Log Configuration
  • Audit Log Format
  • Audit Query Examples
# config/audit.yaml
audit_logging:
  enabled: true
  retention_days: 2555  # 7 years (HIPAA requirement)

  events:
    # Authentication events
    - user_login
    - user_logout
    - failed_login_attempt
    - mfa_challenge
    - password_reset

    # Authorization events
    - phi_access_granted
    - phi_access_denied
    - permission_change

    # Data events
    - phi_read
    - phi_create
    - phi_update
    - phi_delete
    - phi_export

    # System events
    - configuration_change
    - user_created
    - user_deleted
    - role_assigned

  output:
    - type: postgresql
      table: audit_logs
      encrypted: true

    - type: siem
      endpoint: https://siem.healthcare.example.com
      protocol: syslog

    - type: s3
      bucket: hipaa-audit-logs
      encryption: AES-256
      lifecycle: 2555_days

3. Integrity Controls (§164.312(c)(1))

Requirement: Implement policies and procedures to protect ePHI from improper alteration or destruction.

Data Integrity Implementation

# src/middleware/integrity.py
import hashlib
import hmac
from datetime import datetime

class DataIntegrityMiddleware:
    """Ensure PHI integrity with cryptographic hashing."""

    def compute_integrity_hash(self, data: dict, secret: bytes) -> str:
        """Compute HMAC-SHA256 hash of PHI data."""
        canonical = json.dumps(data, sort_keys=True)
        return hmac.new(secret, canonical.encode(), hashlib.sha256).hexdigest()

    async def store_phi(self, patient_id: str, data: dict):
        """Store PHI with integrity hash."""
        # Compute integrity hash
        integrity_hash = self.compute_integrity_hash(
            data,
            secret=self.get_secret_key()
        )

        # Store with metadata
        record = {
            "patient_id": patient_id,
            "data": data,
            "integrity_hash": integrity_hash,
            "created_at": datetime.utcnow().isoformat(),
            "created_by": self.current_user.id,
            "version": 1
        }

        await self.db.medical_records.insert_one(record)
        return record

    async def verify_phi_integrity(self, record: dict) -> bool:
        """Verify PHI has not been tampered with."""
        stored_hash = record.get("integrity_hash")
        computed_hash = self.compute_integrity_hash(
            record["data"],
            secret=self.get_secret_key()
        )

        if stored_hash != computed_hash:
            # Log integrity violation
            await self.audit_log.critical(
                event="integrity_violation",
                record_id=record["_id"],
                patient_id=record["patient_id"]
            )
            return False

        return True

4. Transmission Security (§164.312(e)(1))

Requirement: Implement technical security measures to guard against unauthorized access to ePHI that is being transmitted over an electronic communications network.

Encryption in Transit

# config/tls.yaml
tls:
  # Require TLS 1.3 (HIPAA best practice)
  min_version: "1.3"
  cipher_suites:
    - TLS_AES_256_GCM_SHA384
    - TLS_CHACHA20_POLY1305_SHA256
    - TLS_AES_128_GCM_SHA256

  # Certificate management
  cert_file: /secrets/tls/cert.pem
  key_file: /secrets/tls/key.pem
  ca_file: /secrets/tls/ca.pem

  # mTLS for service-to-service
  mutual_tls:
    enabled: true
    verify_client_cert: true
    allowed_dns_names:
      - "*.healthcare.example.com"

# Kubernetes Ingress
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: mcp-server-hipaa
  annotations:
    nginx.ingress.kubernetes.io/ssl-protocols: "TLSv1.3"
    nginx.ingress.kubernetes.io/ssl-ciphers: "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256"
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
spec:
  tls:
    - hosts:
        - agents.healthcare.example.com
      secretName: tls-cert

5. Encryption at Rest (§164.312(a)(2)(iv))

Requirement: Implement a mechanism to encrypt and decrypt ePHI (addressable).

Database Encryption

# PostgreSQL encryption configuration
# postgresql.conf
ssl = on
ssl_cert_file = '/var/lib/postgresql/server.crt'
ssl_key_file = '/var/lib/postgresql/server.key'
ssl_ca_file = '/var/lib/postgresql/root.crt'

# Enable transparent data encryption (TDE)
# For Google Cloud SQL
resource "google_sql_database_instance" "hipaa_db" {
  name = "mcp-server-hipaa"

  settings {
    tier = "db-n1-standard-4"

    # Encryption at rest
    database_flags {
      name  = "cloudsql.enable_pgaudit"
      value = "on"
    }

    backup_configuration {
      enabled = true
      binary_log_enabled = false  # PostgreSQL
      point_in_time_recovery_enabled = true
    }

    # Encrypt backups
    disk_encryption_configuration {
      kms_key_name = "projects/PROJECT_ID/locations/us-central1/keyRings/hipaa/cryptoKeys/phi-db"
    }
  }
}

Application-Level Encryption

# src/encryption/phi_encryption.py
from cryptography.fernet import Fernet
from typing import Any, Dict

class PHIEncryption:
    """Application-level encryption for sensitive PHI fields."""

    def __init__(self, encryption_key: bytes):
        self.cipher = Fernet(encryption_key)

    def encrypt_sensitive_fields(self, record: Dict[str, Any]) -> Dict[str, Any]:
        """Encrypt sensitive PHI fields before storage."""
        sensitive_fields = [
            "ssn",
            "date_of_birth",
            "medical_record_number",
            "diagnosis",
            "medications",
            "test_results"
        ]

        encrypted_record = record.copy()

        for field in sensitive_fields:
            if field in record and record[field]:
                # Encrypt field value
                plaintext = json.dumps(record[field]).encode()
                encrypted = self.cipher.encrypt(plaintext)
                encrypted_record[field] = {
                    "_encrypted": True,
                    "_value": encrypted.decode()
                }

        return encrypted_record

    def decrypt_sensitive_fields(self, record: Dict[str, Any]) -> Dict[str, Any]:
        """Decrypt sensitive PHI fields after retrieval."""
        decrypted_record = record.copy()

        for field, value in record.items():
            if isinstance(value, dict) and value.get("_encrypted"):
                # Decrypt field value
                encrypted = value["_value"].encode()
                plaintext = self.cipher.decrypt(encrypted)
                decrypted_record[field] = json.loads(plaintext)

        return decrypted_record

Next Steps