Security Best Practices
This guide covers security configuration for production deployments of OctoFHIR.
Authentication Overview
Section titled “Authentication Overview”OctoFHIR implements OAuth 2.0 and SMART on FHIR for authentication and authorization:
- OAuth 2.0 - Industry standard authorization framework
- SMART on FHIR - Healthcare-specific OAuth 2.0 profile
- Policy Engine - Fine-grained access control with JavaScript policies
TLS Configuration
Section titled “TLS Configuration”Nginx Example
Section titled “Nginx Example”server { listen 443 ssl http2; server_name fhir.example.com;
ssl_certificate /etc/letsencrypt/live/fhir.example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/fhir.example.com/privkey.pem; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
location / { proxy_pass http://127.0.0.1:8888; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; }}Caddy Example
Section titled “Caddy Example”fhir.example.com { reverse_proxy localhost:8888}OAuth 2.0 Configuration
Section titled “OAuth 2.0 Configuration”Secure Token Settings
Section titled “Secure Token Settings”[auth]# Must match your public URLissuer = "https://fhir.example.com"
[auth.oauth]# Short-lived access tokensaccess_token_lifetime = "15m"# Longer refresh tokens for UXrefresh_token_lifetime = "7d"# Only allow needed grant typesgrant_types = ["authorization_code", "refresh_token"]JWT Key Management
Section titled “JWT Key Management”For production, configure persistent signing keys:
-
Generate RSA keys
Terminal window # Generate private key (PKCS#8 format required)openssl genpkey -algorithm RSA -out private.pem -pkeyopt rsa_keygen_bits:3072# Extract public keyopenssl rsa -in private.pem -pubout -out public.pem -
Configure in octofhir.toml
[auth.signing]algorithm = "RS384"kid = "prod-key-2024"private_key_pem = """-----BEGIN PRIVATE KEY-----...-----END PRIVATE KEY-----"""public_key_pem = """-----BEGIN PUBLIC KEY-----...-----END PUBLIC KEY-----""" -
Or use environment variables
Terminal window OCTOFHIR__AUTH__SIGNING__PRIVATE_KEY_PEM="$(cat private.pem)"OCTOFHIR__AUTH__SIGNING__PUBLIC_KEY_PEM="$(cat public.pem)"
SMART on FHIR Setup
Section titled “SMART on FHIR Setup”Client Registration
Section titled “Client Registration”Register OAuth clients for your applications:
Clients are internal resources, served at the root rather than under /fhir:
curl -X POST https://fhir.example.com/Client \ -H "Authorization: Bearer $ADMIN_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "resourceType": "Client", "clientId": "my-ehr-app", "clientSecret": "change-me", "name": "My EHR Application", "redirectUris": ["https://app.example.com/callback"], "grantTypes": ["authorization_code", "refresh_token"], "scopes": ["openid", "fhirUser", "launch/patient", "patient/*.read"], "confidential": true, "active": true }'The server stores clientSecret as a hash.
Confidential vs Public Clients
Section titled “Confidential vs Public Clients”| Client Type | Use Case | Auth Method |
|---|---|---|
| Confidential | Server-side apps | client_secret_basic or private_key_jwt |
| Public | SPAs, mobile apps | PKCE required |
[auth.smart]# Production: disable public clients or require PKCEpublic_clients_allowed = falseconfidential_symmetric_allowed = trueconfidential_asymmetric_allowed = truePassword Guessing
Section titled “Password Guessing”After 5 failed attempts a username or client id is refused for 5 minutes, with 429 and
Retry-After, even with the right password. See Lockout.
Access Policies
Section titled “Access Policies”OctoFHIR uses a policy engine for fine-grained access control.
Default Deny
Section titled “Default Deny”A request that no policy allows is denied. This cannot be configured.
Example Policies
Section titled “Example Policies”Scripts see the request as the globals user, client, scopes, request, resource and
environment, and return allow(), deny(reason) or abstain(). See
Access Policies.
Admin Full Access:
// Policy: admin-full-accessif (hasRole('admin')) { return allow();}return abstain();Patient Compartment Access:
// Policy: patient-compartmentif (!isPatientUser()) { return abstain();}if (request.resourceType === 'Patient' && request.resourceId === user.fhirUserId) { return allow();}if (inPatientCompartment()) { return allow();}return deny('Access denied to this patient data');Read-Only for Researchers:
// Policy: researcher-readonlyif (hasRole('researcher') && request.method === 'GET') { return allow();}return abstain();Outbound Requests
Section titled “Outbound Requests”API clients choose some of the URLs the server calls: subscription rest-hook endpoints, $import
source URLs and $bulk-submit file URLs.
Private addresses are allowed by default, so that local setups work. The risk: a client with the right to start such a job can make the server call internal services and the cloud metadata endpoint. Shared or production deployments should set this:
[server]allow_private_outbound = falseSee Outbound requests.
Session Security
Section titled “Session Security”[auth.session]# Idle timeout (sliding window)idle_timeout = "15m"# Absolute timeout (max session length)absolute_timeout = "8h"
[auth.cookie]secure = true # HTTPS onlyhttp_only = true # No JavaScript accesssame_site = "strict" # CSRF protectionAudit Logging
Section titled “Audit Logging”Enable comprehensive audit trails:
[audit]enabled = truelog_fhir_operations = truelog_auth_events = truelog_read_operations = truelog_search_operations = trueAudit events are stored as AuditEvent resources and can be queried:
curl "https://fhir.example.com/fhir/AuditEvent?date=gt2024-01-01&_count=100" \ -H "Authorization: Bearer $ADMIN_TOKEN"Validation Security
Section titled “Validation Security”[validation]# Disable skip validation in productionallow_skip_validation = falseDatabase Security
Section titled “Database Security”Connection Security
Section titled “Connection Security”[storage.postgres]# Use SSL for database connectionsurl = "postgres://user:pass@db.example.com:5432/octofhir?sslmode=require"Principle of Least Privilege
Section titled “Principle of Least Privilege”Create a dedicated database user with minimal permissions:
CREATE USER octofhir_app WITH PASSWORD 'secure-password';GRANT CONNECT ON DATABASE octofhir TO octofhir_app;GRANT USAGE ON SCHEMA public TO octofhir_app;GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO octofhir_app;GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO octofhir_app;Production Checklist
Section titled “Production Checklist”- TLS/HTTPS - Always use HTTPS with TLS 1.2+
- Credentials - Change all default passwords
- JWT Keys - Configure persistent signing keys
- Cookies - Set
secure = trueandsame_site = "strict" - Outbound Requests - Set
allow_private_outbound = false - Audit Logging - Enable audit trail
- Validation - Disable skip validation header
- GraphQL - Disable introspection
- Database - Use SSL connections
- Secrets - Use environment variables for sensitive config
Security Headers
Section titled “Security Headers”Configure your reverse proxy to add security headers:
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;add_header X-Content-Type-Options "nosniff" always;add_header X-Frame-Options "DENY" always;add_header X-XSS-Protection "1; mode=block" always;add_header Content-Security-Policy "default-src 'self'" always;Reporting Security Issues
Section titled “Reporting Security Issues”If you discover a security vulnerability, please report it privately:
- Email: security@octofhir.io
- Do not create public GitHub issues for security vulnerabilities