owned this note
owned this note
Published
Linked with GitHub
# SMART Health Links: OAuth Sketch
## Background and Design goals
See https://hackmd.io/kvyVFD5cQK2Bg1_vnXSh_Q
## Design Sketch #: OAuth 2.0 Method
### Software Components
* **Resource Server**. Hosts static files (which can be updated over time) or a live FHIR API endpoint (such as the endpoints hosted by Certified EHR Technology in the US market).
* **Authorization Server**. Manages access control for files in the Resource Server. If the files are encrypted, the Authorization Server cannot read them.
Notes: These servers can be packaged together into a single software release, but they don't need to be. Files may be encrypted so the resource server and authorization server are unable to read them.
### Protocol Flow
The basic idea is that an authorized end-user can create a QR that allows third parties (i.e., anyone who scans the QR) to register a new OAuth client on-the-fly with the EHR. this OAuth client is bound to a specific set of access policies established at the time the QR is created, and once the client is registered, it can obtain access tokens following the SMART Backend Services IG (all access tokens are limited to the policies established at QR creation time).
#### Data Sharer creates a SH Link QR
For example, the uesr may interact with a patient portal and engaeg in a wizard-type workflow. Or the user may run a mobile app independent of any EHR portal, uploading encrypted files to a trusted backend. The workflow here is out of scope, but results in a QR Code based on the SH Link Data Model:
* `oauth`: Required. JSON Object with:
* `url` Required. Base URL for an OAuth 2.0 authorization server that that SHALL ensure
* `${url}/.well-known/smart-configuration` is publicly hosted
* `capabilities[]` includes `shlinks`
* `registration_endpoint` is present
* `token_endpoint` is present
* `token_endpoint_auth_methods_supported` includes `private_key_jwt`
* `token`: Required. Opaque string that the client can use as an access token during the registration step.
* `exp`: Optional. Numeric value in epoch seconds. Provides a hint for the Data Receiver to determine if this QR is stale.
* `flags`: Optional. String created by concatenating single-character flags in alphabetical order
* `L` for long-term use
* `O` for one-time-use
* `P` if a receiver-supplied PIN is required for redemption
* `prefix`: Optional. String created by concatenating single-character flags in alphabetical order, conveying the behavior of the full URL prefix, if any (i.e., the part of this SHLink before `shlink:/`)
* `I` for a web page with information about this SHLink
* `V` for a web page capable of viewing the clinical data from this SHLink
* `M` for a web page allowing a user to manage this SHLink (e.g., demonstrate ownership and then revoke or review permissions)
* `decrypt`: Conditional. Included if the target resources are encrypted to prevent the Resource Server from reading them. Omitted otherwise. This key is used to encrypt/decrypt the target file. (Format: 43 character string consisting of 32 random bytes, base64urlencoded. This field is necessary if we want to support encrypting files so that the resource server and authorization sever can't read them.)
To create a QR code, the Data Sharer's software generates a JSON payload including at least the `oauth` field and then SHALL prepare the JSON payload as follows:
```typescript=
const qrPayload = {
oauth: {
url: "https://server.example.org",
token: "some-high-entropy-string"
},
flags: "LOP"
};
const qrJson = JSON.stringify(qrPayload);
const qrEncoded = base64url.encode(qrJson);
const qrPrefixed = "shlink:/" + qrEncoded;
const qr = (hostedLandingPage || "") + qrPrefixed;
```
(The optional "hosted landing page" is a prefix on the QR consisting of any https URL that ends in `#`, allowing a source EHR to provide a friendly landing page for anyone who might scan this QR outside of a SHLink-aware app. The landing page SHOULD provide information about the format, and MAY provide a Web-based SHLink client to help the Data Receiver retrieve a file or viewing a file online. Note that in this arrangement the decryption key is not automatically submitted by the web browser to the web server because it's part of the URL fragment, *but* server-supplied JavaScript is capable of reading and exfiltrating this value. The capabilities of the landing page, if any, are described in the `prefix` flags of the SHLink data payload.)
The resulting value is used to create a QR ensuring:
* Level H (high) error correction
* V22 symbol or smaller
* [SMART Logo](https://smarthealthit.org/wp-content/themes/SMART/images/logo.svg)
* embedded at the center of the QR
* scaled to occupy 15% of the symbol area
#### Data Receiver scans and processes the QR
```typescript=
const qrRaw = await scanAndDecode();
const qrSplit = qrRaw.split("shlink:/")[1];
const qrJson = base64url.decode(qrSplit);
const qrPayload = JSON.parse(qrJson);
```
#### Data Receiver Claims the QR by Registering with the Authorization Server
Client registers via Dyn Reg, narrowly profiled so that the registration endpoint:
* SHALL support token_endpoint_auth_method: "private_key_jwt"
* SHALL support ES256 JWKS
* SHALL support grant_types: ["client_credentials"]
* SHALL automatically populate scopes based on a policy established by the Data Sharer
##### Registration
```typescript=
const discoveryUrl = `${qrPayload.oauth.url}/.well-known/smart-configuration`;
const discovery = await fetch(discoveryUrl).then(r => r.json());
assert(discovery.capabilities.includes("shlinks"));
const {publicKey, privateKey} = generateJWK(); // ES256 signing key
let pin = qrPayload.flags?.match("P")
? await promptReceiverForPin()
: undefined;
const client = await fetch(discovery.registration_endpoint, {
method: "POST",
headers: {
"authorization": `Bearer ${qrPayload.oauth.token}`,
// only if `P` is included in the flags
"shlink-pin": pin,
"content-type": "application/json",
"accept": "application/json"
},
body: JSON.stringify({
token_endpoint_auth_method: "private_key_jwt",
grant_types: ["client_credentials"],
jwks: {
"keys": [publicKey.toJson()]
},
client_name: "Dr. B's Quick Response Squared", // optional
contacts: ["drjones@clinic.com"], // optional
})
}).then(r => r.json());
```
##### Generate authentication JWT and request an access token
This follows [SMART Backend Services](http://build.fhir.org/ig/HL7/smart-app-launch/client-confidential-asymmetric.html).
```typescript=
const assertion = await jose.JWS.createSign({format: "compact"}, privateKey)
.update(JSON.stringify({
iss: client.client_id,
sub: client.client_id,
aud: discovery.token_endpoint,
// no more than 5min in future
exp: Math.floor(new Date().getTime()/1000 + 60),
jti: randomUuid()
}))
.final();
const accessTokenResponse = await fetch(discovery.token_endpoint, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json"
},
body: encodeQueryString({
scope: client.scope,
grant_type: "client_credentials",
client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
client_assertion: assertion
})
}).then(r => r.json());
```
#### Data Receiver Uses Access Token Metadata to retrieve files
The Access Token Response includes an `access_token` as well as the following properties (building upon https://datatracker.ietf.org/doc/html/draft-ietf-oauth-rar):
```typescript=
interface AccessTokenResponse {
access_token: string, // high entropy string, per OAuth 2.0
expires_in: number, // integer seconds from now, per OAuth 2.0
authorization_details: ResourceAccessRights[]
}
interface ResourceAccessRights {
type: "shlink-view" | "smart-on-fhir-api";
locations: string[];
actions?: string[];
datatypes?: string[];
}
```
The client issues data access requests following the Resource Access Rights conveyed in the Access Token Response. To request files or issue API calls, the client provides an `Authorization: Bearer {{}}` header, per OAuth 2.0.
Access tokens will be short-lived, but the client can re-issue a request as needed; requests will continue to work until the Data Sharer's poilcy expires or is manually revoked.
#### Data Receiver (Conditionally) Decrypts retrieved files
If the SHL's `.decrypt` value is present, the Data Receiver derives a symmetric decryption key as `base64urldecode(shl.decrypt)` (yielding a 32-byte random sequence). The client then processes `shlink-view` payloads by treating each file as a compact-serialization JWE encrypted with ``"alg": "dir", "enc": "A256GCM"``. The header includes only the `alg`, `dir`, and `contentType` claims and the payload is the full shared file (of the specified contentType).