Role-Based Access Control (RBAC) Implementation Guide
Core Concepts
Medbackend's FHIR-based RBAC system provides granular access control through configurable validation rules. Key principles:
- Compartment-based security: Automatic filtering of resources based on patient/practitioner/organization relationships
- Zero-trust default: "Forbidden" baseline with explicit access grants
- Context-aware validation: Dynamic request modification to enforce access policies
- Multi-tenancy support: Built-in isolation mechanisms for organizational data separation
Request Validation Workflow
The order in which a request is checked, from token to returned rows, is drawn on How access is decided. The components it passes through:
Critical Components:
- Identity provider: issues the access token and the claims that name the caller. By default this is the MedBackend OAuth service, scoped per project; any OIDC provider you point the JWKS URL at works the same way.
- JWT validation: verifies the token signature against the provider's published JWKS, then reads the caller's role and identity from the claims.
- FHIR RBAC engine: matches the request against the project's validation rules and runs the validator each matching rule names.
- Query handler: narrows searches at the FHIR server where it can, and re-checks every returned row against the same validator.
Validator Types & Strategies
Compartment Validators
The write fields column is exact and it matters more than it looks. On create and update, a compartment validator requires the submitted payload to reference the caller in at least one of these fields — no other field will satisfy it, however sensible it looks in FHIR terms. See What a compartment validator asks of a write below.
| Validator | Scope | Write fields (payload must reference the caller in one of these) | Typical Use | FHIR References |
|---|---|---|---|---|
patient_compartment | Direct patient ownership | subject, patient, performer | Patient portals | Patient Compartment |
practitioner_compartment | Clinical staff context | practitioner, performer, requester | EHR access | Practitioner Role |
relatedperson_compartment | Family/caregiver relationships | subject, actor, requester | Family portals | RelatedPerson |
device_compartment | Device-generated data | device, subject, performer | IoT / remote monitoring | Device Compartment |
On read and search, the compartment membership question is asked of the row the server returned, using the inclusion criteria the FHIR compartment definition specifies for that resource type — not the write-field list above. The two lists overlap but are not the same, and a resource can be readable under a compartment yet impossible to create under it.
Specialized Validators
| Validator | Purpose | Use Case Example |
|---|---|---|
organization_compartment | Organization-associated resources | Multi-tenant systems |
organization_consent | Organization membership AND active consent naming the caller | Consent-gated multi-tenant access |
legitimate_interest | GDPR-compliant access without explicit consent | Emergency access |
general_practitioner | Verified practitioner-patient relationships | Primary care coordination |
allowed/forbidden | Explicit access override | Public APIs/Admin interfaces |
device_compartment | Device-linked resources | IoT/remote monitoring |
Implementation Examples
Patient Compartment Rule
{
"client_role": "Patient",
"entity_name": "Observation",
"operation": "search",
"validator": "patient_compartment"
}
Query Transformation:
# Original Query
query {
Observation { id }
}
# Modified Execution
query {
Observation(subject: "Patient/123") { id }
}
Practitioner Role Restriction
{
"client_role": "Practitioner",
"entity_name": "Patient",
"operation": "search",
"validator": "legitimate_interest",
"required_role_system": "http://terminology.hl7.org/CodeSystem/practitioner-role",
"required_role_code": "doctor"
}
required_role_system and required_role_code are optional, and they are top-level keys on the rule — not nested inside a params object. When both are present and the caller is a practitioner, MedBackend looks up the caller's PractitionerRole resources and grants only if some code.coding entry matches both halves exactly. A triple may carry one such rule per role, each with its own validator; how they combine is in Several roles on one triple.
Getting either of those wrong fails in opposite directions, so it matters which:
- A rule carrying one key without the other denies every practitioner. It is unusable, not ungated. (This reversed in 2026; documentation written before the change says such a rule is ignored.)
- Keys nested inside
paramsare not read at all, so the rule declares no role requirement and grants every caller the validator allows. This is the one that gives access away.
Saving a rule rejects a nested pair; publishing the project rejects a half pair and a code HL7's CodeSystem does not define. A configuration that reached the platform without going through either — written straight into a settings.json, say — is reported when it is loaded, and may prevent it loading at all. See Requiring a Practitioner Role for the full set of conditions and what each does when unmet.
The gate applies to whichever validator the rule names, including allowed. It runs before the validator does.
required_role_system is compared against PractitionerRole.code.coding.system in your live FHIR data, and FHIR defines that element as the code system that defines the code. For HL7's practitioner roles the correct value is http://terminology.hl7.org/CodeSystem/practitioner-role; for SNOMED-coded roles it is http://snomed.info/sct.
http://hl7.org/fhir/ValueSet/practitioner-role is the ValueSet canonical — a selection of codes, not a definition of them — and http://hl7.org/fhir/R4/valueset-practitioner-role is the documentation page URL and identifies nothing. Either one will match only data written with the same non-conformant string, so the rule denies every conformant caller, silently and forever. Nothing validates the value at load time, and the failure is indistinguishable at runtime from correct strict enforcement.
Configuration Strategy
Default Access Configuration
{
"rbac": {
"default_access": "Forbidden",
"validation_rules": [
// Role-specific rules
]
}
}
Security Recommendations:
default_accessis recognised as exactly one of two values:"Forbidden"or"Allowed". Both are compared literally, so both are case-sensitive.- Use
"Forbidden". Access is granted only by a rule matching the caller's role, the resource and the operation; a triple with no rule is denied. - Do not set
"Allowed". It applies only where no rule matches; where a rule exists that rule decides, for every operation. Where none matches, areadorsearchis granted outright and a write is granted too, reaching only three narrow structural checks — anid-collision refusal oncreate, a referent check ondeletethat coversPatient,Practitioner,RelatedPersonandDeviceonly, and onupdatea re-check against the granting rule, which for an unruled write is nothing at all. New configurations carrying it are refused at publish time, but that is not retroactive. - Spell the value exactly.
"forbidden","Allow"and"Forbidden "are all different from"Forbidden", and none of them is a valid configuration. Publishing rejects an unrecognised value with a400before it reaches storage, so a misspelling is caught at that point rather than silently at request time.python -m json.tool settings.jsoncatches a malformed document, but not a well-formed one with the wrong string in it.
Rule Definition Structure
{
"client_role": "<RoleName>",
"entity_name": "<FHIRResource>",
"operation": "<search|create|read|update|delete>",
"validator": "<ValidatorType>",
// Optional role constraints
"required_role_system": "<CodingSystem>",
"required_role_code": "<CodeValue>"
}
Any validation rule can include pre_request_hook or post_response_hook to add custom validation logic or trigger external workflows. See Webhooks for details.
How rules are matched:
- A rule matches when all three of
client_role,entity_nameandoperationare exactly equal to the request's. The comparison is literal string equality — there are no wildcards."*"in any of the three fields matches a resource type literally named*, which is to say nothing at all. - If more than one rule matches, every one of them must pass. Matching rules are combined with AND, not OR, and the first denial ends the request. Rule order does not matter, and adding a permissive rule never widens access that another matching rule refuses.
- That last point is the one that surprises people: a
forbiddenrule and anallowedrule on the same triple do not "override" one another in either direction. Both run,forbiddendenies, and the request fails. To grant access you remove the restrictive rule — you do not add a permissive one beside it.
How a request is decided
Reading a project's validation_rules tells you most, but not all, of what a caller can do. The full order is:
- Code-level checks, before any rule is read. Three of them, described under Checks that run before your rules below. They cannot be switched off from configuration.
default_access: "Allowed", if set. Areadorsearchreturns immediately here and is granted without reading a single rule.create,updateanddeleteare not covered by this step — they proceed to rule matching at step 3, and where no rule matches they are granted at step 5, subject only to the structural checks under What a compartment validator asks of a write.- Rule matching, as described above.
- The search fallback. A
searchrequest with nosearchrule for its triple falls back to that triple'sreadrules. This is the only fallback in the system, and it runs in that direction only — areadnever falls back tosearch, and no operation falls back to any other. In practice this is load-bearing: it is how a project that defines onlyreadrules gets working list queries. default_access, when nothing matched."Forbidden"denies."Allowed"grants — which is why an unmatched write is permitted under it.- The validator named by each matching rule.
On reads and searches the validator runs twice over the request's lifetime: once before anything is fetched, deciding on the resource type alone, and again on each row that comes back. The second pass is what makes compartment scoping real rather than nominal — the first pass cannot see a row that does not exist yet. A refused request never reaches the FHIR server at all.
Platform rules are merged into every project
MedBackend prepends a fixed set of platform rules to every project's own validation_rules. A project's effective rule set is always its own rules plus these; they are not visible in the project's configuration and cannot be removed from it. They can, however, be narrowed: they are merged in as ordinary rules, and every rule matching a request has to pass, so a rule of your own on the same triple restricts a platform rule exactly as it would restrict one of your own.
| Roles | Resource | Operations |
|---|---|---|
Patient, Practitioner, Device, RelatedPerson | Me | read |
Patient, Practitioner, Device, RelatedPerson | UploadFile | create, read |
Device | Communication | create, read, update |
All of them use the allowed validator. Only the Me read is genuinely un-narrowable, and not because of this table — Me reads are decided in code above rule matching, so no rule of yours ever reaches them. It resolves entirely from the caller's own token and discloses nothing the caller did not already send.
The other rows are ordinary rules and behave like ordinary rules. If your project must not permit device messaging, add your own Device / Communication rules with the forbidden validator for all three granted operations — create, read and update. Yours and the platform's then both match, both have to pass, and the platform grant is refused. Do not stop at the two write verbs: the platform's read grant uses allowed, which applies no compartment filter, so leaving it in place returns every Communication in the project to any of that tenant's devices.
Checks that run before your rules
Three checks are implemented in code rather than expressed as rules, and they run above rule matching and above default_access: "Allowed". Each exists because the rule schema is structurally incapable of expressing it — not because it is more important than a configured rule.
| Check | What it does | Why configuration cannot say it |
|---|---|---|
Me read | Always granted | Me is not a FHIR resource type, so no rule naming an entity_name can ever match it |
AuditEvent writes | Always refused — an AuditEvent cannot be created, updated or deleted through the API | AuditEvent immutability is enforced by this check specifically, not by the rule engine, so it applies regardless of what your validation_rules allow |
Communication create and update | Refused when the write would attach to a chat thread the caller is not party to, or when it names a sender the caller is not | The check compares the payload against another row; validators only ever compare a payload against the caller |
Reads and searches of AuditEvent are not covered by the second row — those are decided by your rules in the normal way. Only writes are refused.
The Communication gate is scoped narrowly on purpose: it refuses threading onto MedBackend's own chat threads, and deliberately leaves ordinary clinical Communication resources to your rules, because who may reply to a clinical message is something a rule can express.
RBAC Design Methodology
Access Matrix Template
| Role | Resource | Operations | Validator | Constraints |
|---|---|---|---|---|
| Nurse | Patient | search, read | practitioner_compartment | role_code: "nurse" |
| Doctor | Patient | search, read | practitioner_compartment | role_code: "doctor" |
| ICT professional | Patient | create | legitimate_interest | role_code: "ict" |
update is deliberately absent from the Doctor row. A Patient resource carries none of practitioner_compartment's write fields — no practitioner, performer or requester element exists on it to name the caller in — so a compartment validator cannot grant a write of that type, however the rule is spelled. See What a compartment validator asks of a write.
Implementation Checklist
- Define all client roles and associated FHIR resources
- Map operations (CRUD) per role/resource combination
- Select appropriate validator for each access pattern
- Implement compartment boundaries for multi-tenancy
- Test all rules with realistic query scenarios
- Audit rule conflicts and validation order
- Configure monitoring for RBAC events
Advanced Validation Patterns
Composite Validation
[
{
"client_role": "Practitioner",
"entity_name": "Observation",
"operation": "search",
"validator": "organization_compartment"
},
{
"client_role": "Practitioner",
"entity_name": "Observation",
"operation": "create",
"validator": "practitioner_compartment"
}
]
What a compartment validator asks of a write
Compartment validators behave differently on writes than on reads, and the difference is the single most common source of rules that look correct and deny every request.
On create and update, the validator inspects the payload you submitted and requires it to reference the caller — by Type/id — in at least one of that compartment's write fields. One is enough; they are combined with OR. The exact lists are in the Compartment Validators table above.
Four consequences follow, and all four bite in practice.
A resource type that has none of those fields can never satisfy the rule. The check has no exception for resource types where the fields do not apply. A rule pairing such a type with a compartment validator will parse, publish, appear correct in the editor, and deny every write. The clearest case is Patient + patient_compartment + update: a patient updating their own demographics passes the ownership check, then fails the payload check, because a Patient resource has no subject, patient or performer element to name its own subject in. The denial reads No valid patient reference found. Expected Patient/<id> in one of ['subject', 'patient', 'performer']. Before configuring a compartment validator on a write, check the resource type actually carries one of the fields.
An empty payload is a denial, not a no-op. A write with no resource body, or with a body that has every field omitted, is refused rather than allowed through to the type-level check.
A create that carries an id naming an existing resource is refused by most validators, but not all. The FHIR write path upserts, so a create naming an existing id would overwrite that resource rather than create one. Which validator decides the request determines whether that is caught:
| Deciding the request | A create carrying an id that already exists |
|---|---|
allowed | Denied outright. It has no compartment, so "do you own the existing resource" is not a question it can ask — it asks only whether the id is taken. The denial reads Create denied: a resource with this id already exists. Use update to modify an existing resource. |
default_access: "Allowed" (no rule read) | Denied outright, same check and same message |
organization_consent | Denied outright, exactly like allowed — ownership and consent are never checked for this case. This is the only row this table covers for organization_consent; see its own page for what an ordinary create (no existing id) requires |
| The compartment validators | Permitted only if the stored row already references the caller, under the same criteria the payload was checked against — the same question an update asks. Otherwise denied. One exception: organization_compartment treats a failed lookup as "no existing row" and falls through to the payload check, so during a FHIR outage a create-with-id under that validator can be permitted. The other compartment validators deny on a failed lookup |
legitimate_interest | Depends on which internal rule it resolves to for that resource type and caller role. Some of its rules delegate to a compartment validator and behave as the row above; its organization-anchored rules decide from the payload alone and do not ask the question at all. See the warning below |
There is no single guard above rule matching that refuses every create-with-id. Each validator answers the question itself, and legitimate_interest answers it differently depending on which internal rule it resolves for that resource type and caller role. Its organization-anchored rules do not ask it, so under those a create carrying an existing id overwrites the stored resource.
Do not generalise from the allowed row to "the platform refuses this on writes". If you cannot say which internal rule your legitimate_interest rule resolves to, do not grant create on it.
A create with no id, or with an id that names nothing, is an ordinary create and is unaffected everywhere — there is no existing resource to overwrite.
An update replaces the whole resource. There is no partial update: a field you omit is a field you erase. An update that drops the reference anchoring the resource to your compartment does not merely fail to prove ownership — it would walk the resource out of the compartment entirely, so it is refused. Send the complete resource, not a patch.
delete carries no payload, so this check does not apply to it. Deletes are decided by fetching the stored resource and confirming it belongs to the caller's compartment; a delete whose target does not exist, or cannot be read, is denied rather than treated as a success.
Performance Considerations
What costs time in validation is FHIR round-trips, not the rule matching. Rule matching is an in-memory comparison over a short list.
allowed,forbidden, and a compartment check on a row already fetched cost nothing measurable — no additional request is made.- Role gating (
required_role_*) adds onePractitionerRolelookup, and only for rules that use it. A rule without those keys makes no such request. - Organization resolution adds a lookup for the caller's active organizations, and patient-linked resource types add one more to resolve the patient's managing organization.
- Each level of organization inheritance adds a further round-trip to walk the hierarchy. Keep inheritance shallow; two levels is usually plenty.
- Writes that target an existing resource fetch that resource before deciding, so an
updateordeletealways costs one read. - Always test with production-like datasets — the cost scales with the shape of your organization hierarchy, not with rule count.
- Use field projection to minimize data transfer:
query {
PatientList {
id
name {
given
family
}
}
}
Audit & Monitoring
Key metrics to track:
- Rule match rates
- Validation latency per type
- Access denial patterns
- Compartment crossover attempts
- Role assignment drift