FHIR Compartment Validation in Medbackend
Core Concept: Logical Resource Grouping
FHIR compartments provide virtual resource organization without physical storage changes. Think of them as dynamic filters that:
- Group related resources through reference relationships
- Enable context-specific access control
- Maintain original resource locations while creating logical views
FHIR Compartment Fundamentals
Key Characteristics
- Reference-Based Membership
Resources join compartments through specific reference fields (e.g.,subject,patient) - Multi-Compartment Resources
A single resource can exist in multiple compartments simultaneously - Dynamic Membership
Compartment relationships update automatically with resource modifications
Common Compartment Types
| Compartment | Reference Path | Example Resources |
|---|---|---|
| Patient | subject | ServiceRequest, CarePlan |
| Practitioner | performer | Observation, Procedure |
| Device | device | DeviceMetric, DeviceUseStatement |
Medbackend Validation Implementation
Configuration Example
{
"client_role": "Patient",
"entity_name": "Observation",
"operation": "read",
"validator": "Patient_compartment",
"reference_paths": [
"subject.reference",
"requester.reference"
]
}
Configuration Breakdown:
client_role: Authenticated user type (Patient, Practitioner)entity_name: FHIR resource to validateoperation: CRUD operation being performedvalidator: Compartment validation strategyreference_paths: JSON paths to check for client ID matches
Validation Workflow
- Extract client identity from authentication token
- Parse requested resource ID/body
- Check reference paths for client ID presence
- Verify at least one matching reference exists
- Allow/deny based on compartment membership
Example Scenario:
# Patient 12345 requests ServiceRequest/67890
def validate_request(resource, client):
references = [
resource.get('subject', {}).get('reference'),
resource.get('requester', {}).get('reference')
]
return any(ref == client.reference for ref in references)
# Returns True if ServiceRequest references Patient/12345
Advanced Compartment Patterns
Cross-Compartment Access
{
"client_role": "Practitioner",
"entity_name": "Observation",
"operation": "write",
"validators": [
"Practitioner_compartment",
"Patient_compartment"
],
"validation_logic": "any"
}
This configuration allows access if the Observation belongs to either the Practitioner's compartment or their Patient's compartment.
Nested References
Handle complex resource relationships:
{
"reference_paths": [
"subject.reference",
"basedOn.reference", # Chain through ServiceRequest
"encounter.reference" # Link via Encounter
]
}
Troubleshooting Compartment Validation
Common Issues:
-
Missing References
{"error": "No compartment references found in ServiceRequest/abc123"}Solution: Verify reference paths match resource structure
-
Cross-Tenant Access
{"error": "Patient/12345 not authorized for CarePlan/xyz789"}Solution: Check resource references across organizational boundaries