Skip to main content

Device Authentication

Device authentication is the platform's non-interactive credential. A caller presents a pre-registered device_id and api_key, receives a short-lived JWT, and uses that JWT as a Device caller for the rest of its lifetime.

What the credential actually is​

Read this section before deploying a device key. The name "device" understates what the credential is for and what it reaches.

A device API key is a project-scoped integration credential. The project is its tenant boundary. It is the credential a project's own developer issues to their devices, background workers, integration processes and AI models so that those processes can read and process the FHIR data of their own project. That is the intended product behaviour, not an oversight.

Concretely, the shipped device RBAC template grants Device/Patient/read, Device/Observation/read, Device/Device/read and Device/DeviceMetric/read with the allowed validator — and four write operations besides, listed under what a leaked key exposes. allowed inspects no row and applies no compartment filter — it is a blanket grant for the matched triple. A device token can therefore read every Patient, Observation, Device and DeviceMetric in the project it belongs to.

Narrowing a device to a single organisation is an opt-in capability, not a default. Until a project configures it, a device key reads across the whole project. This is a recorded architectural decision, not a bug: see ADR-010, "The device API key is a project-scoped integration credential; organisation scoping is opt-in".

Switching a rule from allowed to device_compartment has two different outcomes depending on the resource, and the difference decides whether it is a useful control:

  • For Patient, Device, DeviceMetric, Organization and Location it denies outright unless Access scope narrows devices to their organisation. All five are excluded from the device compartment, so without that setting device_compartment on these removes the access rather than scoping it. With it, a device reaches the ones that belong to its organisation.
  • For Observation it genuinely narrows. Observation is in the device compartment with inclusion criteria subject, device, so the rule scopes a device to the observations it is the subject or source of. Media (subject) and Communication (sender, recipient) behave the same way.

So the narrowing that matters most — the clinical data a device produces — is available today.

What a leaked device key exposes​

If a device_id / api_key pair leaks, an attacker who also knows the project uid can mint device tokens at will and, with the shipped device template in place:

  • Read every Patient resource in the project — names, identifiers, demographics, contact details.
  • Read every Observation and DeviceMetric in the project — clinical measurements for all patients, not only those produced by the leaked device.
  • Read every Device resource in the project.
  • Create Observation, DeviceMetric and Media resources, and update any Device resource. These are granted allowed by the same shipped template. An allowed write applies no compartment filter and no ownership test — the one thing it refuses is a create carrying an id that already exists, which stops the grant being an overwrite primitive but scopes nothing. Treat these as unconditional in every other respect.
  • Create and update Communication resources, granted to Device by the platform's own system rules — subject to the platform's chat-thread check, which refuses a write that threads onto a conversation the caller is not party to or that names a sender the caller is not. Reads are narrower under the shipped template, which scopes Communication read with device_compartment — so an attacker sees the conversations that device is party to, not every conversation in the project. update carries no such rule.
  • Create and read UploadFile, likewise a system rule. An upload is also refused unless the device may create a DocumentReference or Media about the entity it names (see Who may upload).

The blast radius is one project. Cross-project access remains denied at the configuration boundary: the token carries the project it was minted for and the platform refuses to serve it against any other. But within the project, treat a device key as equivalent to a full read of the patient population and the ability to write clinical data into it — falsified observations in a patient record are a more serious outcome than disclosure, and they are the half that is easiest to overlook.

Two consequences follow. First, a device key is not a per-machine secret to be embedded casually across a fleet — every holder gets the same project-wide reach. Second, because there is no revocation list, the response to a suspected leak is to rotate the key or suspend the device; already-issued tokens remain valid until they expire, which is why the default lifetime is five minutes.

To restrict a device to its own organisation's data, use the Access scope setting.

Registering a device​

A device must exist in the project before it can obtain a token. Registration is refused if the project has no organisation:

POST /devices/
X-Project-ID: <project-uid>
ResponseBodyMeaning
400{"detail": "This project has no organisation, …"}The project has no root Organization. Create one first with POST /fhir/organizations/bootstrap, then register the device. Unlike the organization endpoints, this refusal carries no machine-readable code field — match on the status, not on the message text

Registration requires two permissions on the project: manage_devices to reach the endpoint at all, and register_devices to create. Missing either returns 403, and manage_devices is checked first.

Unlike the organization endpoints, device registration does not check the project's status — a pending project will accept a device registration.

The device's organisation​

The body may carry an optional organization: the id of an Organization in the project, which becomes the device's FHIR Device.owner. This is what Access scope narrows a device to.

ResponseMeaning
400organization does not name an Organization in this project. Nothing is registered
409This name was registered before by a device since deleted, with a different organisation or none. Nothing is registered; use a new name

Neither body carries a machine-readable code, so match on the status. A 400 can also mean the name is already taken by another device in the project.

Leave organization out and the device gets the project's root organisation when its patient custodianship is set to organisation, and no owner otherwise; see the warning below.

Changing a device's organisation​

A registered device keeps its API key when its organisation changes. Send the new Organization id:

PATCH /devices/<device-id>
X-Project-ID: <project-uid>
Content-Type: application/json

{"organization": "<organization-id>"}

This needs register_devices as well as manage_devices. On 400, 403 or 409 nothing is changed. A 502 means the change was not confirmed: retry the same request until it returns 200, and do not rely on the device's access until it does.

ResponseMeaning
200Applied. The device now belongs to the new organisation. Sending the organisation the device already has changes nothing
400organization does not name an Organization in this project; or the request removes the organisation (it can be changed, not removed); or the same request also renames the device (send them separately); or the caller lacks manage_devices, has no access to the project, or sent no X-Project-ID
403The caller lacks register_devices
409The device has no FHIR Device yet: it gets one when it first requests a token, so change the organisation after that. Or the device's FHIR record is in a state that cannot be changed automatically; nothing was changed. Contact support
502Not confirmed. Retry the same request until it returns 200; if it keeps failing, contact support

When Access scope is set to "Its own organisation", a device's organisation decides which organisation's data it reaches, so moving a device changes what it can read and write. Run the preview afterwards to check every device still resolves.

The response​

A successful registration answers 201, and its body carries the device's api_key together with an api_key_detail string saying it cannot be read back. Store the key from this response. It is the only time registration shows it; see Managing a device key.

An organisation is necessary, not sufficient — this gate does not mean your device is anchored

Passing this check does not mean the device will be anchored to an organisation. FHIR Device.owner is written only for a project whose patient custodianship is set to organization (ADR-020 mode 1). A project in mode 2 has an organisation, passes this gate, and still gets devices with no owner at all.

Worse, it is not repaired later: a device registered under mode 2 is not backfilled if the project switches to mode 1 afterwards. The device stays unanchored for its lifetime while the project's configuration reads mode 1 and looks entirely consistent.

The failure this sets up is silent. Enabling org_aware on such a device resolves it to no organisation, and every org-aware request is denied — with nothing in the configuration looking wrong. Before enabling org_aware, confirm each device carries an owner. The Access scope preview does this for every active device, and refuses the save while any has none. Do not infer it from the fact that registration succeeded.

Managing a device key​

A device's api_key is shown when it is minted and at no other time. No endpoint returns an existing key.

CallReturns api_key
POST /devices/Yes, once, in the 201 body
POST /devices/{id}/rotate_keyYes, once, in the 200 body: a new key
GET /devices/ · GET /devices/{id}Never
PUT / PATCH /devices/{id}Never

Two consequences are easy to miss:

  • A key that was not stored when it was shown cannot be recovered. The published configuration holds only a digest of it. A lost key is replaced by rotating, never retrieved.
  • Rotating stops the current key working. The previous key is no longer accepted, so re-provision the device with the new key in the same window.

All four actions are POST /devices/{id}/<action> with an empty body and the X-Project-ID header, and need the manage_devices permission on the project. A device id from another project answers 404.

ActionEffectResponse
rotate_keyMints a new key, and the previous key stops being accepted200 with id, name and the new api_key
suspendThe device's key stops being accepted until the device is activated200 with id, name and status: "inactive"
activateThe device's existing key is accepted again200 with id, name and status: "active"
testReports whether the device's current key is in the published configuration200 for any device it finds, even when the answer is no. See below

Changes take effect within about a minute, not instantly. For up to a minute after a rotation, suspension or deletion, the old key can still obtain tokens. A newly registered or rotated key can be refused for up to the same minute. If a fresh key's first token request returns 401, retry it shortly before you treat the key as wrong. Tokens already issued stay valid until they expire either way.

If a rotation fails, the response is an error and carries no key. Do not assume the previous key still works: run test, then rotate again.

What test tells you​

test does not contact the device. A device is a client that calls the platform, so there is nothing to reach. Instead it checks whether the device's current key is the one in the project's published configuration. For a device it finds, it answers 200 even when the answer is no, so read the body, not the status:

{
"success": false,
"status": "not_published",
"message": "…",
"checks": {
"device_active": true,
"fhir_resource_synced": true,
"key_published": false
}
}
statussuccessMeaningWhat to do
readytrueThe device is active and its current key is published. It is accepted within about a minute of being publishedNothing
suspendedfalseThe device is suspended, so its key is refusedactivate it
not_publishedfalseThe device is active, but its current key is not the published oneRotate the key and re-provision the device
unknownfalseThe check could not be completedRetry later

Configuration​

{
"device_auth": {
"valid_keys": {
"icu-monitor-05": "<api-key>"
},
"token_expiry_minutes": 5,
"jwt_secret": "<hs256-signing-secret>"
}
}
KeyMeaning
valid_keysMap of device_id to its stored credential — either plaintext or sha256:<hex>. Verified against the presented api_key in constant time either way
jwt_secretHS256 signing secret for device tokens. If unset, or rejected by the platform (plaintext, a published placeholder, or shorter than 32 characters), no device token is issued or accepted for this project: both the token request and every request carrying a device token answer 401.
token_expiry_minutesToken lifetime. Default 5

valid_keys accepts two coexisting shapes for a stored value: legacy plaintext, or sha256:<64 lowercase hex chars>. The platform's publish path writes the hashed shape automatically; a tenant whose configuration has not been republished since that change still holds plaintext. Either shape verifies in constant time, so neither leaks timing information relative to the other — and a value carrying the sha256: marker that does not parse as 64 lowercase hex characters is rejected outright, never treated as a plaintext credential to fall back on.

Both the keys and jwt_secret are secrets of the same weight as a database password regardless of shape. Inject them from a secret manager; never commit them. When writing valid_keys by hand, generate each key with a cryptographically secure random source — the platform generates its own with secrets.token_urlsafe(32), and a guessable key is equivalent to publishing the data it reaches.

Once a key is hashed, nothing can recover it back to plaintext — not the platform itself, not its own republish path. The published configuration is not a place to read a device's key back from, and no other place returns it either. A lost key is rotated, not recovered.

The FHIR identifier system used to find a device's Device resource is configured separately from device_auth, as device_identifier_system in the project configuration. It defaults to https://fhir.medbackend.com/identifier/device.

Obtaining a token​

POST /api/account/token/device/
Content-Type: application/json
X-Project-ID: 3fa85f64-5717-4562-b3fc-2c963f66afa6

{
"device_id": "icu-monitor-05",
"api_key": "<api-key>"
}
{
"access": "header.payload.signature",
"expires_in": 300
}

expires_in is in seconds and is token_expiry_minutes × 60. The endpoint also accepts form-encoded bodies, and answers on the same path without the trailing slash.

What happens during issuance​

  1. The project's device_auth configuration is loaded.
  2. device_id and api_key are checked against valid_keys.
  3. The X-Project-ID header is read and embedded in the token as a lowercased project_uid claim.
  4. The FHIR Device resource is resolved by searching for identifier {device_identifier_system}|{device_id}. If no such resource exists it is created just-in-time, tagged jit-provisioned. If two requests race and the create returns a conflict, the search is repeated and the existing resource is used.
  5. The resolved FHIR logical id is checked against the reserved-id list.
  6. The token is signed HS256 with jwt_secret and returned.

Just-in-time provisioning means a device does not have to be pre-registered on the FHIR server — only in valid_keys. The Device resource is created with the device id as its identifier, status: active, and a jit-provisioned tag so that provisioning history stays auditable.

Responses​

StatusCondition
200Token issued
401device_id or api_key missing, the pair does not match valid_keys, or the project has no usable jwt_secret
403The device resolves to a reserved id — see below
503The FHIR Device resource could not be resolved or created, or the platform's device-secret service is temporarily unavailable; retry
500Unexpected server error

Both credential failures return 401 with a deliberately unspecific message. The endpoint does not distinguish "unknown device" from "wrong key".

Reserved device ids​

Issuance is refused with 403 when the resolved FHIR Device logical id is a reserved platform identity. Today that is ai-agent, the identity the platform's own AI proxy uses.

The check runs against the resolved FHIR resource id, not against the submitted device_id, and it runs after all three resolution paths — found, just-in-time created, and conflict-resolved — have converged. It is also reference-aware, so it answers the same whether the id appears bare or as Device/ai-agent.

The reason it is a hard refusal rather than a scoped denial is worth stating: Device/ai-agent is a party to every chat thread the AI proxy has ever stored, so a token resolving to that id would read every conversation in the project through ordinary GraphQL queries. Refusing at issuance covers every downstream consumer — GraphQL, the chat endpoint, MCP — instead of relying on each to re-check. It returns 403 rather than folding into the generic 401 because this is a reserved identity, not a credentials failure, and a silent denial would be misread as a broken RBAC rule.

Using the token​

POST /graphql
Authorization: Bearer <device token>
X-Project-ID: 3fa85f64-5717-4562-b3fc-2c963f66afa6
Content-Type: application/json

Token claims​

ClaimValue
subThe device_id presented at issuance
entity_typeAlways Device
entity_idThe FHIR Device logical id this token acts as
project_uidThe project the token was minted for
is_devicetrue — this is what marks the token as a device token
iat / expIssued-at and expiry

How it is validated​

Device tokens are tried first, before the OAuth path. The token is decoded HS256 with the project's jwt_secret and must carry is_device: true. An HS256-signed bearer is always treated as a device token. There is no fall-through to OAuth: a token whose header says HS256 and that fails any device rule is refused with 401 (TOKEN_EXPIRED for an expired token, otherwise TOKEN_INVALID). Tokens that are not HS256 go to the OAuth path.

Tenant binding then applies. Every device token must carry a project_uid claim equal to the request's X-Project-ID:

  • Present and equal → the request continues.
  • Absent or different → refused with 401.

Because the token is signed with the project's own jwt_secret, and each project's secret is distinct, a device token minted for one project does not validate against another.

Authorization​

A device token is authorized exactly like any other caller: RBAC rules are matched on client_role: "Device" plus the resource type and operation. There is no device-specific bypass and no device-specific escalation.

Some grants come from the platform's own system rules rather than from your configuration: Me read, UploadFile create and read, and Communication create, read and update. They are merged into every project's rule set, and they are not visible in it.

They are not immune to your rules. System rules are merged as ordinary rules, and every rule matching a triple must pass — so a rule of your own on the same triple narrows the system grant. Me read is the single exception: it is decided in code above rule matching and cannot be overridden.

That distinction is load-bearing rather than academic. The shipped device template pairs Device / Communication / read with device_compartment, on the same triple as the system rule's allowed. Both run, and the narrower decides — so under that template a device reads the conversations it is party to, not every conversation in the project. Removing that rule as redundant would widen access to all of them. The same technique narrows UploadFile: add your own rule on UploadFile / read, the operation an upload is evaluated as.

Everything else comes from the project's own rules — which, with the shipped device template, means the project-wide reads described at the top of this page.

Operational guidance​

  • Rotate jwt_secret and API keys on a schedule, and immediately on any suspicion of exposure or on staff change. Rotation is the only revocation mechanism.
  • Issue one key per integration, not one per fleet. They all carry identical reach, but distinct keys let you rotate one without taking every device offline.
  • Keep token_expiry_minutes low. The default of 5 exists because it is the revocation window.
  • Audit your devices against reality. A key stays valid until the device is rotated, suspended or deleted; nothing expires it.
  • Watch for jit-provisioned Device resources you did not expect. A Device resource appearing with that tag means a credential in valid_keys was used for the first time.

Troubleshooting​

SymptomCauseFix
401 on token requestdevice_id not in valid_keys, or key mismatch, or the project has no usable jwt_secretCompare exactly; the match is case-sensitive whether the stored value is plaintext or sha256:<hex>
403 on token requestDevice resolves to a reserved idUse a different device_id; the reserved identity cannot be issued a token
503 on token requestFHIR server unreachable, or the endpoint is misconfiguredRetry; check the project's FHIR configuration
Token issued, then every query deniedNo RBAC rules for client_role: "Device"Add device rules; the default policy is Forbidden
Token rejected as project mismatchToken minted for a different project, or header changed since issuanceRe-issue against the correct project
Token refused, no project claimToken minted before the project claim existedRe-issue it
401 on every request with a device tokenThe project's jwt_secret is unset or rejected by the platform (plaintext, placeholder, too short), or it changed since issuanceSet or fix it in the project's device configuration, then re-issue tokens