HIPAA Testing for Healthcare Software

HIPAA Testing for Healthcare Software

HIPAA compliance is not a checkbox exercise. The Health Insurance Portability and Accountability Act imposes enforceable technical, administrative, and physical safeguards on any organization that handles Protected Health Information (PHI). Violations carry civil penalties from $100 to $50,000 per violation, with annual maximums reaching $1.9 million per violation category. Criminal violations can result in prison.

For engineering teams, compliance translates into a set of verifiable technical requirements. This guide covers how to test those requirements — from PHI handling and encryption to audit logs and access controls — with practical code examples you can integrate into your CI pipeline.

What Counts as PHI?

Before writing a single test, your team needs to agree on what constitutes PHI in your system. HIPAA defines 18 identifiers that, when linked to health information, become PHI:

Category Examples
Direct identifiers Name, address, SSN, phone, email, MRN, account numbers
Geographic ZIP codes smaller than first 3 digits, dates of birth, admission/discharge dates
Biometric Fingerprints, retinal scans, voice recordings
Device identifiers Serial numbers, IP addresses
Photos Full-face photographs
Unique identifiers URLs, license plate numbers

Data that passes through your system without any of these 18 identifiers is de-identified and no longer subject to HIPAA. De-identification is a compliance strategy, but it must be tested rigorously.

The HIPAA Security Rule: Technical Safeguards

The Security Rule (45 CFR §164.312) specifies required and addressable technical safeguards. Required means mandatory; addressable means you must implement it or document a reasonable alternative.

Safeguard Status What to Test
Access control (unique user IDs) Required Each user has unique credentials; shared logins blocked
Emergency access procedure Required Break-glass access works and is logged
Automatic logoff Addressable Session expires after inactivity
Encryption and decryption Addressable PHI encrypted at rest and in transit
Audit controls Required All PHI access logged with user, timestamp, action
Integrity controls Addressable PHI not altered in transit (checksums, MACs)
Transmission security Required TLS enforced for all PHI in transit

Testing Encryption

Verifying TLS Configuration

# tests/compliance/test_tls.py
import ssl
import socket
import pytest

HEALTHCARE_ENDPOINTS = [
    ('api.example.com', 443),
    ('app.example.com', 443),
]

@pytest.mark.parametrize('host,port', HEALTHCARE_ENDPOINTS)
def test_tls_minimum_version(host, port):
    """Verify TLS 1.2+ is enforced — HIPAA requires strong encryption."""
    context = ssl.create_default_context()
    context.minimum_version = ssl.TLSVersion.TLSv1_2

    with socket.create_connection((host, port), timeout=10) as sock:
        with context.wrap_socket(sock, server_hostname=host) as ssock:
            version = ssock.version()
            assert version in ('TLSv1.2', 'TLSv1.3'), (
                f"Expected TLS 1.2+, got {version} on {host}:{port}"
            )

@pytest.mark.parametrize('host,port', HEALTHCARE_ENDPOINTS)
def test_tls_1_0_rejected(host, port):
    """Verify TLS 1.0 connections are rejected."""
    context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
    context.maximum_version = ssl.TLSVersion.TLSv1
    context.check_hostname = False
    context.verify_mode = ssl.CERT_NONE

    with pytest.raises((ssl.SSLError, ConnectionResetError, OSError)):
        with socket.create_connection((host, port), timeout=5) as sock:
            with context.wrap_socket(sock, server_hostname=host):
                pass

def test_certificate_not_expired():
    """Verify SSL certificate is valid and not expired."""
    context = ssl.create_default_context()
    host = 'api.example.com'

    with socket.create_connection((host, 443), timeout=10) as sock:
        with context.wrap_socket(sock, server_hostname=host) as ssock:
            cert = ssock.getpeercert()
            # If this doesn't raise, the cert is valid (ssl module verifies expiry)
            assert cert is not None
            assert cert.get('subject') is not None

Verifying Encryption at Rest

# tests/compliance/test_encryption_at_rest.py
import boto3
import pytest

def test_s3_bucket_encryption():
    """Verify S3 buckets storing PHI have server-side encryption enabled."""
    s3 = boto3.client('s3', region_name='us-east-1')
    phi_buckets = ['my-app-phi-documents', 'my-app-medical-records']

    for bucket_name in phi_buckets:
        response = s3.get_bucket_encryption(Bucket=bucket_name)
        rules = response['ServerSideEncryptionConfiguration']['Rules']
        assert len(rules) > 0, f"No encryption configured on {bucket_name}"

        sse = rules[0]['ApplyServerSideEncryptionByDefault']
        algo = sse['SSEAlgorithm']
        assert algo in ('aws:kms', 'AES256'), (
            f"Bucket {bucket_name} uses weak or no encryption: {algo}"
        )

def test_rds_encryption():
    """Verify RDS instances storing PHI have encryption enabled."""
    rds = boto3.client('rds', region_name='us-east-1')
    response = rds.describe_db_instances()

    phi_instances = ['prod-healthcare-db', 'staging-healthcare-db']

    for instance in response['DBInstances']:
        if instance['DBInstanceIdentifier'] in phi_instances:
            assert instance['StorageEncrypted'], (
                f"RDS instance {instance['DBInstanceIdentifier']} is NOT encrypted"
            )

def test_ebs_volumes_encrypted():
    """Verify EBS volumes on PHI servers are encrypted."""
    ec2 = boto3.client('ec2', region_name='us-east-1')
    response = ec2.describe_volumes(
        Filters=[{'Name': 'tag:Environment', 'Values': ['production']}]
    )

    for volume in response['Volumes']:
        assert volume['Encrypted'], (
            f"EBS volume {volume['VolumeId']} is not encrypted"
        )

Audit Logging Tests

HIPAA requires audit logs of all access to PHI — who accessed what, when, and what action was taken. This is non-negotiable.

Log Structure Verification

// tests/compliance/audit-log.test.ts
import request from 'supertest';
import { app } from '../../src/app';
import { db } from '../../src/db';

describe('HIPAA Audit Logging', () => {
  let authToken: string;

  beforeAll(async () => {
    const res = await request(app)
      .post('/auth/login')
      .send({ username: 'clinician@example.com', password: 'TestPass123!' });
    authToken = res.body.token;
  });

  it('should log PHI read access with required fields', async () => {
    const patientId = 'patient-uuid-123';

    await request(app)
      .get(`/api/patients/${patientId}`)
      .set('Authorization', `Bearer ${authToken}`)
      .expect(200);

    // Verify audit log entry was created
    const auditEntry = await db('audit_logs')
      .where({ resource_id: patientId, action: 'READ' })
      .orderBy('created_at', 'desc')
      .first();

    expect(auditEntry).toBeDefined();
    expect(auditEntry.user_id).toBeTruthy();       // WHO
    expect(auditEntry.resource_type).toBe('Patient'); // WHAT
    expect(auditEntry.resource_id).toBe(patientId);
    expect(auditEntry.action).toBe('READ');
    expect(auditEntry.created_at).toBeTruthy();    // WHEN
    expect(auditEntry.ip_address).toBeTruthy();    // FROM WHERE
    expect(auditEntry.user_agent).toBeTruthy();
  });

  it('should log PHI modification with before/after state', async () => {
    const patientId = 'patient-uuid-123';

    await request(app)
      .patch(`/api/patients/${patientId}`)
      .set('Authorization', `Bearer ${authToken}`)
      .send({ phone: '555-0199' })
      .expect(200);

    const auditEntry = await db('audit_logs')
      .where({ resource_id: patientId, action: 'UPDATE' })
      .orderBy('created_at', 'desc')
      .first();

    expect(auditEntry.action).toBe('UPDATE');
    expect(auditEntry.changed_fields).toContain('phone');
  });

  it('should log failed access attempts', async () => {
    const patientId = 'patient-uuid-456'; // patient not in clinician's care

    await request(app)
      .get(`/api/patients/${patientId}`)
      .set('Authorization', `Bearer ${authToken}`)
      .expect(403);

    const auditEntry = await db('audit_logs')
      .where({ resource_id: patientId, action: 'READ_DENIED' })
      .orderBy('created_at', 'desc')
      .first();

    expect(auditEntry).toBeDefined();
    expect(auditEntry.outcome).toBe('DENIED');
  });

  it('should not allow audit logs to be deleted via API', async () => {
    await request(app)
      .delete('/api/audit-logs/some-log-id')
      .set('Authorization', `Bearer ${authToken}`)
      .expect(404); // endpoint should not exist
  });
});

Access Control Testing

HIPAA requires unique user identification and role-based access controls. Minimum necessary access is a core principle — users should only see PHI relevant to their role.

// tests/compliance/access-control.test.ts
import request from 'supertest';
import { app } from '../../src/app';

describe('HIPAA Access Controls — Minimum Necessary', () => {
  const credentials = {
    admin: { username: 'admin@example.com', password: 'AdminPass123!' },
    clinician: { username: 'dr.smith@example.com', password: 'ClinicianPass123!' },
    billing: { username: 'billing@example.com', password: 'BillingPass123!' },
    receptionist: { username: 'reception@example.com', password: 'ReceptionPass123!' },
  };

  async function getToken(role: keyof typeof credentials) {
    const res = await request(app)
      .post('/auth/login')
      .send(credentials[role]);
    return res.body.token;
  }

  it('billing staff cannot access clinical notes', async () => {
    const token = await getToken('billing');

    await request(app)
      .get('/api/patients/patient-123/clinical-notes')
      .set('Authorization', `Bearer ${token}`)
      .expect(403);
  });

  it('receptionist cannot access medication records', async () => {
    const token = await getToken('receptionist');

    await request(app)
      .get('/api/patients/patient-123/medications')
      .set('Authorization', `Bearer ${token}`)
      .expect(403);
  });

  it('clinician can only access their own patients', async () => {
    const token = await getToken('clinician');

    // Patient assigned to a different clinician
    await request(app)
      .get('/api/patients/patient-999/medical-history')
      .set('Authorization', `Bearer ${token}`)
      .expect(403);
  });

  it('unauthenticated requests are rejected', async () => {
    await request(app)
      .get('/api/patients/patient-123')
      .expect(401);
  });

  it('sessions expire after configured inactivity period', async () => {
    // This test would typically use a mock clock or a short-lived test token
    const expiredToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyLTEiLCJleHAiOjE2MDAwMDAwMDB9.invalid';

    await request(app)
      .get('/api/patients/patient-123')
      .set('Authorization', `Bearer ${expiredToken}`)
      .expect(401);
  });
});

PHI Leakage Prevention

PHI must not appear in logs, error messages, URLs, or any channel that lacks PHI-appropriate controls.

// tests/compliance/phi-leakage.test.ts
import request from 'supertest';
import { app } from '../../src/app';
import * as logger from '../../src/logger';

describe('PHI Leakage Prevention', () => {
  it('SSN should not appear in API error responses', async () => {
    const res = await request(app)
      .post('/api/patients')
      .send({
        name: 'John Doe',
        ssn: '123-45-6789',
        dob: '1980-01-01',
      })
      .expect(400); // validation error for missing required field

    // SSN should not be echoed back in the error
    expect(JSON.stringify(res.body)).not.toContain('123-45-6789');
  });

  it('PHI should not appear in application logs', async () => {
    const logSpy = jest.spyOn(logger, 'info');

    await request(app)
      .get('/api/patients/patient-123')
      .set('Authorization', 'Bearer valid-token');

    const allLogMessages = logSpy.mock.calls
      .map(call => JSON.stringify(call))
      .join(' ');

    // Verify no SSN patterns in logs
    expect(allLogMessages).not.toMatch(/\d{3}-\d{2}-\d{4}/);
    // Verify no full names from PHI in logs
    expect(allLogMessages).not.toContain('John Doe');
  });

  it('PHI should not appear in URL parameters', async () => {
    // PHI in URLs ends up in web server logs, browser history, and referrer headers
    // Verify the API does not accept PHI in query params
    const res = await request(app)
      .get('/api/patients?ssn=123-45-6789')
      .set('Authorization', 'Bearer valid-token');

    // Should either 400 (bad request) or return empty results, not match by SSN
    expect(res.status).not.toBe(200);
  });
});

Penetration Testing for HIPAA

HIPAA does not mandate penetration testing by name, but the Security Rule's risk analysis requirement (§164.308(a)(1)) effectively requires it. Automated scanners are a starting point; manual pen testing by a qualified assessor is needed for serious compliance.

# OWASP ZAP automated scan targeting your healthcare API
docker run -v $(pwd):/zap/wrk:rw \
  ghcr.io/zaproxy/zaproxy:stable zap-api-scan.py \
  -t http://api.example.com/openapi.json \
  -f openapi \
  -r zap-report.html \
  -x zap-report.xml

# Nuclei — template-based scanner with HIPAA-relevant checks
nuclei -u https://api.example.com \
  -t nuclei-templates/misconfiguration/ \
  -t nuclei-templates/vulnerabilities/ \
  -severity critical,high \
  -o nuclei-results.txt

CI Integration for Security Scanning

# .github/workflows/hipaa-security.yml
name: HIPAA Security Checks

on:
  pull_request:
  schedule:
    - cron: '0 2 * * 1'  # Weekly Monday 2am

jobs:
  tls-check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install testssl.sh
        run: |
          git clone --depth 1 https://github.com/drwetter/testssl.sh.git
      - name: Check TLS configuration
        run: |
          ./testssl.sh/testssl.sh --severity HIGH --json \
            api.example.com:443 > tls-results.json
      - name: Fail on critical TLS issues
        run: |
          python3 -c "
          import json, sys
          with open('tls-results.json') as f:
            results = json.load(f)
          critical = [r for r in results if r.get('severity') == 'CRITICAL']
          if critical:
            print('CRITICAL TLS issues found:')
            for r in critical:
              print(f'  {r[\"id\"]}: {r[\"finding\"]}')
            sys.exit(1)
          "

  dependency-audit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
      - run: npm audit --audit-level=high

BAA and Vendor Compliance Testing

If your application uses third-party services that process PHI (cloud storage, email, analytics), you must have a Business Associate Agreement (BAA) with each vendor. Testing this is contractual, not technical, but you can automate the check for known non-BAA services appearing in your infrastructure:

# tests/compliance/test_third_party.py
import re

# Services known NOT to offer HIPAA BAAs (as of 2024)
NON_HIPAA_SERVICES = [
    'analytics.google.com',
    'hotjar.com',
    'fullstory.com',  # Requires HIPAA BAA plan
    'mixpanel.com',
    'amplitude.com',  # Requires HIPAA agreement
]

def test_no_non_hipaa_services_in_phi_pages():
    """Verify PHI-containing pages don't load non-HIPAA-compliant third parties."""
    # This would normally run via a browser and check network requests
    # Here we check the frontend source for references
    with open('src/pages/patient-dashboard.tsx', 'r') as f:
        source = f.read()

    for service in NON_HIPAA_SERVICES:
        assert service not in source, (
            f"Non-HIPAA service {service} referenced in PHI page. "
            f"Verify BAA exists or remove the integration."
        )

Building Your HIPAA Test Suite

A complete HIPAA technical testing program covers these areas on a recurring basis:

  1. Continuous (every commit) — PHI leakage in logs, access control unit tests, input validation
  2. Every PR — audit log structure, encryption configuration checks, OWASP dependency audit
  3. Weekly — TLS/certificate validation, full authentication flow tests, session management
  4. Quarterly — Penetration testing, access control review (are former employees deprovisioned?), backup encryption verification
  5. Annual — Third-party risk assessment, BAA review, full security risk analysis per §164.308(a)(1)

HIPAA compliance is a continuous process. Automated testing catches regressions early. Manual review catches what automation misses. Documentation — test results, risk analyses, policies — is what auditors actually examine. All three are required.

Read more

Start now free