diff --git a/.gitattributes b/.gitattributes index 1f05a99d6e..792609ee4a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -48,6 +48,9 @@ crates/*/src/**/generated/** linguist-generated=true crates/openehr-rm/src/model/data.rs linguist-generated=true # The shipped ferroehr.toml, generated by tools/config-reference (#5316). app/ferroehr/assets/ferroehr.default.toml linguist-generated=true +website/book/src/reference/cli.md linguist-generated=true +website/book/src/reference/aql-functions.md linguist-generated=true +website/book/src/reference/refusal-codes.md linguist-generated=true # ── Linguist: honest language stats ────────────────────────────────────────── # Generated spec crates: emitted from the vendored BMM by openehr-codegen. The diff --git a/README.md b/README.md index ec2e71bb3b..acee596c80 100644 --- a/README.md +++ b/README.md @@ -157,7 +157,7 @@ continues from here. - [Docker Compose](https://ferroehr.eu/docs/latest/installation/compose.html) and a [Helm chart](https://ferroehr.eu/docs/latest/installation/kubernetes.html), with multi-arch images (amd64, arm64) - [Observability](https://ferroehr.eu/docs/latest/operations.html#observability): Prometheus metrics, OpenTelemetry traces, health probes -- [Backup and point-in-time recovery](https://ferroehr.eu/docs/latest/operations.html#backup-and-point-in-time-recovery) on PostgreSQL +- [Backup and point-in-time recovery](https://ferroehr.eu/docs/latest/database-operations.html#backup-and-point-in-time-recovery) on PostgreSQL - [Measured conformance](https://ferroehr.eu/docs/latest/conformance.html) and [performance](https://ferroehr.eu/docs/latest/performance.html) - [Verifiable releases](https://ferroehr.eu/docs/latest/verifying-releases.html): signed, with provenance and a software bill of materials diff --git a/app/ferroehr-rest/tests/it/book_examples_http.rs b/app/ferroehr-rest/tests/it/book_examples_http.rs new file mode 100644 index 0000000000..148d7982fe --- /dev/null +++ b/app/ferroehr-rest/tests/it/book_examples_http.rs @@ -0,0 +1,180 @@ +// SPDX-FileCopyrightText: Cadasto B.V. +// SPDX-License-Identifier: BUSL-1.1 + +//! The requests of the book's "Your first integration" tutorial, run in page +//! order against a fresh server, each held to the status its marker names. +//! +//! A request is a fenced `http` block after a `` +//! marker whose attributes are `expect=STATUS`, `body-file=PATH` (relative to +//! the repository root), `capture=VAR:/json/pointer` (with `|object` for the +//! versioned object id before `::`), `json-has=/json/pointer` and +//! `header=NAME:VALUE`. A `{VAR}` in the request is a value an earlier answer +//! captured. The page shows no credentials, so the server runs without +//! authentication. + +use std::collections::BTreeMap; +use std::path::PathBuf; + +use http::StatusCode; +use serde_json::Value; + +use crate::common; + +const PAGE: &str = "website/book/src/tutorials/first-integration.md"; +const MARKER: &str = "\n") + .expect("a marker closes on its line"); + let block = rest + .strip_prefix("```http\n") + .unwrap_or_else(|| panic!("an http block follows the marker {attributes}")); + let block = block.split_once("\n```").expect("the http block closes").0; + let (head, body) = block.split_once("\n\n").unwrap_or((block, "")); + let mut lines = head.lines(); + let (method, path) = lines + .next() + .and_then(|line| line.split_once(' ')) + .expect("a request line"); + let headers = lines + .map(|line| { + let (name, value) = line.split_once(": ").expect("a header line"); + (name.to_owned(), value.to_owned()) + }) + .collect(); + let mut words = attributes.split_whitespace(); + let name = words.next().expect("a marker names its request").to_owned(); + let mut example = Example { + name, + method: method.to_owned(), + path: path.to_owned(), + headers, + body: body.to_owned(), + body_file: None, + expect: 0, + captures: Vec::new(), + json_has: Vec::new(), + header_has: Vec::new(), + }; + for word in words { + let (key, value) = word.split_once('=').expect("an attribute is key=value"); + match key { + "expect" => example.expect = value.parse().expect("a status code"), + "body-file" => example.body_file = Some(value.to_owned()), + "capture" => { + let (var, pointer) = value.split_once(':').expect("capture=VAR:/pointer"); + example.captures.push((var.to_owned(), pointer.to_owned())); + } + "json-has" => example.json_has.push(value.to_owned()), + "header" => { + let (name, wanted) = value.split_once(':').expect("header=NAME:VALUE"); + example + .header_has + .push((name.to_owned(), wanted.to_owned())); + } + other => panic!("unknown marker attribute {other}"), + } + } + found.push(example); + } + found +} + +/// `text` with each `{VAR}` replaced by its captured value. +fn fill(text: &str, vars: &BTreeMap) -> String { + vars.iter().fold(text.to_owned(), |text, (var, value)| { + text.replace(&format!("{{{var}}}"), value) + }) +} + +#[tokio::test] +async fn the_first_integration_tutorial_runs_as_written() { + let (_pg, app) = common::app(common::api_config(false)).await; + let examples = examples(); + assert!(examples.len() >= 8, "the tutorial holds its eight requests"); + let mut vars = BTreeMap::new(); + for example in examples { + let path = fill(&example.path, &vars); + let mut req = common::req(&example.method, path.as_str()); + for (name, value) in &example.headers { + req = req.header(name.as_str(), fill(value, &vars)); + } + let body = match &example.body_file { + Some(file) => repo_file(file), + None => fill(&example.body, &vars), + }; + let (status, headers, text) = common::send(&app, req.body(body).build()).await; + assert_eq!( + status, + StatusCode::from_u16(example.expect).expect("a status"), + "{} answers {}: {text}", + example.name, + example.expect + ); + for (name, wanted) in &example.header_has { + let got = headers + .get(name.as_str()) + .and_then(|value| value.to_str().ok()) + .unwrap_or_default(); + assert!( + got.starts_with(wanted.as_str()), + "{} carries {name}: {wanted}, got {got}", + example.name + ); + } + if example.captures.is_empty() && example.json_has.is_empty() { + continue; + } + let json: Value = serde_json::from_str(&text).expect("a JSON answer"); + for pointer in &example.json_has { + assert!( + json.pointer(pointer).is_some(), + "{} holds {pointer}: {json}", + example.name + ); + } + for (var, pointer) in &example.captures { + let (pointer, object) = match pointer.strip_suffix("|object") { + Some(pointer) => (pointer, true), + None => (pointer.as_str(), false), + }; + let value = json + .pointer(pointer) + .and_then(Value::as_str) + .unwrap_or_else(|| panic!("{} holds {pointer}", example.name)); + let value = if object { + value.split_once("::").map_or(value, |(id, _)| id) + } else { + value + }; + vars.insert(var.clone(), value.to_owned()); + } + } +} diff --git a/app/ferroehr-rest/tests/it/main.rs b/app/ferroehr-rest/tests/it/main.rs index 90512902a9..7ab420497c 100644 --- a/app/ferroehr-rest/tests/it/main.rs +++ b/app/ferroehr-rest/tests/it/main.rs @@ -82,6 +82,7 @@ mod binding_commits_http; mod binding_issuers_http; mod binding_purposes_http; mod binding_refusals_http; +mod book_examples_http; mod caller_kinds_http; mod care_writer_review_http; mod cohort_http; @@ -152,6 +153,7 @@ mod query_caseload_http; mod query_ehr_id_header; mod query_refusals_http; mod rbac_e2e; +mod reference_pages; mod release_before_render; mod repeated_member_names_http; mod representation_http; diff --git a/app/ferroehr-rest/tests/it/reference_pages.rs b/app/ferroehr-rest/tests/it/reference_pages.rs new file mode 100644 index 0000000000..7ee5e275ea --- /dev/null +++ b/app/ferroehr-rest/tests/it/reference_pages.rs @@ -0,0 +1,111 @@ +// SPDX-FileCopyrightText: Cadasto B.V. +// SPDX-License-Identifier: BUSL-1.1 + +//! The book's reference pages generated from the code: the AQL built-in +//! functions of `openehr-query` and the access refusal codes of the draft +//! access terminology. +//! +//! `the_book_holds_the_current_reference_pages` fails when a committed page +//! differs from what the code renders; `write_the_reference_pages` (ignored, +//! run with `cargo nextest run -p ferroehr-rest --test it --run-ignored only +//! reference_pages`) writes them again. + +use std::path::PathBuf; + +use openehr_query::ast::{DateTimeFunction, NumericFunction, StringFunction}; +use openehr_rm::draft::access_control::terminology::{Refusal, Term as _}; + +const AQL_FUNCTIONS: &str = "website/book/src/reference/aql-functions.md"; +const REFUSAL_CODES: &str = "website/book/src/reference/refusal-codes.md"; + +fn path(relative: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../..") + .join(relative) +} + +// REUSE-IgnoreStart +fn banner(title: &str, intro: &str) -> String { + [ + "\n", + "\n", + "\n\n", + "# ", + title, + "\n\n", + intro, + "\n\n", + ] + .concat() +} + +// REUSE-IgnoreEnd + +fn aql_functions() -> String { + let mut out = banner( + "AQL built-in functions", + "**For:** integrators. Every built-in single-row function the AQL parser\n\ + accepts, by the group the AQL specification puts it in (QUERY, §Functions).\n\ + Names compare without regard to case. How to use them, the aggregates and\n\ + FerroEHR's extension functions are on [Querying with AQL](../querying-aql.md).", + ); + out.push_str("| Function | Group |\n|---|---|\n"); + let rows = StringFunction::ALL + .iter() + .map(|f| (f.as_str(), "string")) + .chain(NumericFunction::ALL.iter().map(|f| (f.as_str(), "numeric"))) + .chain( + DateTimeFunction::ALL + .iter() + .map(|f| (f.as_str(), "date and time")), + ); + for (name, group) in rows { + out.push_str(&["| `", name, "` | ", group, " |\n"].concat()); + } + out +} + +fn refusal_codes() -> String { + let mut out = banner( + "Access refusal codes", + "**For:** integrators and operators. Every code the access evaluator refuses\n\ + a request under, with the status the caller receives. A `403` names its code\n\ + in the problem's `detail`; a `404` answers as if the data did not exist and\n\ + names nothing. A `refused-confidentiality` answers `404` instead at a level\n\ + the access policy conceals. The access log records the code either way. What each step\n\ + decides is on [How FerroEHR decides access](../explanation/access-model.md).", + ); + out.push_str("| Code | Answer |\n|---|---|\n"); + for refusal in Refusal::ALL { + let answer = if refusal.is_invisible() { "404" } else { "403" }; + out.push_str(&["| `", refusal.code(), "` | ", answer, " |\n"].concat()); + } + out +} + +fn pages() -> [(&'static str, String); 2] { + [ + (AQL_FUNCTIONS, aql_functions()), + (REFUSAL_CODES, refusal_codes()), + ] +} + +#[test] +fn the_book_holds_the_current_reference_pages() { + for (page, rendered) in pages() { + let committed = std::fs::read_to_string(path(page)).expect("the reference page"); + assert!( + committed == rendered, + "{page} is out of date: run `cargo nextest run -p ferroehr-rest --test it \ + --run-ignored only reference_pages` and commit the page" + ); + } +} + +#[test] +#[ignore = "writes the book pages; run on purpose after changing the code they render"] +fn write_the_reference_pages() { + for (page, rendered) in pages() { + std::fs::write(path(page), rendered).expect("the reference page is written"); + } +} diff --git a/app/ferroehr-rest/tests/it/scim_users_http/default_definitions.rs b/app/ferroehr-rest/tests/it/scim_users_http/default_definitions.rs index dc3efadadd..7892c0f2a3 100644 --- a/app/ferroehr-rest/tests/it/scim_users_http/default_definitions.rs +++ b/app/ferroehr-rest/tests/it/scim_users_http/default_definitions.rs @@ -45,9 +45,9 @@ fn repo_file(relative: &str) -> String { std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{} is readable: {e}", path.display())) } -/// The TOML block of the book's authentication page that holds `marker`. +/// The TOML block of the book's authorization keys page that holds `marker`. fn documented_block(marker: &str) -> String { - let page = repo_file("website/book/src/installation/config-auth.md"); + let page = repo_file("website/book/src/installation/config-authz.md"); page.split("```toml\n") .skip(1) .filter_map(|block| block.split("```").next()) diff --git a/app/ferroehr-server/tests/it/cli_reference.rs b/app/ferroehr-server/tests/it/cli_reference.rs new file mode 100644 index 0000000000..68ffaf36c0 --- /dev/null +++ b/app/ferroehr-server/tests/it/cli_reference.rs @@ -0,0 +1,80 @@ +// SPDX-FileCopyrightText: Cadasto B.V. +// SPDX-License-Identifier: BUSL-1.1 + +//! The book's CLI reference, generated from the `clap` definition of +//! [`Cli`](ferroehr_server::Cli): one section per command with its long help. +//! +//! `the_book_holds_the_current_cli_reference` fails when the committed page +//! differs from what the definition renders; `write_the_cli_reference` +//! (ignored, run with `cargo nextest run -p ferroehr-server --run-ignored +//! only cli_reference`) writes the page again. + +use std::path::PathBuf; + +use clap::{Command, CommandFactory as _}; +use ferroehr_server::Cli; + +const PAGE: &str = "website/book/src/reference/cli.md"; + +/// The help width, fixed so the page does not depend on the terminal. +const WIDTH: usize = 100; + +fn page_path() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../..") + .join(PAGE) +} + +/// Appends the section of `command`, reached as `path`, and of each visible +/// subcommand below it. +fn section(out: &mut String, path: &str, command: &mut Command) { + let help = command.render_long_help().to_string(); + for piece in ["## `", path, "`\n\n```text\n", help.trim_end(), "\n```\n\n"] { + out.push_str(piece); + } + for sub in command + .get_subcommands_mut() + .filter(|sub| !sub.is_hide_set() && sub.get_name() != "help") + { + let below = [path, sub.get_name()].join(" "); + section(out, &below, sub); + } +} + +// REUSE-IgnoreStart +/// The page the definition renders. +fn render() -> String { + let mut command = Cli::command().term_width(WIDTH).max_term_width(WIDTH); + command.build(); + let mut out = String::from( + "\n\ + \n\ + \n\n\ + # Command-line reference\n\n\ + **For:** operators. Every command and option of the `ferroehr` binary,\n\ + as `ferroehr --help` prints it. The guides to the commands are\n\ + on [CLI & production checklist](../installation/config-cli.md).\n\n\ + \n\n", + ); + section(&mut out, "ferroehr", &mut command); + out.trim_end().to_owned() + "\n" +} + +// REUSE-IgnoreEnd + +#[test] +fn the_book_holds_the_current_cli_reference() { + let committed = std::fs::read_to_string(page_path()).expect("the CLI reference page"); + assert!( + committed == render(), + "{PAGE} is out of date: run `cargo nextest run -p ferroehr-server --run-ignored only \ + cli_reference` and commit the page" + ); +} + +#[test] +#[ignore = "writes the book page; run on purpose after changing the CLI"] +fn write_the_cli_reference() { + std::fs::write(page_path(), render()).expect("the CLI reference page is written"); +} diff --git a/app/ferroehr-server/tests/it/main.rs b/app/ferroehr-server/tests/it/main.rs index 7d4839dfcf..4febb0275d 100644 --- a/app/ferroehr-server/tests/it/main.rs +++ b/app/ferroehr-server/tests/it/main.rs @@ -13,6 +13,7 @@ //! path compiles out of the shipped defaults. mod authz_wiring; +mod cli_reference; mod definitions; mod exit_status; mod wiring; diff --git a/app/ferroehr/tests/it/policy_parties.rs b/app/ferroehr/tests/it/policy_parties.rs index df84c494c5..33d3eb8902 100644 --- a/app/ferroehr/tests/it/policy_parties.rs +++ b/app/ferroehr/tests/it/policy_parties.rs @@ -43,10 +43,10 @@ const ROLE: &str = "e41c7b2a-6d3f-4a9e-8b05-2f7d1c9e3a68"; /// The administrator role of the tests. const ADMIN: &str = "ADMIN"; -/// The text of the book's "Operational policy" page. +/// The text of the book's "Worked policy examples" page. fn book_page() -> String { let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../website/book/src/operational-policy.md"); + .join("../../website/book/src/policy-examples.md"); std::fs::read_to_string(path).expect("the book page is readable") } diff --git a/changelog.d/6672-book-diataxis-structure.changed.md b/changelog.d/6672-book-diataxis-structure.changed.md new file mode 100644 index 0000000000..159d3e4fac --- /dev/null +++ b/changelog.d/6672-book-diataxis-structure.changed.md @@ -0,0 +1,3 @@ +- The book is organised by what you came to do: tutorials, how-to guides for integrating and for deploying and operating, reference, explanation, and the compliance record. The introduction is a landing page that sends integrators, clinician-facing app builders, operators and decision makers to their first pages. Every page keeps its address. +- Operational policy is four pages: the policy parties, roles, care relationships and representatives, the access policy and the admin registers, and the worked policy examples, with every link moved to the section's new page. +- The longest pages are split by task: Security into Security, Access control in detail and The pseudonymisation boundary; Audit trail into Audit trail, The access log, The EHDS logging elements and Tamper evidence, seals and retrieval; Operations into Operations, Database roles, migrations and backup, Storage sizing and Upgrades; Authentication & access into it, Authorization keys and SCIM provisioning; and Kubernetes & Helm into it, its security posture and its integrations. Every link into a moved section points at its new page. diff --git a/changelog.d/6673-first-integration-tutorial.added.md b/changelog.d/6673-first-integration-tutorial.added.md new file mode 100644 index 0000000000..331a89de97 --- /dev/null +++ b/changelog.d/6673-first-integration-tutorial.added.md @@ -0,0 +1 @@ +- The book has a "Your first integration" tutorial: upload a template, create an EHR, commit, read, update and query a composition, and handle a stale `If-Match` and a missing record. Every request on the page runs against the server in CI with the status the page shows. diff --git a/changelog.d/6674-generated-cli-reference.added.md b/changelog.d/6674-generated-cli-reference.added.md new file mode 100644 index 0000000000..c728c42c88 --- /dev/null +++ b/changelog.d/6674-generated-cli-reference.added.md @@ -0,0 +1,2 @@ +- The book has a Command-line reference generated from the `ferroehr` binary's own `clap` definition: every command and option as `--help` prints it. A test fails when the page and the binary disagree. +- The book has two more reference pages generated from the code, each checked by a test: the AQL built-in functions the parser accepts, and every access refusal code with the status its caller receives. diff --git a/changelog.d/6675-operator-docs-v6.changed.md b/changelog.d/6675-operator-docs-v6.changed.md new file mode 100644 index 0000000000..83282921e3 --- /dev/null +++ b/changelog.d/6675-operator-docs-v6.changed.md @@ -0,0 +1 @@ +- The operator documentation is current for v6: storage sizing carries one run against a pinned v6 image on PostgreSQL 19 (vital signs at 14.0 KB per committed version and about 1.5 KB per access-log entry), the Helm upgrade steps join the upgrade page, and Docker Compose and the admin API each split into a page for the everyday task and a page for the overlays or the storage routes. diff --git a/changelog.d/6676-book-history-removed.removed.md b/changelog.d/6676-book-history-removed.removed.md new file mode 100644 index 0000000000..2342239633 --- /dev/null +++ b/changelog.d/6676-book-history-removed.removed.md @@ -0,0 +1,2 @@ +- The book describes only the current release: the notes on configuration keys earlier releases read, the RabbitMQ migration steps, the release-by-release provenance history and the per-issue measurement trail are gone, PostgreSQL documentation is cited at version 19, and the steady-state access-log sizing points at the performance gate's measured bytes instead of figures from an earlier storage layout. +- The book no longer cites the removed `[authz.professional]` key in the audit trail and shared-responsibility pages, and its prose drops the em-dash habit outside the compliance record's revision logs and the viewer pages. diff --git a/docs/law/nl/nen-7513/PROVENANCE.md b/docs/law/nl/nen-7513/PROVENANCE.md index e32d6e1144..8984c8a500 100644 --- a/docs/law/nl/nen-7513/PROVENANCE.md +++ b/docs/law/nl/nen-7513/PROVENANCE.md @@ -33,7 +33,7 @@ each one and names its 2024 clause (#5136). | §5, the content of a logged event | `website/book/src/audit.md` (the field-by-field table) | Every item the clause lists is mapped to the field of the access record that carries it, including the two a deployment must supply itself (`purpose`, `legal_basis`) | | Actor role | `website/book/src/compliance/control-matrix.md`, `website/book/src/security/dpia.md` | The access record carries the roles the caller held at access time, as FHIR `agent.role` and as a DICOM `RoleIDCode` | | Event content | `website/book/src/compliance/control-matrix.md`, `website/book/src/security/dpia.md`, `website/book/src/security/records-of-processing.md` | Per-domain access logging for reads and queries, aligned with this standard and EHDS Annex II 3.2 | -| Retention | `website/book/src/audit.md`, `website/book/src/compliance/control-matrix.md`, `website/book/src/security/dpia.md` | The retention floor for the NL jurisdiction, which the Besluit vaststelling bewaartermijn logging binds to this standard | +| Retention | `website/book/src/ehds-logging.md`, `website/book/src/compliance/control-matrix.md`, `website/book/src/security/dpia.md` | The retention floor for the NL jurisdiction, which the Besluit vaststelling bewaartermijn logging binds to this standard | The retention chain is followable without holding the standard, because the legal end of it is vendored: `docs/law/nl/begz/` (Art. 5 delegates the diff --git a/scripts/checks/docs-claims.sh b/scripts/checks/docs-claims.sh index 20e10654fc..ed0ef14f13 100755 --- a/scripts/checks/docs-claims.sh +++ b/scripts/checks/docs-claims.sh @@ -66,7 +66,7 @@ VALUES=deploy/helm/ferroehr/values.yaml # went silently stale when the hardening chapter split into sub-pages (#2348), # leaving five chart pages unchecked while the gate reported OK. CHART_PAGES=$(printf '%s ' "$BOOK"/installation/kubernetes*.md "$BOOK"/installation/hardening-*.md \ - "$BOOK"/operations.md "$BOOK"/operations-admin-apis.md) + "$BOOK"/operations.md "$BOOK"/database-operations.md "$BOOK"/upgrades.md "$BOOK"/operations-admin-apis.md "$BOOK"/storage-admin-apis.md "$BOOK"/installation/compose*.md) for required in "$TOML" "$VALUES"; do [[ -f "$required" ]] || { echo "docs-claims: missing authority file $required" >&2; exit 1; } diff --git a/scripts/perf/storage-sizing.sh b/scripts/perf/storage-sizing.sh index 7f62014112..0a3b853180 100755 --- a/scripts/perf/storage-sizing.sh +++ b/scripts/perf/storage-sizing.sh @@ -3,7 +3,7 @@ # SPDX-License-Identifier: BUSL-1.1 # The storage sizing driver: what one composition version, one node row and # one audit record take on disk, measured against a running FerroEHR. It is -# the measurement behind the book's storage sizing section (operations.md, +# the measurement behind the book's storage sizing page (storage-sizing.md, # "Storage sizing"). # # `run` drives the server over ITS-REST in phases, with a fixed count per @@ -273,8 +273,8 @@ EOF return 1 fi # The book's sizing section names this command, so it reproduces its figures. - grep -q 'scripts/perf/storage-sizing.sh run' "$ROOT_DIR/website/book/src/operations.md" || { - echo "self-test FAILED: website/book/src/operations.md does not name scripts/perf/storage-sizing.sh run" >&2 + grep -q 'scripts/perf/storage-sizing.sh run' "$ROOT_DIR/website/book/src/storage-sizing.md" || { + echo "self-test FAILED: website/book/src/storage-sizing.md does not name scripts/perf/storage-sizing.sh run" >&2 return 1 } echo "storage-sizing.sh self-test: the report shape and the book's pointer pass" diff --git a/scripts/vendor/law-nl.sh b/scripts/vendor/law-nl.sh index 4df72e4659..3b4afd807d 100755 --- a/scripts/vendor/law-nl.sh +++ b/scripts/vendor/law-nl.sh @@ -341,7 +341,7 @@ each one and names its 2024 clause (#5136). | §5, the content of a logged event | \`website/book/src/audit.md\` (the field-by-field table) | Every item the clause lists is mapped to the field of the access record that carries it, including the two a deployment must supply itself (\`purpose\`, \`legal_basis\`) | | Actor role | \`website/book/src/compliance/control-matrix.md\`, \`website/book/src/security/dpia.md\` | The access record carries the roles the caller held at access time, as FHIR \`agent.role\` and as a DICOM \`RoleIDCode\` | | Event content | \`website/book/src/compliance/control-matrix.md\`, \`website/book/src/security/dpia.md\`, \`website/book/src/security/records-of-processing.md\` | Per-domain access logging for reads and queries, aligned with this standard and EHDS Annex II 3.2 | -| Retention | \`website/book/src/audit.md\`, \`website/book/src/compliance/control-matrix.md\`, \`website/book/src/security/dpia.md\` | The retention floor for the NL jurisdiction, which the Besluit vaststelling bewaartermijn logging binds to this standard | +| Retention | \`website/book/src/ehds-logging.md\`, \`website/book/src/compliance/control-matrix.md\`, \`website/book/src/security/dpia.md\` | The retention floor for the NL jurisdiction, which the Besluit vaststelling bewaartermijn logging binds to this standard | The retention chain is followable without holding the standard, because the legal end of it is vendored: \`docs/law/nl/begz/\` (Art. 5 delegates the diff --git a/website/book/src/SUMMARY.md b/website/book/src/SUMMARY.md index 82eea62570..1dceb7870c 100644 --- a/website/book/src/SUMMARY.md +++ b/website/book/src/SUMMARY.md @@ -2,46 +2,21 @@ [Introduction](introduction.md) -# Evaluate +# Tutorials -- [Why FerroEHR exists](why-ferroehr.md) -- [Concepts](concepts/index.md) - - [openEHR primer](concepts/openehr-primer.md) - - [System architecture](concepts/architecture.md) - - [Storage architecture](concepts/storage.md) - - [The AQL engine](concepts/aql-engine.md) - - [How FerroEHR decides access](explanation/access-model.md) -- [Conformance](conformance.md) -- [Performance](performance.md) - - [Capacity](capacity.md) -- [Benchmarks](benchmarks.md) -- [Licensing & legal](licensing.md) - - [Compliance overview](compliance/index.md) - - [Shared responsibility](compliance/shared-responsibility.md) - - [Retention, restriction and objection](compliance/retention.md) - - [Secondary use](compliance/secondary-use.md) - - [Control matrix](compliance/control-matrix.md) - - [Cyber Resilience Act](compliance/cra.md) - - [CRA information and instructions to the user](compliance/cra-user-information.md) - - [Complaints, incidents and vulnerabilities](compliance/post-market.md) - - [Intended purpose](compliance/intended-purpose.md) - - [CRA risk assessment](compliance/cra-risk-assessment.md) - - [Hazard log: the logging component](compliance/hazard-log.md) - - [The logging component's intended performance](compliance/logging-performance.md) - - [The EHDS logging checklist](compliance/logging-checklist.md) - - [EEHRxF metadata from the Reference Model](compliance/eehrxf-annex-iii.md) - - [PDF/A originals](compliance/eehrxf-pdf-originals.md) - - [Claims review](compliance/claims-review.md) +- [Getting started](getting-started.md) +- [Your first integration](tutorials/first-integration.md) +- [Try it in Codespaces](installation/codespaces.md) -# Integrate +# How-to guides: integrate -- [Getting started](getting-started.md) - [Using the API](using-the-api/index.md) - [Resource walkthroughs](using-the-api/resources.md) - - [Content negotiation & errors](using-the-api/content-negotiation.md) - - [Problem types](using-the-api/problems.md) - [Querying with AQL](querying-aql.md) - [Templates & validation](templates-validation.md) +- [SMART App Launch](smart-app-launch.md) + - [Behind FerroSMART](behind-ferrosmart.md) + - [The xShare Yellow Button](xshare-yellow-button.md) - [Beyond the core](beyond-core/index.md) - [EHR Extract & messaging](beyond-core/messaging.md) - [FerroEHR as a federation node](beyond-core/federation-node.md) @@ -49,14 +24,15 @@ - [Terminology servers](beyond-core/terminology.md) - [Change events (outbox feed)](beyond-core/outbox-feed.md) - [S3 multimedia](beyond-core/s3-multimedia.md) -- [Rust crates](crates.md) -# Operate +# How-to guides: deploy and operate - [Installation](installation/index.md) - - [Try it in Codespaces](installation/codespaces.md) - [Docker Compose](installation/compose.md) + - [Overlays and profiles](installation/compose-overlays.md) - [Kubernetes & Helm](installation/kubernetes.md) + - [Security posture, probes and authentication](installation/kubernetes-security.md) + - [Integrations](installation/kubernetes-integrations.md) - [Running several instances](installation/several-instances.md) - [Cluster hardening](installation/kubernetes-hardening.md) - [The cluster: hosts, control plane, access](installation/hardening-cluster.md) @@ -65,31 +41,27 @@ - [Namespaces, network & policy](installation/hardening-network-policy.md) - [Secrets, detection & response](installation/hardening-detection-response.md) - [From source](installation/from-source.md) - - [Configuration reference](installation/configuration.md) - - [Server, database & telemetry](installation/config-server.md) - - [Authentication & access](installation/config-auth.md) - - [Integrations](installation/config-integrations.md) - - [Audit](installation/config-audit.md) - - [Privacy & data minimisation](installation/config-privacy.md) - - [CLI & production checklist](installation/config-cli.md) - - [Every configuration key](installation/config-keys.md) - - [Default demographic definitions](installation/default-demographic-definitions.md) - [Party binding: bootstrap and migration](installation/party-binding-migration.md) -- [Security](security.md) - - [Verifying releases](verifying-releases.md) - - [Threat model](threat-model.md) - - [Data protection impact assessment](security/dpia.md) - - [Records of processing](security/records-of-processing.md) - - [Go-live checklist](security/go-live-checklist.md) - - [Who is the committer](security/committer.md) - [Enterprise identity providers](identity-providers.md) - - [SMART App Launch](smart-app-launch.md) - - [Behind FerroSMART](behind-ferrosmart.md) - - [The xShare Yellow Button](xshare-yellow-button.md) +- [Verifying releases](verifying-releases.md) +- [Go-live checklist](security/go-live-checklist.md) +- [Operations](operations.md) + - [Database roles, migrations and backup](database-operations.md) + - [Storage sizing](storage-sizing.md) + - [Upgrades](upgrades.md) + - [Operational policy](operational-policy.md) + - [Roles, care relationships and representatives](caller-facts.md) + - [The access policy and the admin registers](access-policy.md) + - [Worked policy examples](policy-examples.md) - [Audit trail (IHE ATNA)](audit.md) + - [The access log](access-log.md) + - [The EHDS logging elements](ehds-logging.md) + - [Tamper evidence, seals and retrieval](audit-integrity.md) - [Version signing](signing/index.md) - [Digest signing](signing/digest.md) - [PGP signing](signing/pgp.md) + - [Returning to the original state](operations-reset.md) + - [Decommissioning](operations-decommissioning.md) - [FerroEHR Viewer](viewer/index.md) - [Dashboard & queries](viewer/queries.md) - [Templates & EHRs](viewer/browsing.md) @@ -98,15 +70,73 @@ - [Server & audit log](viewer/server.md) - [Access control](viewer/access-control.md) - [Preferences & the theme](viewer/preferences.md) -- [Operations](operations.md) - - [Access path metrics and runbooks](operations-access-path.md) - - [Admin & messaging APIs](operations-admin-apis.md) - - [Operational policy](operational-policy.md) - - [Care relationships and episodes of care](care-relationships.md) - - [What the CDR leaves to the application](application-boundary.md) - - [Usage report](usage-report.md) - - [Returning to the original state](operations-reset.md) - - [Decommissioning](operations-decommissioning.md) + +# Reference + +- [Configuration reference](installation/configuration.md) + - [Server, database & telemetry](installation/config-server.md) + - [Authentication & access](installation/config-auth.md) + - [Authorization keys](installation/config-authz.md) + - [SCIM provisioning](installation/config-scim.md) + - [Integrations](installation/config-integrations.md) + - [Audit](installation/config-audit.md) + - [Privacy & data minimisation](installation/config-privacy.md) + - [CLI & production checklist](installation/config-cli.md) + - [Every configuration key](installation/config-keys.md) + - [Default demographic definitions](installation/default-demographic-definitions.md) +- [Command-line reference](reference/cli.md) +- [AQL built-in functions](reference/aql-functions.md) +- [Access refusal codes](reference/refusal-codes.md) +- [Content negotiation & errors](using-the-api/content-negotiation.md) + - [Problem types](using-the-api/problems.md) +- [Admin & messaging APIs](operations-admin-apis.md) + - [Storage integrity, dump and load](storage-admin-apis.md) +- [Access path metrics and runbooks](operations-access-path.md) +- [Usage report](usage-report.md) +- [Rust crates](crates.md) +- [Conformance](conformance.md) +- [Performance](performance.md) + - [Capacity](capacity.md) + - [Benchmarks](benchmarks.md) + +# Explanation + +- [Why FerroEHR exists](why-ferroehr.md) +- [Concepts](concepts/index.md) + - [openEHR primer](concepts/openehr-primer.md) + - [System architecture](concepts/architecture.md) + - [Storage architecture](concepts/storage.md) + - [The AQL engine](concepts/aql-engine.md) +- [How FerroEHR decides access](explanation/access-model.md) + - [Care relationships and episodes of care](care-relationships.md) + - [What the CDR leaves to the application](application-boundary.md) + - [Who is the committer](security/committer.md) +- [Security](security.md) + - [Access control in detail](access-control.md) + - [The pseudonymisation boundary](pseudonymisation.md) + - [Threat model](threat-model.md) + +# Compliance + +- [Licensing & legal](licensing.md) +- [Compliance overview](compliance/index.md) + - [Shared responsibility](compliance/shared-responsibility.md) + - [Retention, restriction and objection](compliance/retention.md) + - [Secondary use](compliance/secondary-use.md) + - [Control matrix](compliance/control-matrix.md) + - [Data protection impact assessment](security/dpia.md) + - [Records of processing](security/records-of-processing.md) + - [Cyber Resilience Act](compliance/cra.md) + - [CRA information and instructions to the user](compliance/cra-user-information.md) + - [Complaints, incidents and vulnerabilities](compliance/post-market.md) + - [Intended purpose](compliance/intended-purpose.md) + - [CRA risk assessment](compliance/cra-risk-assessment.md) + - [Hazard log: the logging component](compliance/hazard-log.md) + - [The logging component's intended performance](compliance/logging-performance.md) + - [The EHDS logging checklist](compliance/logging-checklist.md) + - [EEHRxF metadata from the Reference Model](compliance/eehrxf-annex-iii.md) + - [PDF/A originals](compliance/eehrxf-pdf-originals.md) + - [Claims review](compliance/claims-review.md) # Contribute diff --git a/website/book/src/access-control.md b/website/book/src/access-control.md new file mode 100644 index 0000000000..3fd7a3ca7c --- /dev/null +++ b/website/book/src/access-control.md @@ -0,0 +1,833 @@ +# Access control in detail + +How each layer of authorization behaves and what it answers. The model as a whole is on +[How FerroEHR decides access](explanation/access-model.md). + + + + +Authorization has two composable layers. The per-EHR `EHR_ACCESS` gate with +the access evaluator is the openEHR-grounded base and is always on; the coarse +role layer is active when authentication is enabled. A request must clear every +active layer. Deployments serving SMART apps can enable a third, token-scope +layer on top; see [SMART App Launch](smart-app-launch.md). The access +evaluator alone confines a patient to their own EHR +([a patient's own EHR](#a-patients-own-ehr)). + +The model as a whole (parties, roles and grants, the patient's settings, the +access policy, justification and the legal marks) is explained on [How +FerroEHR decides access](explanation/access-model.md). This section holds the +details of each part. + +## Per-EHR access control (`EHR_ACCESS`) + +Every EHR carries a versioned `EHR_ACCESS` object, the openEHR +access-decision authority for that record. A new EHR has no settings, and what +that admits is a **server-wide choice**: + +| `authz.rbac.ehr_access_default` | An EHR with no settings | +|---|---| +| `open` *(default)* | reachable by any caller the coarse layers already admitted | +| `restricted` | reachable only by `authz.rbac.admin_role` | + +`open` is the default because it is what every existing deployment runs, and +changing it changes who can read existing records. `restricted` is object-level +**default-deny**, and it is the setting to reach for if your threat model +includes a caller enumerating record ids: a server-created `ehr_id` is a +time-ordered UUIDv7, so it is not even unpredictable, and the OWASP +[Insecure Direct Object Reference Prevention](https://cheatsheetseries.owasp.org/cheatsheets/Insecure_Direct_Object_Reference_Prevention_Cheat_Sheet.html) +cheat sheet is explicit that an unpredictable identifier is not itself an access +control. + +> [!NOTE] +> Under `restricted`, the admin role still reaches a setting-less EHR. That is +> deliberate: a plain deny would make such a record unreachable by everyone +> (including the operator who would author the settings that fix it) which is an +> outage rather than a control. A patient reaches only their own EHR +> ([a patient's own EHR](#a-patients-own-ehr)); this key decides only the +> default disposition. + +Committing settings of the `access_directives` scheme switches that EHR to +explicit policy, and those settings **always win over the server default**, +in both directions. The settings are an `ACCESS_DIRECTIVE_SETTINGS`, a class +of FerroEHR's draft access control package, and every coded value is a code +of the access control groups of the draft openEHR access terminology `openehr_access`: + +```json +{ + "_type": "EHR_ACCESS", + "name": { "_type": "DV_TEXT", "value": "EHR Access" }, + "archetype_node_id": "openEHR-EHR-EHR_ACCESS.access_directives.v1", + "archetype_details": { + "_type": "ARCHETYPED", + "archetype_id": { "_type": "ARCHETYPE_ID", + "value": "openEHR-EHR-EHR_ACCESS.access_directives.v1" }, + "rm_version": "1.2.0" + }, + "settings": { + "_type": "ACCESS_DIRECTIVE_SETTINGS", + "default_access": { + "_type": "DV_CODED_TEXT", "value": "restricted", + "defining_code": { "_type": "CODE_PHRASE", + "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, + "code_string": "restricted" } + }, + "gate_keepers": [ + { "_type": "PARTY_SELF" }, + { "_type": "PARTY_RELATED", + "external_ref": { "_type": "PARTY_REF", "namespace": "demographic", "type": "PERSON", + "id": { "_type": "HIER_OBJECT_ID", + "value": "0190b3a2-5a3e-7c1d-9e2f-3b4c5d6e7f80" } }, + "relationship": { "_type": "DV_CODED_TEXT", "value": "guardian", + "defining_code": { "_type": "CODE_PHRASE", + "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr" }, + "code_string": "10" } } } + ] + } +} +``` + +- **Default access:** `open` admits any caller the other layers admit. + `restricted` admits the administrator (`authz.rbac.admin_role`), the + gate-keepers, a caller with a live care relationship to the subject and a + caller a consent permit names; `consent_required` admits the + administrator, the gate-keepers and a caller a consent permit names. Every + other caller gets `403` with `refused-consent-required`. The record's + person always reads their own record. An EHR Extract export by manifest + (`POST /message/export`) passes the access evaluator for every EHR the + manifest names before it reads any content, so one EHR the caller may not + reach refuses the whole export. +- **Who writes the settings:** while the current settings name no + gate-keeper, the record's person writes their own settings, as a + mentally competent adult is their own gate-keeper (BASE Architecture + Overview, Access Control). Once the settings name gate-keepers, a new + `EHR_ACCESS` version is committed only by a gate-keeper they name. + `PARTY_SELF` names the record's person; any other gate-keeper names a + party of the demographic service by its `external_ref`, matched against + the `PERSON` the caller is bound to. Naming gate-keepers without + `PARTY_SELF`, such as a guardian, takes the person's own write away. + Changing `gate_keepers` is itself a write, so only a current writer + changes them. An administrator acting on the person's instruction writes + in every case. Settings held closed are written only by an administrator. + Every other caller is refused with `403`. A gate-keeper commits changes with a + CONTRIBUTION (there is no dedicated `EHR_ACCESS` endpoint in the openEHR + REST API). The controller commits them on the person's instruction with + `POST /ferroehr/rest/extensions/v1/admin/ehr-access`, which names the EHR + in its body, so it reaches an EHR a restriction hides, and reads every + version with `GET /ferroehr/rest/extensions/v1/admin/ehr-access?ehr_id=…`. + Every change is versioned and audited like all record content. +- **Who reads the settings:** the administrator, the record's person and the + gate-keepers. To anyone else the settings are absent, so a restriction stays + invisible to a provider (EHDS Art. 8): an AQL query returns no + `EHR_ACCESS` row of the EHR, an EHR Extract leaves its `EHR_ACCESS` out, + and a CONTRIBUTION that commits an `EHR_ACCESS` version reads as unknown + (`404`). One caller more receives the `EHR_ACCESS` in an EHR Extract: the + holder of an `export_ehr_extract` grant whose `subject_namespace` covers + the EHR, such as a migration client, since the extract transfers the whole + EHR and an import elsewhere must keep the person's directives. Those + callers read the settings over the wire with + `GET /ferroehr/rest/extensions/v1/ehr/{ehr_id}/ehr_access` and its + `versioned_ehr_access` reads, a FerroEHR extension shaped on the + `EHR_STATUS` reads ([Resource walkthroughs](using-the-api/resources.md#ehr_access)), + which another product uses to exchange the directives. +- **Every write is checked:** a CONTRIBUTION, an EHR Extract import and an + admin archive load that carry settings are refused whole naming the first + defect: with `400` for settings of another scheme or a member the class does not + declare, and with `422` for a broken invariant of the draft package, named + as `CLASS.Invariant`, such as `ACCESS_DIRECTIVE.Restriction_denies`, or a + `DV_DATE_TIME` or `DV_DURATION` that is no ISO 8601 value + (`DV_DATE_TIME.Value_valid`). The + same writes, and the controller's commit, refuse with `422` a directive + that names a party the demographic service does not hold, naming the + directive and the party: an actor scope's `party`, or the `external_ref` + of the `instructed_by` party, in the directive or any of its exceptions. A + reference of another type than the party it names is refused the same + way, and so is an id that is no UUID, since the evaluator could never + match it to a caller. A gate-keeper whose `external_ref` names such a + party is refused the same way, naming the gate-keeper, since it would lock + the settings to nobody. An import may name a party its own demographics + chapter carries, and an archive load one its demographic records carry. + An import and an archive load check only the head `EHR_ACCESS` version, + the one in force: an earlier version is the unchanged record of what was + in force then and decides nothing, so a party erased since (under GDPR + Art. 17, for example) never blocks a faithful restore of your own export. + `PARTY_SELF` names the record's person and needs no lookup. +- **Unreadable settings:** stored settings that do not read as the scheme + hold the EHR closed. A request that names the EHR is refused with `500`, + no query reaches it, and the server logs an error naming it. Only settings + stored before the write check can hold an EHR. An administrator repairs a + held EHR with + `POST /ferroehr/rest/extensions/v1/admin/ehr-access/repair`, body + `{"ehr_id": "…", "settings": {…}}`: the new settings must pass the write + check, the repair commits a new `EHR_ACCESS` version with its own commit + audit and contribution, and it writes an access record + (`ehr-access-repair:`) naming the administrator. The + repair is refused with `409` for an EHR that is not held; such an EHR + changes its settings with a CONTRIBUTION. +- **Every replica decides by the committed settings:** the commit of an + `EHR_ACCESS` version writes the EHR's settings into a side table in the + same transaction, as a settings class and its facts, and notifies every + replica when it commits. The class is what the EHR's settings share with + others, and the facts are what is particular to the EHR: instants, parties, + objects and origins. Every opt-out from a date shares one class. Each + replica holds a copy of the settings of the EHRs it read most recently and + of every class, and drops an entry on that notification, so a revoked + gate-keeper or directive decides the next request on every replica. A query + reads each EHR's class and facts in its own SQL, so its counts and pages + stay exact. An EHR of a class the replica has not copied yet contributes no + row. While a replica's listener is down it reads the settings on every + request, and a settings store that cannot answer is `503`. The first boot + fills the side table from the stored versions, and + `ferroehr party-binding refill` rebuilds it. +- **What a replica holds does not grow with the EHRs that carry settings:** + at most 4096 EHRs' settings and the settings classes. The measured sizes + and times, against the whole-set copy this replaced: + +{{#include ../generated/access-index-bench.md}} +- **The access evaluator decides every request:** see + [Access directives](#access-directives) below. +- **The default definition:** every boot stores the archetype + `openEHR-EHR-EHR_ACCESS.access_directives.v1.0.0` when no definition of its + id is stored, and never over a stored one. It constrains the settings to + `ACCESS_DIRECTIVE_SETTINGS` and its attributes; the definition upload + validates an archetype that names a class of the draft access control + package against the RM extended by that package. FerroEHR reads the + settings by their codes, never by this id, so a deployment may use its own. + +The scheme is a FerroEHR extension: openEHR mandates the `EHR_ACCESS` object +and its change control but publishes no concrete access-control scheme. The +decision also holds for AQL, ad-hoc and stored queries alike: data the caller +may not read contribute no rows, whether the query names the EHR in its +`WHERE` clause, in an `EHR` predicate, through the `ehr_id` parameter, or not +at all, as in a population query, and `COUNT`, `LIMIT` and `OFFSET` count only +the rows the caller reads. + +## Access directives + +The access evaluator decides every request that reaches an EHR. Its steps, +refusal codes and answers are on [How FerroEHR decides +access](explanation/access-model.md#how-one-request-is-decided); the rules +below say when each step applies. + +- **Who is bound.** The record's person skips every step on their own EHR + (EHDS Art. 3), so no controller rule limits a patient's own access, and is + refused at step 0 on any other. A caller bound to the person reads their own + record as the person, unless it performs a professional `ROLE`: then its + read is a professional's, refused at step 5 as a conflict of interest, and + the staff member reads their own record under their own login. A + representative reaches only the EHR of the subject it represents, refused + at step 0 on any other, and is held there to steps 1 to 3 and 5 and skips + the others (Art. 4(2)): a controller rule can keep, say, a minor's confidential + data from a parent. + An access service is a caller holding an `access_service` grant or a + verified caller of a `federation` issuer. +- **When a directive applies.** Every attribute an `applies_to` entry sets + must hold for the caller: the party (its own `PERSON` or `AGENT`, a care + team it is a member of, the provider its client acts for, or a `GROUP` + that provider is a member of), a role it performs (the coded `name` of a + `ROLE` in force it performs, compared by terminology and code; a token's + role claims never count), the `care` relationship (a live care relationship), the + `representative` and `proxy` relationships, or its caller kind. Its + `operations` (`read`, `write`, `export`, `query`), `purposes` and + `time_validity` must hold too, and its `data` scopes say which data it + covers: objects, templates, root archetypes, categories (through the + [category map](audit.md)), sensitivities, origins and commit time. One + level of `exceptions` of the opposite effect narrows it. +- **A fact that cannot be read never opens data.** A `time_validity` bound + with no offset, or a commit with no recorded origin, is read as covered by + a deny and not by a permit, and so is a purpose the request does not + declare, against a directive of the person. +- **A purpose is declared.** The caller states the purpose, and the access + policy's `purpose_required` refuses a request without one at step 4. A + controller rule's `purposes` therefore match only a purpose the request + declares: "no medical examination" refuses that purpose and nothing else, + and a request with no purpose under a policy that does not require one is + not refused by a purpose rule. +- **Emergencies.** An emergency is a + [justification](#justified-access-outside-the-care-relationships) of the + access policy whose `emergency` is set. A caller it names that declares + its purpose and states a reason reads data a restriction, a consent deny, + an exclusion or a deny rule covers where its `emergency_override` holds, + and passes steps 6 to 8 (Art. 11(5)); an access service that may override + an opt-out reads an opted-out EHR the same way, unless it acts for the + person (Art. 10(2)). A directive whose `emergency_override` is false binds + in every emergency, as an absolute opt-out of the Member State's law does + (recital 55). Each such access is recorded as an emergency with its + reason. +- **Writes.** A write is judged by steps 1 and 2 for the EHR as a whole and + by steps 3 to 8 for the version it commits: its template, root archetype, + origins and the sensitivities the policy's classifications give it. A + restriction and an opt-out restrict who sees data, not its recording + (EHDS Art. 8): no write is refused for its content by either, so care is + always documented and a write never reveals one, and the data written stay + restricted for reading. Where the answer depends on the + datum, the first step that refuses that datum answers, for a named object + as for a written version, before any step about the EHR alone. +- **Every decision is a copy.** The settings, the caller facts and the access + policy are held on each replica and dropped on the notification of the + commit that changes them, so a decision adds no database transaction. A + named object is read for its template, archetype, origins and commit time + only when a directive, label or classification of the EHR depends on them. +- **Refusals.** A `403` names its code in `detail`, and with + `Prefer: return=representation` in the `refusal` member, with the + `legal_grounds` of the controller rules that refused at step 5 + ([problem types](using-the-api/problems.md#forbidden)). Steps 1 and 2 say + nothing. + +The decision procedure, its order and its codes are FerroEHR's own design: +RM EHR IM §EHR Access requires every decision to follow `EHR_ACCESS`, and +publishes no procedure. + +## Care relationships + +Where the [access policy](#the-access-policy) sets +`care_relationship_required`, a professional reads a patient's clinical data +only while a care relationship to the patient is live: the professional's +`PERSON` is a member of a care team or unit the patient's `PERSON` is under +the care of, and the admission has begun and has not ended more than the +policy's `relationship_grace` ago. Otherwise step 7 refuses with +`403 refused-no-care-relationship`. openEHR leaves it to the care delivery +environment to say who cares for whom (BASE Architecture Overview, §The +Problem of Roles), so your ADT system writes admissions and team rosters +under the `write_care_relationship` grant, or your identity provider +provisions care teams as SCIM Groups. An admission, a transfer, a discharge +or a membership change decides the next request on every replica. + +A query that names no EHR reads care from the care projection, which a +replica uses only while it reflects the care facts the replica holds, so a +discharge or a removed membership never admits from a stale row +([The care projection](installation/config-privacy.md#the-care-projection)). +How the relationships are modelled is on +[Caller facts: roles and care relationships](caller-facts.md#caller-facts-roles-and-care-relationships). + +## Sensitivity + +Data carries a sensitivity from two places: a label on a single object in +the person's `EHR_ACCESS` settings, and a classification in the access +policy that gives every object it covers (by template, root archetype, +category or origin) its sensitivities. Sensitivity codes are those of your +jurisdiction's terminology, such as HL7 `HL7_Confidentiality` and +`HL7_ActCode`. Step 6 refuses data with a sensitivity that no applying permit +names, with `403 refused-sensitivity`. Two permits clear a caller: a consent +permit of the person whose `data` names the sensitivity, and a permit rule +of the access policy, such as one that clears the psychiatrist role for +`PSY`. No capability or token claim clears a caller. + +## Record confidentiality + +The controller can protect a whole record, for example of a public figure, +a staff member or a person under protection, by setting a confidentiality +marking in the record's `EHR_ACCESS` settings: the `marking` of +`ACCESS_DIRECTIVE_SETTINGS`, a `CONFIDENTIALITY_MARKING` with the level, who +set it, when and why. The level is a code of HL7 `HL7_Confidentiality`: `N` +normal (the same as no marking), `R` restricted or `V` very restricted +(`U`, `L` and `M` read as `N`). A label on one object can carry a marking +too, and a classification of the access policy a `confidentiality`; the +confidentiality of a datum is the highest of the three. + +- **Who sets it.** Only the controller, through `POST /admin/ehr-access` + (or a CONTRIBUTION by a holder of the administrator role). A version a + patient or another gate-keeper commits must carry the current marking + unchanged; one that sets, changes or clears it is refused `403` whole. +- **Who reads the record.** Step 6 refuses data above `N` that no applying + permit clears. A permit clears a datum when one of its `data` scopes + names, in `confidentialities`, the datum's level or a higher one, so a + permit for `V` also clears `R`. With no rule that names a level, a marked + record is read by its subject alone. A typical policy permits `R` to + callers with a care relationship (`applies_to` with `relationship` `care`) + for a treatment purpose, and `V` to a named role. The patient still reads + their own record, and an emergency justification invoked with a reason + lifts the step, recorded in the access log. +- **What a refused caller sees.** A named read answers `403 + refused-confidentiality`, which names neither the level nor the reason, so + `R` and `V` answer alike. A level listed in the access policy's + `concealed_confidentialities` answers `404`, as an unknown record. A + query, an export and `GET /ehr?subject_id=` always leave a refused record + out, inside the query's one SQL statement, so `COUNT`, `LIMIT` and paging + agree. +- **Who reads the marking.** The subject and the controller read the + `EHR_ACCESS` settings whole. A representative, and any other gate-keeper + who is not the subject, reads them without `marking`, since the marking + itself says the record is protected. That holds on every route that + serves the settings: `GET /ehr/{ehr_id}/ehr_access` and the + `versioned_ehr_access` reads, a CONTRIBUTION read with `Prefer: + resolve_refs`, an EHR Extract (unless the caller holds an + `export_ehr_extract` grant, whose extract moves the marking with the + record) and AQL, where a whole `EHR_ACCESS` or its `settings` comes + without the marking (no path below `settings` resolves in AQL, for any + reader, so no query filters on the marking). A version served this way no + longer holds the data its `signature` signs, so it carries no `signature`, + and the REST response says so in the header `Redacted: marking`, a header + of this CDR's own design (no openEHR or HTTP specification defines one). +- **The access log.** Every access to a marked record carries the level as + the entry's security label (the BALP `entity.securityLabel` in the + `v3-Confidentiality` system), a refusal names the marking's level in its + description, and the controller's commit that sets or clears a marking is + an entry naming the level it set or cleared. + +## The access policy + +The controller's access policy is one versioned `ACCESS_POLICY` that holds +for every EHR this FerroEHR keeps: the classifications above, whether access +needs a declared purpose (step 4) and a care relationship (step 7), the +controller's rules (step 5, EHDS Art. 11(3)), the catalogue of named +directives a person accepts by reference, and the restrictions of the +access log's subject view. An administrator holding the +`write_access_policy` grant writes it over the admin API, and it decides the +next request on every replica. Its `justifications` say who may open a +record outside their care relationships, and in an emergency +([below](#justified-access-outside-the-care-relationships)). The trust and +the floor stay in `ferroehr.toml`: `authz.rbac.admin_role` and +`ehr_access_default`. The policy can only tighten them. Until you write one, +nothing is tightened and nobody is admitted on a justification. The model and +the rules are on [The access policy](access-policy.md#the-access-policy). + +## Justified access outside the care relationships + +A clinician sometimes needs a record outside their caseload: a consultation, +a second opinion, a colleague's patient on a shift, or an emergency. Your +EHR lets them open it when your access policy allows it for the purpose they +declare, asks them why, and FerroEHR keeps the reason in the access record +the patient reads (EHDS Art. 9 and Annex II 3.2, Art. 11(5)). The +justification, the header and the bound of the reason are this CDR's own +design; the purposes are HL7 v3 `ActReason` codes, and the reason travels +on as the text of the purpose of use (FHIR R4 `AuditEvent.purposeOfEvent` +and `agent.purposeOfUse`, IHE BALP). + +- **The policy.** Each entry of `ACCESS_POLICY.justifications` names the + `purposes` that invoke it, the callers that may (`applies_to`, actor + scopes as in a rule: a role they perform, a party, a caller kind; void + means every professional), and whether it is an `emergency`. Without + `justifications` nobody is admitted on one. +- **The request.** The clinician declares the purpose in `x-purpose-of-use` + and the reason in `x-access-reason` (`[audit] reason_header`): their own + words, percent-encoded UTF-8 (RFC 3986 §2.1) so any language travels in an + HTTP header, 1 to 1000 characters after decoding, with no control + character. A malformed or longer value is a `400` naming the header, and + nothing is recorded in part. +- **The decision.** The first justification whose purposes hold the + declared purpose and whose `applies_to` names the caller is invoked. It + stands in for a live care relationship at steps 7 and 8 for the data no + relationship of the caller covers: with a reason they are admitted, and + without one they are refused `403 refused-reason-missing`, which tells + your EHR to ask the clinician why. Inside the caller's care relationships + no reason is asked. An emergency justification lifts each + `emergency_override` and steps 6 to 8, and needs the reason before any + directive is read, so its refusal never reveals a restriction. +- **What it never lifts.** A justification that is no emergency lifts no + restriction, opt-out, consent deny, exclusion, controller rule, + sensitivity, confidentiality or conflict. The patient's restriction still + refuses (EHDS Art. 8), and a GDPR Art. 18 restriction of processing refuses + every access, an emergency included. +- **The record.** The access record stores the purpose and the reason + (`audit_event.justification`), the access-log entry names the + justification with its `reason` (`justification`, or `emergency`), and the + patient's own ITI-81 retrieval shows who looked, why and that it rested on + a justification ([Audit](ehds-logging.md#justified-and-emergency-access)). + +```mermaid +sequenceDiagram + participant C as Clinician (EHR app) + participant F as FerroEHR + participant E as Access evaluator + participant L as Access record + participant P as Patient portal + C->>F: GET composition, x-purpose-of-use TREAT + F->>E: decide (no care relationship) + E-->>F: refused-reason-missing + F-->>C: 403 refused-reason-missing + C->>F: GET composition, x-purpose-of-use TREAT, x-access-reason + F->>E: decide (justification 1 invoked, reason stated) + E-->>F: admitted on the justification + F->>L: purpose TREAT, justification and reason + F-->>C: 200 composition + P->>F: GET AuditEvent?patient=... + F-->>P: purposeOfEvent TREAT, text = the reason +``` + +A policy that admits consultations under `TREAT` and emergencies under +`ETREAT` to every professional, and break the glass only to the emergency +physicians: + +```json +"justifications": [ + { "_type": "ACCESS_JUSTIFICATION", "emergency": false, + "purposes": [{ "_type": "DV_CODED_TEXT", "value": "treatment", + "defining_code": { "terminology_id": { "value": "HL7_ActReason" }, "code_string": "TREAT" } }] }, + { "_type": "ACCESS_JUSTIFICATION", "emergency": true, + "purposes": [{ "_type": "DV_CODED_TEXT", "value": "break the glass", + "defining_code": { "terminology_id": { "value": "HL7_ActReason" }, "code_string": "BTG" } }], + "applies_to": [{ "_type": "ACCESS_ACTOR_SCOPE", + "role": { "_type": "DV_CODED_TEXT", "value": "emergency physician", + "defining_code": { "terminology_id": { "value": "urn:example:roles" }, "code_string": "EP" } } }] } +] +``` + +Each purpose must also be on `[audit] purpose_codes` when that list is set, +since a purpose the audit layer does not record is no declared purpose. + +## Restriction of access by health professionals (EHDS Art. 8) + +Regulation (EU) 2025/327 Art. 8 gives a person the right to restrict the +access of health professionals and healthcare providers to all or parts of +their data, and has the fact of the restriction stay invisible to healthcare +providers. Art. 11(5) lets the restricted data be reached where necessary to +protect the person's vital interests, logged so the person can see it. No +openEHR specification governs this; it is our own design. + +- **Recording it.** A restriction is a `restriction` deny directive of the + EHR's own `EHR_ACCESS` settings (the `access_directives` scheme above). The + controller records it on the person's instruction by committing a new + `EHR_ACCESS` version with `POST /ferroehr/rest/extensions/v1/admin/ehr-access`, + for the whole EHR (no `data`) or for the versioned objects its + `data[].objects` name, and lifts it by committing a version without it + ([the routes](operations-admin-apis.md#legal-marks-restriction-objection-and-retention)). + `GET /ferroehr/rest/extensions/v1/admin/ehr-access` reads every version, so a + lifted restriction stays in the history, and an EHR Extract carries the + versions. A whole-EHR restriction covers data recorded after it too. +- **What the server reads of it.** The access evaluator reads every + attribute of the directive for each caller ([Access directives](#access-directives)): + its `data` scope, `applies_to`, `operations`, `purposes`, `time_validity` + and `exceptions`. The event stream, which has no caller, withholds every + object a restriction in force covers, and the whole EHR for a `data` scope + beyond `objects`. +- **What a professional sees.** Restricted data reads as absent: a restricted + composition or EHR answers **404** exactly as an unknown one does, a query + leaves it out at every scope (and a query scoped to a restricted EHR answers + as for an unknown EHR), an export skips it, a CONTRIBUTION lists none of its + versions, the event stream withholds it, and a write to it is refused as a + write to an unknown target. No status, header or count says that a + restriction exists. +- **What it does not change.** Nothing is deleted, and storage and the + controller's own processing go on: the admin routes (dump, archive, erase, + the registers) see everything. It is not the GDPR Art. 18 restriction of + processing, which answers **403** and stops processing itself. +- **The emergency override.** A caller an emergency + [justification](#justified-access-outside-the-care-relationships) of the + access policy names, declaring its purpose and stating a reason, reads the + restricted data where the directive's `emergency_override` holds, and its + access record names the emergency with the reason + ([Audit](ehds-logging.md#justified-and-emergency-access)). Without the reason, or + without a justification that names the caller, nothing is lifted. + +The grain is the versioned object, the whole EHR, or both. A finer grain (one +entry inside a composition) is not built: an object is the unit the version +reads, the queries and the exports already decide on, and splitting a +composition would change what the stored, signed version holds. + +## Opt-out from the access services (EHDS Art. 10) + +Regulation (EU) 2025/327 Art. 10(1) lets a Member State's law give a person +"the right to opt out from the access to their personal electronic health data +registered in an EHR system through the electronic health data access services +referred to in Articles 4 and 12", and has the Member State "ensure that the +exercise of that right is reversible". Art. 10(2) lets the Member State admit +"a healthcare provider or health professional" where processing "is necessary +in order to protect the vital interests of the data subject or of another +natural person", even after an opt-out. No openEHR specification governs this; +it is our own design. + +FerroEHR ships the software part: a mark on the whole EHR that the callers you +grant as the access services read as absent. Whether the right exists, how +the person exercises it, and the rules and safeguards of Art. 10(2) are your +Member State's law and yours to apply. Where the Member State enforces the +opt-out in its own services, leave the mark unused. + +- **Granting the access services.** Your Art. 4 access service (the + person's) and your Art. 12 health professional access service each hold an + `access_service` grant in the CDR: a capability of a `ROLE` their `ACTOR` + or `PERSON` performs ([Operational policy](operational-policy.md#what-the-grants-decide)). + `[authz.grants] allowed` does not allow `access_service` by default, so the + opt-out holds for nobody, and recording one is refused with **400**. A role + a token names grants nothing here. +- **Recording and reversing it.** An opt-out is an `opt_out` deny directive + of the EHR's own `EHR_ACCESS` settings, at most one, covering the whole EHR. + The controller records it on the person's instruction by committing a new + `EHR_ACCESS` version with `POST /ferroehr/rest/extensions/v1/admin/ehr-access`, + and reverses it by committing a version without it + ([the routes](operations-admin-apis.md#legal-marks-restriction-objection-and-retention)). + The reversed opt-out stays readable as a past version, and a version + without one is accepted whatever the configuration, so an opt-out can + always be reversed. Its `emergency_override` false makes it absolute: no + vital-interest override lifts it (EHDS recital 55). +- **What an access service sees.** A request from a caller holding an + `access_service` grant reads the EHR as absent: a route that names the EHR or an + object in it answers **404** as for an unknown EHR, a population query leaves + its data out, a query scoped to it answers as for an unknown EHR, an export + and the lookup by subject find no such EHR, and a write to it is refused as a + write to an unknown EHR. +- **What it does not change.** Every other caller reads the record as before: + your own care, through callers that hold no `access_service` grant, and the + controller's admin routes. Nothing is deleted. It is not the Art. 8 + restriction above, which reaches every professional route and leaves the + person's own access open. +- **The vital-interest override.** An access-service caller an emergency + [justification](#justified-access-outside-the-care-relationships) names + (an `applies_to` of caller kind `access_service`), declaring its purpose + and stating a reason, reads the EHR where the opt-out's + `emergency_override` holds, unless it acts for the + person (a SMART `patient/` grant or the patient claim), because Art. 10(2) + names a healthcare provider or health professional. Its access record + names the emergency with the reason + ([Audit](ehds-logging.md#justified-and-emergency-access)), and a + route that names the opted-out EHR, in its path or in a `POST + /message/export` manifest, adds an access record + `access-opt-out-override:ehr-wide` against it. +- **The record.** Each commit and each read through the controller's route + is an access record on the EHR (`ehr-access:ehr-wide`) naming the + administrator. + +```toml +[authz.grants] +allowed = ["commit_composition", "access_service"] + +[audit] +purpose_codes = ["TREAT", "ETREAT"] +``` + +## Information a person inserts (EHDS Art. 5) + +Regulation (EU) 2025/327 Art. 5 lets a person, or their representative, insert +information in their own EHR through the access services. That information +"shall be clearly distinguishable as having been inserted by the natural +person or by his or her representative", and the person "shall not be able to +directly alter the electronic health data and related information inserted by +health professionals". FerroEHR keeps both rules at the commit. No openEHR +specification governs who may change what, so the rules are our own design; +the marker is the RM's own. + +- **Who counts as the person.** A caller the party binding binds to the + `PERSON` an EHR's subject names, with no professional `ROLE`. A patient + claim or a `patient/` scope in the token does not make a caller the person, + because a professional's token in a patient's context carries both (SMART + on openEHR master08 §Resource Scopes). +- **Who counts as the representative.** A person bound to their own `PERSON` + who acts for the patient through a representation relationship FerroEHR has + recorded ([how a login is looked up](installation/config-authz.md#how-a-login-is-looked-up)), + ([Representatives](caller-facts.md#representatives)). + The rules below hold for the representative exactly as for the person. +- **The marker.** Every version and CONTRIBUTION the person commits records + `PARTY_SELF` with no `external_ref` as `AUDIT_DETAILS.committer`, the RM's + way to say the committer is the record subject (RM common, Audit Details). + A representative's records `PARTY_RELATED`, naming the representative's own + `PERSON` and the coded relationship. FerroEHR writes this committer itself + and refuses one the request states that differs, in the + `openehr-audit-details` header or in a CONTRIBUTION body. Every read of the version carries it, an AQL query reads it with + `v/commit_audit/committer`, the contribution list extension flags the change + set with `inserted_by_person`, and the viewer names the committer "The person + or their representative". The marker is part of the stored version, so a + dump and its restore keep it. +- **The composer.** A COMPOSITION the person or the representative commits + names the person (`PARTY_SELF`) or their representative (`PARTY_RELATED`) + as its composer. + Any other composer is refused with **403**, so the person cannot present what + they insert as a professional's. +- **What the person may change.** The person and their representative may + update and delete a version whose committer is `PARTY_SELF` or + `PARTY_RELATED`. An update or a deletion of a version anyone else committed, + a professional or a system, is refused with **403** and a body that names + EHDS Art. 5, whether it comes as a direct write or inside a CONTRIBUTION. + Nothing is written. The marker is in the version, so the rule holds whatever + became of the access record of the write. +- **What a professional may change.** A professional's writes are unchanged. + A professional may update or delete an entry the person inserted; the new + version is the professional's, which the person may then no longer alter. + The person's own versions stay in the version history. + +## Delayed access by the person (EHDS Art. 3(3)) + +Regulation (EU) 2025/327 Art. 3(1) gives a person access to their data +"immediately after the personal electronic health data have been registered in +an EHR system". Art. 3(3) lets a Member State restrict that right "by delaying +access to their personal electronic health data for a limited period of time +until a health professional is able to properly communicate and explain to the +natural persons concerned information that can have a significant impact on +their health". Recital 10 gives the example: a diagnosis of an incurable +disease should come first in a consultation, not through an electronic +channel. This is the opposite direction of the Art. 8 restriction above: the +data is withheld from the person, never from a professional. No openEHR +specification governs it; it is our own design. + +FerroEHR ships the software part. Whether the delay applies, to which data and +for how long is the Member State's rule, and you configure it in +[the access-delay register](installation/config-auth.md#the-access-delay-register), an +[admin register](access-policy.md#the-admin-registers). It is off by +default, so the person's access stays immediate. + +- **What is held.** With the register on, every new COMPOSITION whose category + (the [audit category register](installation/config-audit.md#the-audit-category-register), template first, + then the root archetype) is listed in the register's `categories` is held from + the moment it is committed, for the register's `max_delay`. Only the first version + is held: a composition the person has already seen stays visible when it is + amended, and a professional holds an amendment by hand if it needs + explaining. A composition the person commits is never held from them. +- **Who it is held from.** A request that may be the person's own: a bearer + token the party binding binds as the person or a representative. Such a + token is treated as the + person's, whatever `user/` or `system/` grant it also carries, so a mixed + token is withheld from rather than shown the data too early. The rule is the + FerroHEALTH family's, shared with the other products through + `ferrohealth-smart`. To that request a held composition reads + as absent: a read answers **404** as for an unknown composition, a query and + an export leave it out, a CONTRIBUTION lists none of its versions, and a write + to it is refused as a write to an unknown target. +- **On a professional's own record.** The person an EHR belongs to is read + from the party binding: a caller whose identity is bound to the `PERSON` + the EHR's `EHR_STATUS.subject` names is that record's person, whatever + roles it holds. On that EHR the hold applies to them as above, in a read, + a query pinned to the EHR, a query across the population and an export, + and their own write to it is never held. A bound person holding no role + reaches only their own records, so the hold applies on every one. +- **What a professional sees.** Everything else, as before. The hold changes + no professional route, query or export on another person's record. +- **Releasing it.** The treating professional releases a composition once it + has been explained, from the clinical surface with + `POST /ferroehr/rest/extensions/v1/ehr/{ehr_id}/versioned_composition/{versioned_object_uid}/access-delay/release`. + The route takes the checks of a write to that EHR: its `EHR_ACCESS` gate and + the SMART `composition-` update grant. A request that may be the person's is refused with **403**. The + controller releases with + `POST /ferroehr/rest/extensions/v1/admin/access-delay/release`, and holds + one by hand with `POST /ferroehr/rest/extensions/v1/admin/access-delay`, for + at most the access-delay register's `max_delay` + ([the routes](operations-admin-apis.md#legal-marks-restriction-objection-and-retention)). +- **The limit.** Every hold ends by itself when its period passes, released or + not, because Art. 3(3) allows a delay "for a limited period of time" only. +- **The record.** Placing a hold, releasing it and its expiry are each an + access record: the release names the professional who made it, and the + server writes the expiry record within a minute of the limit passing. +- **The person's access trail (Art. 9).** A record about a held composition + would tell the person a result exists. The subject-scoped ITI-81 read, the + one an app serves the person's own trail from, leaves out every + record that names a held composition, its hold included, until the hold is + released or expires; the records then appear unchanged, with their original + times. The filter is `ehds-logging`'s, the FerroHEALTH family's EHDS + logging component. The controller's unscoped read shows every record at + all times. + +Turning the section off makes every held composition readable to the person at +once: the holds stay in the register, and no new one can be placed. + +## RBAC (role-based, coarse) + +Every openEHR operation is classified as **Public**, **Clinical**, or +**Admin**, and a role model gates each class. Roles are plain, +case-insensitive strings. A Clinical operation needs an authenticated caller +and no role; the configured roles default to `ADMIN` (`admin_role`, every +Admin operation) and `READONLY` (`readonly_role`, refused on every write). + +| Environment variable | Default | Meaning | +|---|---|---| +| `FERROEHR__AUTHZ__RBAC__ENABLED` | `true` | the coarse role gate (active only when auth is enabled) | +| `FERROEHR__AUTHZ__RBAC__ADMIN_ROLE` | `ADMIN` | role required for admin operations | +| `FERROEHR__AUTHZ__RBAC__READONLY_ROLE` | `READONLY` | role marking a principal read-only: refused on every write | +| `FERROEHR__AUTH__ISSUER____ROLE_CLAIMS` | `["roles","groups","entitlements"]` | JWT claim paths mined for roles, per issuer; a Keycloak issuer adds `realm_access.roles` | +| `FERROEHR__AUTHZ__RBAC__ROLE_ISSUERS` | empty | the names of the issuers whose role claims may grant the administrator role; a token of any other issuer never holds it | + +Roles come from the JWT claims listed in `ROLE_CLAIMS`, or from a Basic user's +configured roles. The defaults are the carriers +[RFC 9068 §2.2.3.1](https://www.rfc-editor.org/rfc/rfc9068#section-2.2.3.1) names +for conveying authorization state (`roles`, `groups`, `entitlements`, of which +`roles` and `entitlements` are [SCIM](https://www.rfc-editor.org/rfc/rfc7643#section-4.1.2) +attributes), the default every FerroHEALTH product shares. A claim path may be +dotted, so an issuer that nests them differently, such as Keycloak's +`realm_access.roles`, is configuration rather than a code change; a claim +carrying a single string and one carrying an array are both accepted. + +**A Clinical operation needs at least one role of any name; an Admin operation +needs the admin role.** A Basic user holds the roles its `roles` list names +and nothing else, so a user with none is refused every Clinical operation; +`roles = ["USER"]` satisfies the Clinical class and no Admin operation. A +bearer token whose SMART on openEHR resource scopes are all `system/` scopes, +such as `system/template-*.r`, is a backend client and needs no role for a +Clinical operation: its scopes decide what it reaches. The record's person and +their representative need no role either: a caller the party binding binds +to the `PERSON` they are, and a +caller acting for the person pass the Clinical class, and the access +evaluator decides from who they are (EHDS Art. 3 and 4(2)), confining them +to their own records. A token's own reading of the patient never counts +without that binding. The read-only role still refuses their writes. +Any other `user/` or `patient/` token belongs to a professional and still needs +a role. +Disabling RBAC restores authentication-only behaviour. + +> [!IMPORTANT] +> **The management surface is not configured here.** `/management/*` is governed +> entirely by `[management.endpoints]`, one level per endpoint, and nothing under +> `[authz.rbac]` changes it. There is **no global default beside it: an endpoint +> you do not name is `off`** and is not mounted at all. +> +> Each level means: `off`, not mounted, answers `404`; `private`, any +> authenticated principal; `admin_only`, authenticated **and** holding +> `authz.rbac.admin_role` (the one place RBAC is consulted); `public`, no check +> at all, including no authentication. +> +> The consequence worth internalising: `prometheus = "public"` is reachable by +> an anonymous caller **whatever** your RBAC settings say, because a `public` +> endpoint is mounted outside the authentication layer. Lock the surface down by +> raising the levels in `[management]`, and read the effective set back from +> `/management/env` (or from the boot log line that names every mounted +> endpoint and its level) rather than assuming. + +> [!IMPORTANT] +> **The OAuth2 `scope` claim does not grant roles.** A scope grants a *client* +> delegated authority ([RFC 6749 §3.3](https://www.rfc-editor.org/rfc/rfc6749#section-3.3)); +> it asserts nothing about the subject's roles. Reading it as one also made the +> at-least-one-role check pass for every OIDC token, since `openid` alone +> satisfied it. If your callers rely on a scope naming a role, move that role +> into one of the role claims above. Scopes remain on the principal and still +> drive SMART scope enforcement. + +> [!NOTE] +> The downloadable Compose quickstart deliberately runs with RBAC **off** and a +> single user, so every surface works out of the box (see +> [Docker Compose](installation/compose.md)). Turn the role gate on with +> `[authz.rbac] enabled = true` (or `FERROEHR__AUTHZ__RBAC__ENABLED=true`) and +> give each principal an explicit `roles` list. + +A principal carrying the `readonly_role` (default `READONLY`) is refused on +every write operation (creating an EHR, committing a composition, uploading a +template, and any update/delete) even when it also holds granting roles such +as `ADMIN` (a restriction always overrides a grant). Reads and AQL queries stay +permitted, so a `READONLY` account is an authenticated, view-only principal. The +repository's from-source development stack ships one such account +(`ferroehr-readonly`, password `ferroehr`) alongside `ferroehr` and +`ferroehr-admin`, with RBAC at its default `enabled = true`, so the separation +can be tried out; the downloadable quickstart file has neither (one user, no +role gate). + +## A patient's own EHR + +A caller is the patient, the `subject` caller kind of the +[access evaluator](#access-directives), through a SMART App Launch +patient-context credential: a bearer token whose `patient/` grants name the +launch EHR in `ehrId` (master07 §Context Selection). +The patient's own EHR is the `ehrId` of that token's launch context +(ITS-REST SMART App Launch §Context Selection). The evaluator skips every step +of the decision procedure for the patient on their own EHR (EHDS Art. 3) and +refuses them every other EHR with **`403`** `refused-not-subject`, which the +access record names as step 0 (subject). No key +turns this on or off, and a representative comes in as a delegation of the +subject's directives. + +- An operation on another patient's EHR is refused with **`403`**, whether the + EHR is named in the path, the body or only in the result. That covers the + EHR, `EHR_STATUS`, COMPOSITION, CONTRIBUTION and DIRECTORY operations and + their item tags, and the EHR Extract import and export routes; an export by + manifest (`POST /message/export`) holds every EHR it names, and one EHR of + another patient refuses the whole export. +- An AQL query reads only the rows of the patient's own EHR, whatever the query + scopes or projects, including a query that reads only the `ehr` row, and its + counts and pages see only those rows. +- A patient-context token whose launch context names no EHR reaches none, and + an operation on EHR data that names no EHR (creating an EHR, a lookup by + subject, a query with no single-EHR scope, an import naming no EHR) is + refused the same way. + +The evaluator holds the launch context alone. The SMART layer checks a +`patient/` grant's resource family and permission and refuses on nothing +else, so every route answers a caller on another EHR the same way and the +access record names step 0. A professional whose grants are `patient/` grants +alone, a clinician app launched for one patient, is held to that patient's +EHR the same way, and on that EHR takes every step of the procedure. A contact +point's caller is held to the EHR of its treatment relationship +confirmation's patient. diff --git a/website/book/src/access-log.md b/website/book/src/access-log.md new file mode 100644 index 0000000000..5f9e6ca6ea --- /dev/null +++ b/website/book/src/access-log.md @@ -0,0 +1,349 @@ +# The access log + +The openEHR access-log entry FerroEHR writes for every access, and how a subject or an +administrator reads it over ITS-REST. The sinks and the integrity checks are on +[Audit trail](audit.md). + + + +## The openEHR access-log entry + +Every access to EHR data is recorded as an openEHR access-log entry: an +`ACCESS_LOG_ENTRY` of the draft `org.openehr.rm.access_log` 0.1.0 model, +FerroEHR's proposal to openEHR, which no openEHR release defines yet. Reads, +writes, AQL queries, exports, refusals and reads of the access log itself each +write one. An access that reaches several EHRs writes one entry per EHR, and +the entries of one request share its request id, so a population query writes +one entry for each EHR that contributed a row, a statement that projects +only the EHR (`SELECT e/ehr_id/value FROM EHR e`) included. + +The administrative routes that touch an EHR write entries the same way, one +per EHR they touched: the physical EHR delete, one EHR or in bulk; the +restriction, research-objection, access-delay and access-repair registers and +the `EHR_ACCESS` settings commit that carries a restriction or an opt-out; +archiving an EHR and restoring it; its retention anchor and the retention hold +on one of its objects; the repository dump and load; and the EHR Extract +export and import. An export's entry names the request it answered, the bound +party and the provider, as every other access entry does. The import of another system's access log (`ferroehr +access-log import`) writes its `import` entry through the same path. SCIM +provisioning touches party data only and writes none. + +The entry names who accessed (the bound party, the groups, the provider, the +binding outcome and the credential by its issuer, subject, client and token +id), what (the EHR, the version or object, its categories and origins), why +(the declared purposes), under which authorisation (the agreement, the +representation, a data permit, a justification with the clinician's reason, +and the grounds of the access decision below), the outcome (`granted`, `refused` or `failed`) and +the request. It carries no data value of the EHR: +a query is named by its stored name or the SHA-256 of its text, never the +text, and a read of the access log through ITI-81 is named by the digest of +its search. + +**The grounds of the access decision.** The access evaluator's decision on +the EHR is in the entry's `authorisations`, each an `ACCESS_AUTHORISATION` +whose `name` and `version` name the document the ground is defined in: + +| Kind | When | What it names | +|---|---|---| +| `role` | always | each grant the caller held, by its operation code (`name`) and the `ROLE` that carries it (`reference`); each role the caller held | +| `subject of care` | the person reads their own record | | +| `consent` | a consent permit admitted the access, or the caller is a gate-keeper of the settings | `EHR_ACCESS` and the uid of its version; the directive by its uid, its first identifier or its position from 1, and its legal grounds | +| `representation` | a `delegation` permit admitted a representative | as `consent` | +| `treatment relationship` | the decision read a live care relationship, also when only a controller rule's exception reads it | in `care` the relationship the access rested on, with its `role` and `path`. A stored relationship is an `ACCESS_STORED_CARE_GROUND` under `ACCESS_POLICY` and the uid of its version: its target (`carer`: the professional's `PERSON` or `ROLE`, or the care team or unit), the uid of its version (`relationship`), whether the grace after its end admitted the access (`in_grace`), the carer it covers for (`covers_for`, with the carer's kind as its `type`), its `provider` and the episode of care it is scoped to (`episode`, absent for a relationship that names none). One a verified credential attests is an `ACCESS_ATTESTED_CARE_GROUND` on the `attested` path under the agreement's name and version: the `assertion` (`id`, `issuer`) and the `agreement` (the container uid of its `ROLE`, with the partner's federation issuer); the ground's `reference` names the assertion too. Where several admitted it, `direct` comes before `team` before `self_declared` before `attested`, then the order of the roles in the rule that matched | +| `justification` | a [justification](access-control.md#justified-access-outside-the-care-relationships) of the access policy admitted the caller outside its care relationships | `ACCESS_POLICY` and the uid of its version, the justification by its position from 1 (`reference`, type `justification`), and the clinician's own words in `reason`; an entry naming the objects it delivered names it only when one of them rested on it | +| `emergency` | an emergency justification admitted the access, or lifted a directive, a controller rule or steps 6 to 8 | for the justification itself, as `justification` with its `reason`; for each directive or rule it lifted, the directive, or the `ACCESS_POLICY` version with the rule by its uid, its first identifier or its position from 1, and no `reason`; an entry naming the objects it delivered names only the directives and rules whose data scope covers one of them | + +The entry of each EHR an AQL query served names the same grounds a read of +that EHR alone names. The query's condition is built from this replica's copy +of every EHR's settings, which holds each EHR's subject and the uid of its +`EHR_ACCESS` version beside the settings, so the record adds no database read. +For an EHR with no settings, which the copy does not hold, a care relationship +is named when only a caller in care could have been served its rows, without +the relationship itself. In the FHIR `AuditEvent` the care relationship's +role is an `agent.role` coding of the requestor, its HL7 code system named by +its canonical URL (`HL7_ParticipationType` as +`http://terminology.hl7.org/CodeSystem/v3-ParticipationType`), and the +policy version that named it is among the requestor's `agent.policy`. In +the DICOM message the same role follows the held roles as a `RoleIDCode` in +that code system. Both forms carry it, and a projection written from the log +reads the ground back, so it carries the role as the live record does. + +`accessor.binding` says how FerroEHR bound the login to the party, or why +it could not, in the `credential binding` group of the `openehr_access` +terminology: `bound`, `provisional`, `subject of care`, `external`, +`organisation` and `system` for a login it bound, and the cause for one it +refused, such as `unbound`, `party inactive`, `no agreement` or `treatment +relationship confirmation missing`. The draft terminology page lists every +code. + +A refusal names its code in `outcome.reason`, in the `openehr_access` +terminology, and in `outcome.description` the step that refused and the +directive or policy of that step, such as `step 2 (restriction): directive 1 +of EHR_ACCESS 5a1c…::cdr.example.org::2`. This holds for the `404` of an +opt-out or a restriction too: the response says nothing (EHDS Art. 8), and +the entry says why. A justified access and an emergency name their +justification with the reason, so the person sees them in their access log +(EHDS Art. 9 and 11(5)). The EHDS record +writes the versions the grounds name after the data permit at +`agent[user].policy`, "the policy or plan that authorized the activity being +recorded" (FHIR R4 `AuditEvent.agent.policy`), read from the entry's grounds +when the record is rendered. Which grounds are named is FerroEHR's own design. + +**The entry is the record.** The store keeps an access to EHR data as its +entry alone, in `audit.access_log_record`, sealed in windows (see +[Tamper evidence](audit-integrity.md#tamper-evidence)), and each entry states the date it is +kept until and why. The FHIR `AuditEvent` the ITI-81 search and the ITI-20 +FHIR feed serve, the DICOM message the syslog sink sends and the EHDS access +record are projections of the stored entry: each is written from what the +log keeps and from nothing else, and none is stored as a second record. +`audit.audit_event` keeps the records of accesses outside the access log: an +authentication, a template or party operation, an application activity. + +The entry is written with every other record of its request in one database +transaction before the response leaves, and an access whose entry cannot be +written is refused with `503` ([how a record is written](audit.md#how-a-record-is-written)). + +### The access log details + +The draft's core attributes are openEHR's: the action, the outcome, the +accessor, the items, the query, the authorisations, the channel. The facts +the BALP `AuditEvent`, the DICOM message and the EHDS access record carry +that the core holds no attribute for are kept in the entry's +`other_details`, which the draft gives to the fields a jurisdiction adds: one +`ITEM_TREE` under the archetype `openEHR-EHR-ITEM_TREE.access_log_details.v1`, +one `ELEMENT` per fact, named by its node id. A fact the core states as the +access holds it, such as the principal the credential names or the count the +outcome delivered, is not repeated there: read the core first and the +details beside it. They are part of the entry, so its window's seal covers +them, and a tombstone removes them with the rest of its content. + +The archetype is published, so another system reads the details of an +exported log by it. FerroEHR ships it among its default definitions +(`openEHR-EHR-ITEM_TREE.access_log_details.v1.0.0.adls`, stored at the +first boot like the [operational policy](operational-policy.md) +definitions, with its digest in `deploy/definitions/published.sha256`), and +you read it with `GET /definition/template/adl2/openEHR-EHR-ITEM_TREE.access_log_details.v1.0.0`. +The node ids are two-digit id-codes, so their byte order is their numeric +order, which is the order the elements of a tree are kept in. No openEHR +specification governs the details: they are FerroEHR's own. + +| Node id | Name | Value | Holds | +|---|---|---|---| +| `id11` | event action | `DV_TEXT` | the DICOM `EventActionCode`: `C`, `R`, `U`, `D` or `E` | +| `id12` | resource class | `DV_TEXT` | the class of resource the access addressed | +| `id13` | outcome indicator | `DV_COUNT` | the DICOM `EventOutcomeIndicator`: `0`, `4` or `8` | +| `id14` | principal | `DV_TEXT` | the login the access was made under | +| `id15` | issuer | `DV_TEXT` | the issuer of the caller's token | +| `id16` | client id | `DV_TEXT` | the client the token was issued to | +| `id17` | token id | `DV_TEXT` | the token's `jti` | +| `id19` | role | `DV_TEXT` | a role the caller held, one element each | +| `id20` | domain | `DV_TEXT` | the pseudonymisation domain, when it is not the resource class's own | +| `id21` | ehr id | `DV_TEXT` | the EHR the request named | +| `id22` | subject | `DV_IDENTIFIER` | the subject of care of the EHR, as `EHR_STATUS.subject` names it, with its namespace as the issuer | +| `id23` | subject lookup failed | `DV_BOOLEAN` | set when the subject could not be looked up | +| `id24` | object id | `DV_TEXT` | the object the request named; none for a read of the log, whose search the entry names by digest | +| `id25` | purpose | `DV_TEXT` | the purpose of use the caller declared | +| `id26` | legal basis | `DV_TEXT` | the legal basis the deployment attributes | +| `id27` | result count | `DV_COUNT` | how many records the access served | +| `id28` | origin | `DV_TEXT` | an origin of the data, one element each | +| `id29` | origin count | `DV_COUNT` | how many distinct origins the data had | +| `id30` | category map digest | `DV_TEXT` | the category map the access was classified through | +| `id31` | category content | `DV_PARSABLE` (`application/json`) | what the classification read | +| `id32` | acting mode | `DV_TEXT` | how the credential acted | +| `id33` | assurance level | `DV_TEXT` | the assurance level of the authentication | +| `id34` | assurance value | `DV_TEXT` | the claim value the level was read from | +| `id35` | professional id | `DV_TEXT` | the identifier of the natural person who accessed | +| `id36` | token attributes | `DV_PARSABLE` (`application/json`) | the purposes and roles the token stated | +| `id37` | binding | `DV_PARSABLE` (`application/json`) | the party binding with every field | +| `id38` | summary | `DV_PARSABLE` (`application/json`) | the count and EHRs of a summary of refusals | +| `id39` | event type | `DV_TEXT` | the DICOM `EventTypeCode` of an authentication record: `110122` Login, `110123` Logout | +| `id40` | review | `DV_CODED_TEXT` (`HL7_Confidentiality`) | the level, `R` or `V`, of the record a care relationship was written to, when the write is recorded for review | + +The subject of care is kept so the BALP `entity:patient` and the +`patient` search parameter name the patient as they did when the access +was recorded, whatever happens to the EHR after. An entry imported from +another system ([Seals, checkpoints and the transfer of a log](audit-integrity.md#seals-checkpoints-and-the-transfer-of-a-log)) +keeps that system's details, and FerroEHR projects none of it. + +To read the trail with SQL, `audit.access_trail` holds every record of +either form with the facts it states, in the audit vocabulary +(`operation`, `principal`, `binding`, `party` and the rest), an entry's read +from its content. `audit.access_detail(content::jsonb, 'id32')` reads one +access detail of an entry. The categories a classification computes are no +column there: the projection writes them. + +### The projections and their losses + +Each projection reads one stored entry and writes one target record. +"Loss" means the target has no place for the value; the entry keeps it. The +FHIR R4 `AuditEvent` follows IHE BALP 1.1.4; an access the category map did +not classify is a BALP exchange without the EHDS entities. Each row is a test +(`access_log::projection` in the source). + +**To the FHIR R4 `AuditEvent` (IHE BALP 1.1.4).** + +| Entry | `AuditEvent` | Loss | +|---|---|---| +| `action` | `action` (`C`, `R`, `U`, `D`, `E`), `type` `rest` and the FHIR interaction as the first `subtype`; an export or import is `type` Export or Import | the openEHR action has no code system of its own: `export` and `import` fold into `R` and `C` | +| `operation` | a `subtype` in `urn:openehr:its-rest:operation` | none | +| `time_recorded` | `recorded` | `occurred`: no `period` is written | +| `outcome.result` | `outcome`: `0` granted, `4` refused or a minor failure, `8` a serious failure | refused and a minor failure share `4`; `outcomeDesc` states the outcome in words and no reason code | +| `outcome.delivered` | the `delivered` detail of the `ehds-categories` entity | none, as a detail | +| `accessor.party` | the `ihe-otherId` typed `PRN` of `agent:user` (BALP 1.1.4 §3:5.7.5.4) | none | +| `accessor.credential` | `agent:user` `who.identifier` (issuer as `system`, subject as `value`), the token id as its first `policy`, the client as an agent of its own, the assurance as `ihe-assuranceLevel` | the authentication method has no element | +| `accessor.provider` | an agent naming the provider of the caller's party binding | none | +| `accessor.roles`, `accessor.kind` | `agent:user` `role`, the acting mode first | none | +| `accessor.groups`, `accessor.binding`, `accessor.delegation` | details of the `ehds-accessor` entity, one `actor` per actor in the chain's order | no element; details | +| `ehr_id` | the `ehr` entity, with the subject of care as the patient entity (`entity:patient`, role `1`) | none | +| `items` | `entity:data` (type `2`, role `4`) naming the version in `urn:openehr:object-id`; the categories and the template and archetype ids as details of `ehds-categories` | the RM type and the paths have no element | +| `items.origins` | one `origin` entity each | no element; entities | +| `query` | `entity:query` (role `24`), a stored query by its name | the text digest is not written | +| `purposes` | `purposeOfEvent` and `agent:user` `purposeOfUse` | none | +| `authorisations` | a permit as a `policy` of `agent:user` after the token id; an agreement in the `ehds-relayed` entity; a representation in `ehds-accessor` | legal grounds have no element; details | +| the `emergency` authorisation with a `reason` | the `ehds-emergency-access` entity naming the declared purpose that invoked it | the mark becomes an entity | +| an authorisation's `reason` | the `text` of `purposeOfEvent` and of `agent:user` `purposeOfUse` | none | +| `channel.request_id`, `channel.client_address` | the `X-Request-Id` entity; the client agent's `network.address` | none | +| `system_id` | `source.observer.identifier`; `source.site` from `[audit] enterprise_site_id` | none | +| `security_labels` | the `securityLabel` of the entity they label | no `meta.security` is written | +| `retention` | details of `ehds-categories` | no element; details | +| checkpoints | nothing | the seals do not travel; verify them on the openEHR side | +| `other_details` | the values it holds, where the rows above put them | the tree itself is not written | + +**To the DICOM PS3.15 A.5 audit message (the syslog sink).** + +| Entry | DICOM element | Loss | +|---|---|---| +| `action` | `EventActionCode`; `EventID` Patient Record (110110), Query (110112), Export (110106), Import (110107) | as in R4 | +| `operation` | `EventTypeCode` in `openEHR-ITS-REST` | none | +| `time_recorded` | `EventDateTime` | `occurred` | +| `outcome` | `EventOutcomeIndicator`, `EventOutcomeDescription` | the reason's code | +| `accessor.credential` | the requestor's `UserID` (the subject, or the professional a client acts for) | the issuer, the token id, the assurance | +| `accessor.roles` | `RoleIDCode` in the `codeSystemName` of `[audit] role_code_system`, by default the deployment's `[api] system_id`; the role of the care relationship the access rested on in its HL7 code system | none | +| `accessor.party`, `binding`, `groups`, `delegation` | details of the `ehds-accessor` participant object | no element; details | +| `accessor.provider` | nothing | lost | +| `system_id` | `AuditSourceID`, with `AuditEnterpriseSiteID` from the deployment | none | +| `channel.client_address` | `NetworkAccessPointID`, type `2` | none | +| `ehr_id` | the patient participant (type `1`, role `1`) names the subject of care | the `ehr_id` itself is not written | +| `items` | a System Object (type `2`, ID type URI) naming the version | the categories, origins, template and archetype | +| `query` | the query object of the Query event | the text digest | +| `purposes`, `authorisations` | nothing in the A.5.1 schema | lost | +| `retention`, `security_labels`, `other_details` | nothing | lost | + +**To the EHDS access record (`ehds-logging` `AccessRecord`).** + +| `AccessRecord` | Entry | Loss | +|---|---|---| +| `action` | `action` | export and import fold into `Read` and `Create` | +| `recorded` | `time_recorded` | none | +| `outcome`, `outcome_description` | `outcome.result` and the outcome indicator | a refusal shares `MinorFailure` with a minor failure | +| `accessor` (issuer, subject, client, token id, acting, roles, assurance, provider, party, groups, binding, actors, represents, relayed, purposes, policies) | `accessor`, `purposes`, `authorisations` and the access details | none | +| `subject.ehrs` | `ehr_id`, with the subject of care found | one record per entry; the entries of a request share its request id | +| `categories` | `items.categories`, computed again through the category map that classified the access | none | +| `delivered`, `origins`, `origin_count` | `outcome.delivered`, `items.origins`, the origin count | none | +| `request` (id, operation, resource, stored query, client address, correlation) | `channel`, `operation`, `items`, `query` | the query text is never carried | +| `retention`, `labels`, `emergency` | `retention`, the categories and origins, the `emergency` authorisation with a `reason` | none | + +## Reading the access log over ITS-REST + +The openEHR access-log entries are served under the extensions root, +`/ferroehr/rest/extensions/v1`. No openEHR ITS-REST release defines these +resources: they are part of FerroEHR's access-log proposal to openEHR, and they +follow the ITS-REST 1.1.0 conventions, `offset` and `fetch` paging as the Query +API's and ISO 8601 date-times. + +| Method and path | Who | What | +|---|---|---| +| `GET /ehr/{ehr_id}/access_log` | the subject of care, their representative, a reviewer | The entries of one EHR, newest first. Filters: `from`, `to`, `action`, `outcome`, `accessor_kind` (each a term by its coded content, the token `terminology_id\|code`, such as `HL7_AuditEventAction\|R`, `openehr_access\|refused` or `HL7_SecurityRoleType\|datasubject`; a rubric or a bare code is a `400`), `emergency`, `include_self`; `offset`, `fetch` (1 to 1000, default 100). | +| `GET /ehr/{ehr_id}/access_log/{uid}` | as above | One entry. | +| `GET /admin/access-log` | a reviewer | Records across EHRs, entries and tombstones. Filters: `ehr_id`, `party_namespace`, `party_type`, `party_id`, `issuer`, `subject`, `request_id`, `from`, `to`, `outcome`, `emergency`; `offset`, `fetch`. | +| `GET /admin/access-log/seals` | a reviewer | The seal of each window that covers an entry id from `from_id` to `to_id` (less than 10000 apart), with whether the window was folded, for verification. | +| `GET /admin/access-log/checkpoint` | a reviewer | The newest stored checkpoint, or the one at `sequence`. | + +A list answers `offset`, `fetch` and `entries`, and no total count, since a +count over a large log costs a scan. A parameter a resource does not take, or a +value outside its form, is a `400`. + +**The caller's authorisation selects the view, and no parameter widens it.** + +- The **subject view** goes to the person the EHR is about and to their + representative, bound through the party binding: the person reads the EHRs + whose subject is their `PERSON`, and a representative reads the EHR of the + subject the representation names + ([Operational policy](operational-policy.md)). It shows who accessed (the + provider and the party), when, the action and outcome, the items and their + categories, the purposes and the emergency mark, and leaves out the + credential, the delegation chain, the binding outcome, the channel, the + query text and its digest, the security labels and `other_details`, and the + accessor members a + [restriction](#restricting-the-subject-view-ehds-art-93) withholds. An entry about a composition held from the person under EHDS Art. + 3(3) is left out until the hold ends, as in the [subject-scoped ITI-81 + read](audit.md#while-a-composition-is-held-from-the-person). Any other EHR answers + `404`, the same as an unknown one, so its existence is not disclosed. +- The **full view**, each record in its ITS-JSON form, goes to + a reviewer: a caller the admin class admits (`admin_role` under RBAC), the + same caller `GET /admin/access-log` admits. +- Every other caller is refused with `403`. The log has its own access + control: a clinical grant such as `patient/composition-*.r` or + `user/composition-*.r` reaches none of it. + +The person's own reads of their log are recorded like every other read and +are left out of their default view; `include_self=true` adds them. Every read +of these resources, refused and failed ones included, writes an access-log +entry whose item names the log it read (`ACCESS_LOG_RECORD` for an entry, +`ACCESS_LOG` for an EHR's whole log), with the filter named by its digest. A +tombstone keeps no EHR, so a removed entry is read through the review. + +### Restricting the subject view (EHDS Art. 9(3)) + +EHDS Art. 9(3) lets a Member State restrict the person's right to see who +accessed their data "in exceptional circumstances". If your law does, declare +the restriction in the controller's +[access policy](operational-policy.md), never in `ferroehr.toml`: each entry +of `log_restrictions` names the accessor kinds it applies to (the `accessor +kind` terms of the log, such as `person` or `external person` of +`openehr_access`, or `datasubject` of `HL7_SecurityRoleType` for the +subject of care), the +accessor members the subject view withholds (`accessor_party`, +`accessor_provider`, `accessor_roles`, `accessor_groups`, in +`openehr_access`), and the provisions that lay it down, coded in your +jurisdiction's terminology. FerroEHR ships no country's restriction. + +```json +"log_restrictions": [{ + "_type": "ACCESS_LOG_RESTRICTION", + "name": { "_type": "DV_TEXT", "value": "External accessor withheld" }, + "archetype_node_id": "id11", + "accessor_kinds": [{ "_type": "DV_CODED_TEXT", "value": "external person", + "defining_code": { "_type": "CODE_PHRASE", + "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, + "code_string": "external person" } }], + "withheld": [{ "_type": "DV_CODED_TEXT", "value": "accessor_party", + "defining_code": { "_type": "CODE_PHRASE", + "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, + "code_string": "accessor_party" } }], + "legal_grounds": [{ "_type": "DV_CODED_TEXT", "value": "your national provision", + "defining_code": { "_type": "CODE_PHRASE", + "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "urn:example:national-law" }, + "code_string": "art-x" } }] +}] +``` + +- The subject and their representative get the subject view of an entry + whose accessor is of a named kind without the withheld members. A reviewer + reads the full entry, and the stored entry never changes. +- A policy write applies on the next request on every replica, with no + restart. +- A write that changes the restrictions changes what the log means, so it + writes an access-log entry of its own (operation + `admin_access_policy_write`), and the policy history keeps every version. + When the entry cannot be written, the write is answered `503`. + +```bash +# Who accessed my record this month? (the person's own token) +curl -H "Authorization: Bearer $PATIENT_TOKEN" \ + "https://cdr.example.org/ferroehr/rest/extensions/v1/ehr/$EHR_ID/access_log?from=2026-11-01T00:00:00Z" +``` + +The same entries are queryable with AQL as the top-level class +`ACCESS_LOG_ENTRY`, under the same rules of who reads which view, and each such +query writes its own entry ([Querying the access log](querying-aql.md#querying-the-access-log)). diff --git a/website/book/src/access-policy.md b/website/book/src/access-policy.md new file mode 100644 index 0000000000..921a997444 --- /dev/null +++ b/website/book/src/access-policy.md @@ -0,0 +1,483 @@ +# The access policy and the admin registers + +The controller's `ACCESS_POLICY` and the two admin registers hold the policy that has no +home in the demographic model. How they take part in a decision is on +[How FerroEHR decides access](explanation/access-model.md). + + + +## The admin registers + +Two kinds of operational policy have no home in the openEHR demographic +model, so each is an admin register: + +| Register | What it holds | Default, before anyone writes it | +|---|---|---| +| `audit-categories` | The EHDS category map every access is classified through ([the audit category register](installation/config-audit.md#the-audit-category-register)) | The category map FerroEHR ships | +| `access-delay` | The EHDS Art. 3(3) delay of the person's own access ([the access-delay register](installation/config-auth.md#the-access-delay-register)) | Off | + +You read and write them under `{ext}/admin/registers/{register}` with a token +or Basic user holding `admin_role`, with `[api] admin = true`; the routes are +on [Admin & messaging APIs](operations-admin-apis.md#operational-policy-registers). + +- **Versioned.** Every write appends a version that names its committer and + when it was committed, and never overwrites one; the history route lists + them all. Version 0 is the default no one committed. +- **Whole, over a version.** A write replaces the whole document and names the + version it replaces in `If-Match`. A write over a version that is no longer + the newest is refused with `412`, so two operators never overwrite each + other's change unseen. +- **Checked when written.** A document that does not hold is refused whole with + `400` and never reaches a request: a category map that does not compile or + a delay with an unusable limit. + The register keeps its version in force. +- **Effective without a restart.** Each replica keeps the registers in + memory and is told of every write through PostgreSQL `LISTEN`/`NOTIFY` when + the write commits; its next request after that reads the new version. The + replica that took the write applies it to its own next request. While a + replica's listener is not connected, that replica reads the registers on + every request, so it never serves an outdated policy. A database that cannot + answer that read fails the request with `503`; it is never served under a + guess. +- **Audited.** Every read and write of a register is an access record. + +A deployment provides its registers once the server runs, through the admin +API; neither has a key in `ferroehr.toml`. + +### A worked example: turning the access delay on + +Read the register, then write the new document over the version it answered: + +```sh +curl -s -u admin:… https://cdr.example/ferroehr/rest/extensions/v1/admin/registers/access-delay +# ETag: "0" +# {"register":"access-delay","version":0,"committer":null,"committed_at":null, +# "document":{"enabled":false,"categories":[],"max_delay":null}} + +curl -s -u admin:… -X PUT \ + -H 'Content-Type: application/json' -H 'If-Match: "0"' \ + -d '{"enabled": true, "categories": ["Laboratory-Reports"], "max_delay": "72h"}' \ + https://cdr.example/ferroehr/rest/extensions/v1/admin/registers/access-delay +# ETag: "1" +``` + +The next laboratory report committed on any replica is held from the person +for up to 72 hours. + +### The security floor that stays in `ferroehr.toml` + +A floor that must hold before a register can be read stays configuration. With +`deployment.profile = "production"` and auditing on, the audit category +register refuses a map that classifies nothing (no template, no archetype and +`shipped_map = false`) as the `no_category_map` gap, unless +`deployment.accepts` names it. + +## The access policy + +The controller's access policy states what holds for every EHR this FerroEHR +keeps: which kinds of data carry which sensitivity (`classifications`), +whether a professional's clinical access needs a care relationship +(`care_relationship_required`, with a `relationship_grace`) and a declared +purpose (`purpose_required`), the controller's own `rules` on which callers +may do what with which kinds of data (each an `ACCESS_DIRECTIVE` of kind +`controller_rule`, EHDS Art. 11(3)), the `catalogue` of named directives a +patient can accept by reference, such as an IHE BPPC policy, and the +`log_restrictions` of the access log's subject view your Member State's law +lays down under EHDS Art. 9(3) ([Audit](access-log.md#restricting-the-subject-view-ehds-art-93)). +It is an `ACCESS_POLICY` of FerroEHR's draft access control package, written +against the default archetype `openEHR-EHR-ACCESS_POLICY.controller.v1`, +which every boot stores, or against one of your own. The default floor +(`[authz.rbac] ehr_access_default`) stays in `ferroehr.toml`, and the policy +can only tighten it. Emergency access is one of the policy's +`justifications`. Until you write +one, nothing is tightened. + +- **Versioned.** Every write is a new version in its own contribution, with + you as committer; the history route lists them all. +- **Whole, over a version.** Name the version you replace in `If-Match`, or + create the first with `If-None-Match: *`. A stale condition is `412`. +- **Checked when written.** A body that is no canonical-JSON `ACCESS_POLICY` + is refused whole with `400`. A policy that reads but breaks a rule is + refused whole with `422`, naming the rule or the attribute: an invariant + of the draft model, a rule of another kind than `controller_rule`, a + catalogue entry of that kind, a rule naming a role, purpose, sensitivity, + category or legal ground in `openehr_access`, the template its + `archetype_details.template_id` names, or a code outside a value set it + binds. +- **Effective without a restart**, as the registers above. +- **Read by the access evaluator** on every request: `purpose_required` is + step 4, checked before any rule, the rules are step 5, a classification + gives the data it covers its sensitivities (step 6), and + `care_relationship_required` is step 7 of the + [decision procedure](access-control.md#access-directives). + A `relationship_grace` that is no ISO 8601 duration admits nothing after a + care relationship ends. + +The routes are on +[Admin & messaging APIs](operations-admin-apis.md#the-access-policy). A write +needs `admin_role` and a policy grant of `write_access_policy`. + +### Care relationship facts + +The policy also states how care relationships are read. Each attribute you +leave out reads as its strictest default, so a policy that sets none admits +least. + +| Attribute | What it says | Left out | +| --- | --- | --- | +| `self_declared_care` | The longest period of a care relationship a professional states for themself | no self-declared relationship | +| `attested_care` | The agreements under which a caller's verified credential may attest a care relationship | no attested relationship | +| `caseload` | Whether a query may be narrowed to the caller's [caseload](care-relationships.md#the-caseload) | `true` | +| `episode_shared` | The data every live care relationship covers whatever episode it or the data name, such as the patient summary, each an `ACCESS_DATA_SCOPE` ([Care relationships and episodes of care](care-relationships.md#episodes-of-care)) | none | +| `conflict_rules` | The conflicts of interest (`self`, `related`, with the kinships) allowed through the professional path, and for whom | none: a professional who is the patient, or is related to them, is refused | +| `concealed_confidentialities` | The `HL7_Confidentiality` levels whose refused records answer as absent | every refused record answers as forbidden | +| `value_sets` | The value set on your terminology server that each coded attribute (`care_role`, `representation_basis`, `kinship`, `organisation_type`, `care_purpose`, `emergency_purpose`) is bound to | the package's default code system | +| `relationship_validity` | The default and maximum period of a care relationship, by its `care_role` and the type of its provider | every care relationship is written with an end | +| `relationship_writers` | The writers that may write a care relationship to a record marked `R` or `V` | none | +| `team_targets` | The `ORGANISATION` units a care relationship may name as its target | none: a care team is a `GROUP` | + +FerroEHR ships no value set and no country content. A code of a bound +attribute is checked against its value set on the +[terminology server](templates-validation.md) when you write the policy; +with no terminology server configured, a policy that binds a value set the +check needs is refused. An unbound kinship is a code of the openEHR +`subject relationship` group. An organisation type has no default code +system, so a rule, an exception or a conflict rule that names an +`organisation_type` is refused `422`, naming it, until the policy binds an +`organisation_type` value set. A template of the default archetype that +fixes some of these attributes for many controllers is a profile: write the +policy with its `template_id`, and FerroEHR validates it against the +template. + +Two more attributes say when a relationship is a ground at all: + +| Attribute | What it says | Left out | +| --- | --- | --- | +| `care_purposes` | The purposes of use for which a care relationship is a ground: an access declaring another purpose, such as research, rests on no relationship and matches no rule scope naming `care` | `TREAT`, `ETREAT` and `CAREMGT` of `HL7_ActReason` | +| `time_zone` | The IANA time zone in which the dates of a relationship's `time_validity` are read, such as `Europe/Amsterdam`; a name the zone database does not hold is refused `422` | UTC | + +#### The attested care path + +A caller from another organisation, admitted under a +[federation agreement](operational-policy.md#federation-agreements), can hold a care +relationship that is never stored: its verified credential attests a +treatment context for the patient. This is how a national contact point or a +national infrastructure reaches the record for cross-border care. The path is +off until `attested_care` names the agreement: + +```json +"attested_care": [ + { "_type": "DV_IDENTIFIER", + "issuer": "https://federation.example", + "id": "0190b3a2-5a3e-7c1d-9e2f-3b4c5d6e7f99" } +] +``` + +- `id` is the container uid of the agreement `ROLE` (the part of its + version uid before `::`), so a new version of the agreement keeps the + reference. +- `issuer`, when you set it, must be the federation issuer the partner's + client identifiers are held under. A policy that names another issuer, or + names under an issuer an id that is no agreement `ROLE`, is refused `422`, + naming `/attested_care//issuer`. + +Which claims carry the treatment context is your data, in the issuer's +`[auth.issuer..federation]` table. FerroEHR reads these fields: + +| Field | What it carries | +| --- | --- | +| `patient.id` | The patient, as `system\|value`: the identifier an EHR's subject names | +| `trc.id` | The id of the assertion that attests the treatment context | +| `trc.not_on_or_after` | The end of its window, in seconds since the epoch | +| `trc.not_before` | The start of its window, when the credential states one | +| `assertion.issuer` | The issuer of the assertion, when the credential states one | +| `trc.care_role` | The care role the treatment relationship attests for the professional, one code with its code system | + +A credential that lacks `patient.id`, `trc.id` or `trc.not_on_or_after` +attests nothing. On every access FerroEHR checks that the policy names the +agreement, that the window holds the moment of the access, and that the +record's subject is the attested patient. The caller then holds a live care +relationship for the care step, the default disposition and any rule whose +actor scope names `relationship: care`. The relationship is never stored and +never in a caseload. The access log names it as a `treatment relationship` +ground whose `reference` is the assertion (`id` and `issuer`) and whose +`name` and `version` are the agreement's. + +The attested relationship holds the role `PART` unless the credential +attests a role in `trc.care_role` of the `care_role` value set the policy +binds (unbound, a code of `HL7_ParticipationType`). The code system of the +attested role is the terminology its code is read in, so a credential whose +role carries the system `HL7_ParticipationType` names a code of that +terminology, and a field mapped as `{ constant = "ATND", system = +"HL7_ParticipationType" }` attests that role for every credential of the +issuer. A role outside that value set, or one no terminology server could +check, counts as no role, and the relationship keeps `PART`. +`ferrohealth-smart` refuses a token whose `trc.care_role` is not one code +with its system. + +A rule limits attested callers like any other: give its actor scope +`relationship: care` with `care_path: attested`. A deny rule's `data` keeps +attested callers from the templates or categories it names, and on a record +the controller marks `R` or `V` an attested caller is refused +`refused-confidentiality` until a permit rule for that path names the level +in its `data` `confidentialities`: + +```json +{ "_type": "ACCESS_DIRECTIVE", "kind": "controller_rule", "effect": "permit", + "applies_to": [ { "_type": "ACCESS_ACTOR_SCOPE", + "relationship": "care", "care_path": "attested" } ], + "data": [ { "_type": "ACCESS_DATA_SCOPE", "confidentialities": [ "R" ] } ] } +``` + +The codes are shown short here; write each as a `DV_CODED_TEXT`. A permit +that names `R` clears `R` and nothing above it, and one written for the +`direct` path clears no attested caller. + +#### Writing a care relationship + +FerroEHR checks each care relationship against the policy when it is +written, and refuses one that breaks a bound with `422`, naming +`/time_validity` or `/target`: + +- **Validity.** A relationship written without an end takes the + `default_period` of the first `relationship_validity` entry that covers its + role and its provider's type, counted from its start (or from the day of + the write when it names no start). One longer than that entry's + `max_period` is refused. One that no entry covers, or whose entry has a + `max_period` and no `default_period`, must be written with an end. An entry + with neither period lets the relationship stay open. +- **Target.** An `ORGANISATION` target must be a unit `team_targets` names, + and is never the controller or the relationship's own provider. +- **Writers.** The level is the highest marking of the subject's records: + every EHR whose subject reference names the relationship's source + `PERSON`, directly or through a record subject the `PERSON` declares. + FerroEHR reads those markings exactly before the commit takes its + connection. At `N` every writer the `write_care_relationship` grant + admits writes. At `R` or `V` only a writer a `relationship_writers` entry + names for that level writes, and its access-log record is flagged for + review with the level: the `review` detail (`id40`) of the entry's + [details](audit.md), the `review` column of `audit.access_trail`, and a + `review` detail on the object of the BALP `AuditEvent` and the DICOM + audit message. Every other write is refused `403`, naming the level and + the missing entry. The administrator is no exception: a + policy that wants the administrator to write such relationships names the + administrator's `PERSON` (or a role it performs) for the level. An entry + for `V` does not cover `R`; name each level the writer may write. +- **Self-declared.** A relationship whose `basis` is `self_declared` is + refused `422` unless the policy sets `self_declared_care`. Its target is + the writer's own `PERSON` (`403` otherwise), and it ends within that period + of its start, by its own end or the one `default_period` gives it. While + the policy sets `self_declared_care`, it admits the professional who wrote + it; once the policy no longer sets it, it admits no one. + +For example, this `relationship_writers` lets the admission system's role +write relationships to records at `R`, and the administrator's `PERSON` +write them at `R` and `V` (the role code and the identifiers are your own): + +```json +"relationship_writers": [ + { "_type": "ACCESS_RELATIONSHIP_WRITER", + "applies_to": [{ "_type": "ACCESS_ACTOR_SCOPE", + "role": { "_type": "DV_CODED_TEXT", "value": "admission system", + "defining_code": { "terminology_id": { "value": "urn:example:roles" }, + "code_string": "adt" } } }], + "confidentialities": [ + { "_type": "DV_CODED_TEXT", "value": "restricted", + "defining_code": { "terminology_id": { "value": "HL7_Confidentiality" }, + "code_string": "R" } }] }, + { "_type": "ACCESS_RELATIONSHIP_WRITER", + "applies_to": [{ "_type": "ACCESS_ACTOR_SCOPE", + "party": { "_type": "PARTY_REF", "namespace": "demographic", "type": "PERSON", + "id": { "_type": "HIER_OBJECT_ID", "value": "" } } }], + "confidentialities": [ + { "_type": "DV_CODED_TEXT", "value": "restricted", + "defining_code": { "terminology_id": { "value": "HL7_Confidentiality" }, + "code_string": "R" } }, + { "_type": "DV_CODED_TEXT", "value": "very restricted", + "defining_code": { "terminology_id": { "value": "HL7_Confidentiality" }, + "code_string": "V" } }] } +] +``` + +The end a relationship takes from `default_period` is never written into the +relationship: the version you committed stays exactly as you sent it, with +its digest and signature. FerroEHR computes the end once, in the commit's +transaction, from the policy version the write read, and keeps it beside the +relationship with the uid of that policy version. Every access decision and +query reads that end. A later policy version does not move it: a changed +period applies to the relationships written after the change. To change the +end of a relationship, write a new version of it. + +Each write reads the newest policy version from the store before it takes +its connection to the demographic store, because the policy lives in the +clinical store. A policy version committed between that read and the commit +applies from the next write; the kept end names the version it came from. + +An archive load (`load_ehrs`) carries no kept ends, so it checks each care +relationship it loads against the policy in force on the server it loads +into, counting a missing start from the day the loaded version was +committed. A relationship the policy refuses is reported in the load's +failure report and is not loaded; the rest of the archive loads. Put the +access policy in place before you load an archive that holds open care +relationships. + +### Exclusions and conflicts of interest + +**An exclusion keeps a named person out of one record.** It is a deny of +kind `exclusion` in the `exclusions` of the EHR's `EHR_ACCESS` settings, +naming the parties it keeps out by `applies_to` (a party, or the +`representative` relationship), with an optional data scope, validity and +legal grounds. It is decided before step 1: it binds a professional, a +representative and a gate-keeper, never the person, and no permit of the +person or a representative lifts it. A declared emergency lifts it only +where its `emergency_override` holds and the caller is no representative. +The caller is answered `403 refused-excluded`, and the answer names neither +the exclusion nor its reason; the access log names the exclusion and the +`EHR_ACCESS` version. A law that lets a provider decline to treat a person +as a representative, for example in a case of abuse, is carried by one. + +Only the controller (a caller holding `admin_role`) reads and writes the +exclusions. Every read of an `EHR_ACCESS` by anyone else, the person and a +gate-keeper included, leaves them out; a version envelope, a contribution +or an AQL row that would carry them reads as absent to such a caller, and +an EHR Extract for the person carries no `EHR_ACCESS` that ever held one. A +version a gate-keeper or the person commits carries the current exclusions +forward unchanged, and one that names other exclusions is refused `403`. + +**A restriction binds a representative it names.** A `restriction` the +person gives binds a representative whose `applies_to` names it by party or +by the `representative` relationship, answered as absent, as it is for a +professional. A controller rule over a label that names representatives +refuses them at step 5. + +**A conflict of interest refuses the professional path.** A professional is +in conflict with the person when it performs a professional `ROLE` and is +bound to the person's `PERSON` (a staff member on their own record), or +when a `related_to` relationship in force joins its `PERSON` to the +person's. It is refused `403 refused-conflict` at step 5, in a read and in a +query, unless an entry of the policy's `conflict_rules` for that conflict +names it (and, for `related`, the kinship); an access such an entry admits +is marked in the access log with a `conflict allowance` ground. A staff +member reads their own record. Kinship refuses +and never grants: a relative passes the other steps as anyone else. + +A kinship is a `PARTY_RELATIONSHIP` of its own named `related_to`, written at +`/demographic/party_relationship` under the `write_care_relationship` grant +or by an administrator, whose source and target are two `PERSON`s and whose +`kinship` element is a code of the value set bound for `kinship` (by default +the openEHR `subject relationship` group). Your demographic service or +master patient index decides who is kin; FerroEHR stores the fact and +decides on it. A query leaves out the EHRs of every person the caller is in +conflict with; a conflict rule that names the `care` relationship admits a +conflict in a direct read of a record the caller cares for, and in a query +reads as not admitting it. + +### Controller rules + +Regulation (EU) 2025/327 Art. 11(3) asks each Member State to lay down +which categories of health data different categories of health +professionals may reach. The access policy's `rules` hold those rules for +every EHR you keep. Each rule is an `ACCESS_DIRECTIVE` of kind +`controller_rule`, with the `applies_to`, `operations`, `purposes`, `data`, +`time_validity`, `emergency_override`, `exceptions` and `legal_grounds` a +directive has. The `ROLE` parties say who holds a role; the rules say what +the role may do. + +- **A deny rule refuses** what it covers with `403 refused-policy-denied`, + whatever the patient's directives permit (step 5). It binds every caller + but the patient on their own record, representatives included. +- **A permit rule clears** the callers it names for the sensitivities its + `data` names (step 6) and decides nothing else. +- **A rule's `purposes` match only a declared purpose.** A request that + declares none is outside every rule that names purposes. Set + `purpose_required` to refuse such a request: it is refused + `refused-purpose-missing` before any rule is read, whatever rules you + hold. +- **A deny rule with a permit exception says "only"**: the exception carves + what it covers out of the deny. +- **A scope naming `care` can name care roles and a path.** With + `relationship` `care`, an actor scope's `care_roles` lists the roles a + caller's live care relationship must have, compared by terminology and + code, and `care_path` says how it must reach the caller: `direct`, `team`, + `self_declared` or `attested`. Left out, any role and the paths the policy + turns on. No role implies another: + `RESP` does not cover `ATND`. The same scope decides a read and narrows a + query inside its one statement, so a `COUNT` agrees with the reads. +- **For a write**, the data are the version being committed: its template, + root archetype, origins and the sensitivities your classifications give it. + +Four rules, as you write them in the policy body (a role code of +`urn:example:roles` stands for your jurisdiction's role terminology): + +```json +"rules": [ + { "_type": "ACCESS_DIRECTIVE", "name": { "_type": "DV_TEXT", "value": "Nurses do not record diagnoses" }, + "archetype_node_id": "id15", + "kind": { "_type": "DV_CODED_TEXT", "value": "controller_rule", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "controller_rule" } }, + "effect": { "_type": "DV_CODED_TEXT", "value": "deny", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "HL7_ConsentProvisionType" }, "code_string": "deny" } }, + "applies_to": [{ "_type": "ACCESS_ACTOR_SCOPE", "role": { "_type": "DV_CODED_TEXT", "value": "Nurse", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "urn:example:roles" }, "code_string": "NURSE" } } }], + "operations": [{ "_type": "DV_CODED_TEXT", "value": "write", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "write" } }], + "data": [{ "_type": "ACCESS_DATA_SCOPE", "templates": ["Diagnosis"] }], + "emergency_override": false } +] +``` + +- **A nurse may not record a diagnosis:** the rule above. +- **Only psychiatry reads mental-health notes:** classify the mental-health + templates `PSY` (HL7 v3 `ActCode`), and write a `permit` rule whose + `applies_to` names the psychiatrist role and whose `data` names the + sensitivity `PSY`. A patient's consent permit naming their GP clears the + GP in the same step; everyone else is refused `refused-sensitivity`. +- **Professionals may declare only treatment or emergency treatment:** a + `deny` rule whose `applies_to` names the caller kind `professional`, with + one `permit` exception whose `purposes` are `TREAT` and `ETREAT`. A request + declaring another purpose is refused `refused-policy-denied`. A request + declaring none is refused `refused-purpose-missing` where the policy sets + `purpose_required`, and otherwise `refused-policy-denied`, since the + exception names no request without a purpose. +- **Only the responsible practitioner, directly, signs the discharge + summary:** a `deny` rule on `write` whose `data` names the discharge + summary template, with one `permit` exception whose `applies_to` is + `relationship` `care`, `care_roles` `[RESP]` and `care_path` `direct`. A + second in chain (`SPRF`), a consultant (`CON`) and a team member are + refused `refused-policy-denied`; a professional covering for the + responsible one holds a `RESP` relationship of their own for the period + and is admitted. +- **A system client writes only its laboratory templates:** a `deny` rule on + `write` whose `applies_to` names the client's `AGENT` by `party`, with one + `permit` exception whose `data` lists the templates. +- **Only care providers reach records through the exchange:** a `deny` rule + whose `applies_to` names the caller kind `access_service`, with one + `permit` exception whose `applies_to` lists one `organisation_type` per + care provider type, and the provision in its `legal_grounds`. A partner's + professional whose token attests an insurer's facility type, or none, is + refused `refused-policy-denied`. A second `deny` rule naming a `role`, such + as an occupational physician, or `purposes`, such as a medical + examination, keeps those out too. A rule naming `purposes` refuses only a + request that declares one of them, so set `purpose_required` to refuse a + request that declares none. Wabvpz Art. 15f is a rule of this kind: you commit it, + FerroEHR holds no copy of it. + +A rule whose `emergency_override` is true is lifted for a caller that +invokes an emergency +[justification](access-control.md#justified-access-outside-the-care-relationships) +with a reason, and the access record names the rule. The access record of a refusal names the +rule by its uid, its first identifier or its position in `rules`, and a +`legal obligation` ground carrying the rule's `legal_grounds`. The `403` +problem body carries them in its `legal_grounds` member beside `refusal`, +each with its `terminology`, `code` and `value`, under +`Prefer: return=representation`. + +**A federation agreement and the rules.** A federation agreement is the +contract with a partner: its `template` elements say what the partner's +persons may send. The rules are your own limits, and they hold for a +partner's persons too: a deny rule refuses a template the agreement allows, +because a deny overrides. + +No openEHR specification has a controller rule: the rules, their place as +step 5 after the purpose check, matching a rule's purposes only on a +declared purpose, reading a role from the coded name of a `ROLE` and an organisation +type from the coded name of an `ORGANISATION`, reading a partner's attested +roles and facility types as the same facts, and naming a refusing rule's +legal grounds as a `legal obligation` ground are FerroEHR's own design, +proposed in the draft access control specification. diff --git a/website/book/src/application-boundary.md b/website/book/src/application-boundary.md index b46fada578..ff36fd2559 100644 --- a/website/book/src/application-boundary.md +++ b/website/book/src/application-boundary.md @@ -20,12 +20,12 @@ deployment own, and what each uses in FerroEHR instead. | Left to the application | Who owns it | What it uses in FerroEHR | |---|---|---| -| Country and jurisdiction content: lists of professional roles and their names, organisation types, kinship codes, identifier systems, default periods of a relationship | the deployment, on its terminology server | the value-set bindings of the access policy ([Care relationship facts](operational-policy.md#care-relationship-facts)) and its relationship periods; FerroEHR ships no such list of its own | -| Deciding who represents a patient: from which age a minor decides alone, whether a person can decide for themselves, which legal basis applies, what happens when the patient dies | the care delivery environment, under its national law | a stored representation, a `PARTY_RELATIONSHIP` of its own with its basis, its provider and its period ([Representatives](operational-policy.md#representatives)). You end it by closing its period | -| Deciding who is in a patient's care: admissions, referrals, registrations with a practice, rosters and cover | the admission, rostering or practice system | stored `under_care_of` relationships, each its own `PARTY_RELATIONSHIP` with a role and a provider, naming a professional, a role, a team or a unit, and team memberships ([Caller facts](operational-policy.md#caller-facts-roles-and-care-relationships)); the relationship resources read and write them by subject and by carer ([The care relationship resources](operational-policy.md#the-care-relationship-resources)) | -| Households, family files and family plans | the application that works with families | care relationships to a group and representation relationships; the controller's exclusions and restrictions that bind a representative ([Exclusions and conflicts of interest](operational-policy.md#exclusions-and-conflicts-of-interest)) and confidentiality labels on single compositions | -| Worklists: a professional's caseload list, a list of relationships due for review | the client application | AQL, narrowed to your [caseload](care-relationships.md#the-caseload) by the `caseload`, `caseload_roles` and `caseload_episodes` request members, and the reverse reading of the relationship resources ([The care relationship resources](operational-policy.md#the-care-relationship-resources)) | -| Matching a staff member's person to a patient's person, so a conflict of interest can be seen | the master patient index or the demographic service | the person identifiers you store and a `related_to` fact, on which FerroEHR refuses the professional path ([Exclusions and conflicts of interest](operational-policy.md#exclusions-and-conflicts-of-interest)) | +| Country and jurisdiction content: lists of professional roles and their names, organisation types, kinship codes, identifier systems, default periods of a relationship | the deployment, on its terminology server | the value-set bindings of the access policy ([Care relationship facts](access-policy.md#care-relationship-facts)) and its relationship periods; FerroEHR ships no such list of its own | +| Deciding who represents a patient: from which age a minor decides alone, whether a person can decide for themselves, which legal basis applies, what happens when the patient dies | the care delivery environment, under its national law | a stored representation, a `PARTY_RELATIONSHIP` of its own with its basis, its provider and its period ([Representatives](caller-facts.md#representatives)). You end it by closing its period | +| Deciding who is in a patient's care: admissions, referrals, registrations with a practice, rosters and cover | the admission, rostering or practice system | stored `under_care_of` relationships, each its own `PARTY_RELATIONSHIP` with a role and a provider, naming a professional, a role, a team or a unit, and team memberships ([Caller facts](caller-facts.md#caller-facts-roles-and-care-relationships)); the relationship resources read and write them by subject and by carer ([The care relationship resources](caller-facts.md#the-care-relationship-resources)) | +| Households, family files and family plans | the application that works with families | care relationships to a group and representation relationships; the controller's exclusions and restrictions that bind a representative ([Exclusions and conflicts of interest](access-policy.md#exclusions-and-conflicts-of-interest)) and confidentiality labels on single compositions | +| Worklists: a professional's caseload list, a list of relationships due for review | the client application | AQL, narrowed to your [caseload](care-relationships.md#the-caseload) by the `caseload`, `caseload_roles` and `caseload_episodes` request members, and the reverse reading of the relationship resources ([The care relationship resources](caller-facts.md#the-care-relationship-resources)) | +| Matching a staff member's person to a patient's person, so a conflict of interest can be seen | the master patient index or the demographic service | the person identifiers you store and a `related_to` fact, on which FerroEHR refuses the professional path ([Exclusions and conflicts of interest](access-policy.md#exclusions-and-conflicts-of-interest)) | | Screens and workflows for any of the above | the client application | the REST resources over the stored facts | A fact you store takes effect on the next request: FerroEHR confirms every diff --git a/website/book/src/audit-integrity.md b/website/book/src/audit-integrity.md new file mode 100644 index 0000000000..c52e02f54c --- /dev/null +++ b/website/book/src/audit-integrity.md @@ -0,0 +1,397 @@ +# Tamper evidence, seals and retrieval + +How the audit trail shows it has not been changed, how a log is sealed and moved, and how +an audit record repository retrieves records (ITI-81) and authenticates nodes (ITI-19). + + + +## Tamper evidence + +An audit trail that anything with the application's database password can +quietly rewrite is a log, not an accountability record. The local store is +therefore tamper-**evident**. The system records (`audit.audit_event`, the +system chain) and the access log's entries are each sealed in windows, each +seal following the one before it and covering every record of its window by +its position and content digest +([Seals, checkpoints and the transfer of a log](#seals-checkpoints-and-the-transfer-of-a-log)). + +A request writes each system record once, in `audit.audit_event`, and never +changes it. Its position (`seq`) is drawn after its transaction took its +id, and its content digest is computed by the server when it writes the +record: the SHA-256 of the RFC 8785 form of the array +`["ferroehr.audit_event.v7", {column: value}]` over every column but `seq` +and the digest, with SQL `NULL` as `null`, booleans as booleans, text and +UUIDs as strings, integers (`integer[]` element by element) as decimal +strings, instants as `YYYY-MM-DDTHH:MM:SS.ffffffZ` in UTC, dates as +`YYYY-MM-DD`, `bytea` as lower-case hexadecimal and `jsonb` as its value +(`system_log::content_digest`, with the SQL that builds the object for an +auditor). A column added by a later release joins the digest under a new +form in the same release. A record a write still holds is in no search, no +feed and no window. Which records a sink still owes is told by its cursor +(`audit.delivery_cursor`): the records past it up to the delivery frontier, +and those it parked ([How a record is delivered](audit.md#how-a-record-is-delivered)). + +The store keeps a record's facts in columns and renders its FHIR `AuditEvent` +from them when the record is read (ITI-81) or delivered (the FHIR feed). What +the rendering takes from the configuration (`source_id`, `enterprise_site_id`, +`server_host`, `value_if_missing`, the access policy's log retention and the +audit category register) is kept once per distinct configuration in +`audit.audit_render_policy`, keyed by the SHA-256 of its text, and every record +names the policy it was written under. A record therefore renders the same +document after the configuration changes, and the verification below reports a +policy whose text no longer matches its digest, as it reports a changed record. +Release 5.6.0 starts on an empty audit store: its migration refuses a store +that holds records written by an earlier release, and names the remedy. + +Four controls sit on top of it, and they are separate on purpose: + +- **The table refuses the ordinary rewrite paths outright.** An `UPDATE`, a + `DELETE` and a `TRUNCATE` of a stored record are refused by the database, + and so are a change to a seal or to a reaped position. + Retention pruning goes through the one sanctioned deletion path, which keeps + each removed record's position and content digest + (`audit.audit_event_reaped`) so its window still verifies, and removes those + only once every record of a sealed window is reaped, recording the window as + folded; so reaping does not look like tampering, and tampering does not look + like reaping. +- **The privileges are narrow.** The runtime role may record an event, stamp it + forwarded, and read the trail back. It holds nothing that can rewrite a + record, remove one, or alter a reaped position. That posture is only + fully in force with `database.migrations = "verify"`; see + [Operations](database-operations.md#database-roles-and-least-privilege), because a + self-migrating server owns the schema and can therefore turn the enforcement + off. +- **Verification is something you can run yourself.** For the system + records it is `ferroehr audit-chain verify`, for the access log + `ferroehr access-log verify` (or `POST /admin/access-log/verify`); each + recomputes every sealed window, every record's content digest, and follows + every seal from the one before it to the seal state. No finding means the + trail is intact. A finding names one record or window (its position, the + record's id and time when it is still there) and what is wrong with it: + content modified after it was written, a render policy, search token or + search set changed or missing, a record changed, removed or inserted inside + a sealed window, or seals removed from the end. +- **The server runs the check itself, on a schedule.** With the local store on, + the check runs one minute after boot and then every + `[audit.store] verify_interval` (default `3600`, one hour; `0` turns + it off). Each run verifies the windows sealed since the newest window an + earlier run found intact, and the seal state, so its cost follows the + records sealed since rather than the size of the trail. It walks each + log's sealed windows from its own cursor, one snapshot per step, each + sized to take about half a + second, and each intact step moves the cursor, so a backlog of any size is + verified in one run and no statement nears the + `[database] statement_timeout`. After each step the run pauses at least as + long as the step took, and longer the more the step's cost per record rose + above the lowest the server has measured for that chain: a step that cost + twice as much pauses four times as long, up to 16 times. A catch-up + therefore takes about half a core of a quiet database and yields to the + requests under load, where the lag can grow until the load falls. How far + a cursor is behind is + the `audit_chain_verification_lag` and `audit_chain_unverified_age_seconds` + metrics; once the oldest unverified record has waited longer than + `[audit.store] max_verify_lag` (default four hours), the `audit_chain` + indicator reads `DEGRADED` and names the chain. + A full pass + runs every `[audit.store] full_verify_interval` (default `604800`, + one week; `0` leaves it to the commands above) and after every run that found + damage, so damage to an older record stays reported. A run that finds damage logs at `ERROR`, one summary line with the + finding count and one line per finding (the first 20), and adds the count to + the `atna_audit_chain_findings` counter with `kind = "damage"`. A run that + cannot verify at all counts as `kind = "unverifiable"`, because a trail that + cannot be checked is never a pass. The latest result is the `audit_chain` + indicator on `GET /health/readiness`: `UP` while intact and `DEGRADED` + when damaged or unverifiable; its detail on `GET /management/health` names + the first finding. It never flips + readiness, because the trail keeps recording while the damage is + investigated. Alert on the counter or on that component, and use the + commands above to see every finding. Each replica runs its own check. + +> [!IMPORTANT] +> This is **detection, not prevention**, and the boundary is worth stating +> plainly. The unsigned seals are unkeyed, so a party with unrestricted +> write access to the `audit` schema (the database owner, or a superuser) can +> delete a record and recompute every seal after it; a signed seal kept +> outside the database shows that. A record newer than the last seal, at +> most a minute plus the frontier's lag, is protected by the refused changes +> and the grants alone. What closes that case is keeping the trail +> somewhere that party does not control. Enable +> `[audit.syslog]` or `[audit.fhir_feed]` so records leave the box as they are +> written, and give the server an app-role-only DSN so it is not that party. + +## Seals, checkpoints and the transfer of a log + +The records of the openEHR access log (`audit.access_log_record`) hold only +the accesses to EHR data, apart from the `audit_event` records above, the +system chain (an authentication, a template, party or application +operation). Neither carries a chain. A request writes each entry or +system record once, before its response, and every reader, the delivery and +the sealer read that row. What follows holds for both logs, each with its +own id sequence, holds, seals and tag, unless it names one. + +- **The frontier.** A round on every replica's audit runtime, about once a + second, moves the log's frontier: the highest entry id at or below which + every entry is committed or never will be. Every insert takes its + transaction's id before any row draws its entry id, so an entry id the + round has seen belongs to a transaction that a later snapshot shows ended. + A long writing transaction anywhere in the database delays the frontier + and loses nothing: an entry is in the log from its own commit. The + entries of a write whose commit is not yet confirmed are held, in no read, + and the frontier the sealer and the delivery use stops below them. +- **A window a minute.** About once a minute the sealer seals every entry + id past the last window, up to that bound, as one window. A seal is the + SHA-256 of this text, which you can rebuild from the stored rows: + + ```text + 27:ferroehr.access_log.seal.v1 (the system records: 27:ferroehr.system_log.seal.v1) + : + : + : + : + 64: + then, for each entry of the window in id order: + : + 64: + ``` + + Each field is its length in bytes in decimal, a colon, the field and a + line feed; integers are decimal, digests lower-case hexadecimal. The first + window follows the SHA-256 of the version tag. A tombstone keeps the content + digest of the entry it replaced, and a reaped system record leaves its + position and content digest, so its window verifies after the content is + gone. `GET /admin/access-log/seals` answers the access log's seals over a + span of entry ids. +- **The signed checkpoint.** With an OpenPGP key in the version-signing + keyring, each seal is signed as the `ACCESS_LOG_CHECKPOINT` of the log up + to the window's last entry id, whose `digest` is the seal's digest, in the + form RM common `master04-generic_package.adoc` §Attestation gives + `ATTESTATION._proof_`. A deployment without a key seals without signing, + and `ferroehr access-log checkpoint` refuses. `ferroehr access-log + checkpoint` and `POST /admin/access-log/checkpoint` seal every committed + entry and answer the newest checkpoint; `GET /admin/access-log/checkpoint` + answers the newest stored one, or the one at `sequence`. +- **What is left unsealed.** A record of either log newer than the last + seal, at most a minute and the frontier's lag, is protected by the refused + `UPDATE` and `DELETE` and by the runtime role's grants alone. The CRA risk + assessment (C4, C5) and hazard H7 state that window. +- **Publish the checkpoints outside the database.** Someone who can write + the database can remove the newest windows together with their seals, and + nothing left in the database shows it. Set `[audit.access_log] + publish_directory` to storage that person cannot rewrite: every 30 seconds + the server writes the newest checkpoint there as its own file, + `access-log-checkpoint-.json`, created once and never + rewritten. Without it the `access_log_checkpoints` health indicator reads + `DEGRADED`. To verify the log against a published checkpoint, run + `ferroehr access-log verify --checkpoint ` with the newest file. +- **Verification.** `ferroehr access-log verify` and `POST + /admin/access-log/verify` recompute every window from its rows and every + column the log derives from an entry's content, follow the seals from one + to the next to the sealer's state, and check the checkpoint's signature and + that the seal at its position is the one it signs. A changed, removed or + inserted record inside a sealed window is reported, as is a removed seal. + They also verify every imported bundle. +- **The fold.** Once every record of a sealed window is a tombstone past its + end, the retention run removes the window's entries and records the window + as folded with the grounds its tombstones named. Its seal stays, so the + seals still follow one another. +- **Moving the log with the EHR.** `ferroehr access-log export ` and + `POST /admin/access-log/export?ehr_id=…` export one EHR's records as a + bundle: each record with its content digest, signed whole by this system's + keyring over its RFC 8785 form without its proof. It carries no record or + digest of another person. `ferroehr access-log import ` verifies the + signature against the certificates in `[audit.access_log] + trusted_key_files` and every entry's digest, keeps the records with their + `system_id`, `retain_until` and content digest, and records the import as + an entry of this log that names the bundle's digest and a digest over the + imported records' uids and content digests, so this log's seal covers + them. An imported entry ends at the `retain_until` it states; its + tombstone is kept as long again and then folds, leaving its uid, bundle + and content digest so the bundle still verifies. A repeated import stores + nothing twice. +- **The system records are sealed too.** The same sealer and key seal their + windows (`audit.audit_event_seal`), each signed as a seal naming the + window's last position and its digest. `ferroehr audit-chain seal` seals + every committed record on demand and prints the newest signed seal, and + `ferroehr audit-chain verify [--seal ]` recomputes every window, + checks the seal's signature and that the window ending at its position has + the digest it fixes, and exits 1 when the records do not verify. Retention + removes a system record at its own end and keeps its position and content + digest; once every record of a sealed window is reaped, the window's + reaped positions are removed and the window recorded as folded. +- **The erasure is recorded once.** `POST /admin/access-log/erase` writes the + tombstone and the entry that records the erasure in one transaction; the + erasure is not written a second time as an `audit_event` record. + +## Retrieving audit records (ITI-81) + +The RESTful-ATNA **ITI-81 Retrieve ATNA Audit Event** transaction is a FHIR +search on `AuditEvent`, so it is served at FerroEHR's FHIR R4 base, +`/ferroehr/rest/fhir/r4`, beside the openEHR API rather than under it, where a +FHIR client or an IHE Audit Consumer expects `[base]/AuditEvent`. It is the one +FHIR route FerroEHR serves: + +```text +GET /ferroehr/rest/fhir/r4/AuditEvent +``` + +It returns a FHIR `searchset` Bundle of the matching records' `AuditEvent` +documents, rendered from the store, newest first, with a `self` link and a +`next` link while more pages follow. The page carries the full match `total` +only when the query asks for it with `_total=accurate` or `_total=estimate` +(FHIR R4 Search §3.1.1.5.2): counting every match reads every record the +filter selects, and a page alone reads one record past what it serves. The query is read by `ihe-atna`, the family's audit +crate. At least one `date` parameter is required (RESTful ATNA +§3.81.4.1.2.1): a query without one is a `400`. Every search parameter +§3.81.4.1.2.2 says the repository shall support is applied. A parameter +with several comma-separated values matches any of them, and every +parameter of the query must match. A token takes the three forms of FHIR R4 +Search §3.1.1.4.10: `code`, `|code` (recorded without a system) and +`system|code` (or `system|` for any code of that system). FerroEHR records +identifiers without a system, except the object of an access record, whose +system is `urn:openehr:object-id`: `entity.identifier=urn:openehr:object-id|` +and `entity.identifier=` find it, and a query that names another system +for an identifier matches nothing. Every parameter answers through an index. A +parameter on an element of the document (`address` and the `.identifier`, +`entity-type`, `entity-role`, `type` and `subtype` parameters) matches the +search tokens the store takes from the record's rendered document +(`audit.audit_search_token`, `audit.audit_search_set` and the record's +`search_tokens`): a system record's when the store writes it, an access-log +entry's when the frontier round renders it from the stored entry into +`audit.access_log_index`, about once a second, which go with the entry's +content when a tombstone replaces it. A search on such a parameter first +moves the index past every entry written before it, so it finds an entry +written a moment ago; when an open database transaction keeps it from doing +so within 2 seconds, the search answers `503` with `Retry-After`. So the +search finds what the served document says and renders only the page it +serves. An `entity.identifier` that carries +the record's request id or the object it names (the version uid of a create) +is read from the record's own column instead, so a request adds no row to +`audit.audit_search_token`. One GIN index per record table holds the search +tokens and a key for each of the request id and the touched resource id +(`audit.search_keys`), which answers `entity` and such an `entity.identifier` +as well; the search then compares the text. Retention deletes the tokens +that no remaining system audit record, access-log entry or search set names, +and never one a kept record names. + +| Parameter | Matches | +|---|---| +| `date` | **required**, repeatable: a FHIR date value with a prefix (`eq` when none, `gt`, `lt`, `ge`, `le`, `sa`, `eb`); a day such as `2026-07-12` covers the whole day, read in UTC | +| `patient` | the recorded patient (EHR subject) id | +| `patient.identifier` | `entity.what.identifier` of the entity whose role is Patient | +| `agent` | the authenticated principal | +| `agent.identifier` | `agent.who.identifier` | +| `entity` | the touched resource id | +| `entity.identifier` | `entity.what.identifier` of any entity | +| `entity-type` | `entity.type` | +| `entity-role` | `entity.role` | +| `source.identifier` | `source.observer.identifier`, the audit source id | +| `type` | `type` | +| `subtype` | `subtype` (the REST interaction and the openEHR operation) | +| `address` | a part of `agent.network.address`, compared without regard to case | +| `outcome` | the outcome indicator: `0`, `4`, `8` or `12` (FerroEHR records `0`, `4` and `8`) | +| `action` | the action code: `C`, `R`, `U`, `D` or `E` | +| `_count` / `_offset` | paging; page size defaults to 50, capped at 1000; `_count=0` returns the total alone | +| `_total` | `accurate` or `estimate` adds the full match `total`; `none`, or no `_total`, serves the page without it; any other value is a `400` | + +A malformed value is a `400` carrying a FHIR `OperationOutcome` with +`invalid`; another FHIR R4 `AuditEvent` parameter, which §3.81.4.1.2.2 does +not ask for, is a `400` with `not-supported`; a parameter the crate does not +know is ignored +(§3.81.4.1.3). Under RBAC the +unscoped retrieval is **admin-only**; a caller holding a +`read_subject_audit` grant, an app acting for the people it +serves, reads it **scoped to one subject**: one +`patient` or `patient.identifier` with one value is required, and the caller +is refused with a `403` that names the parameter when it omits +it. Reading a subject's log is itself recorded as an access naming that +subject and the record count served. An +[justified access](ehds-logging.md#justified-and-emergency-access) in the subject's log carries the clinician's reason +as the text of its purpose of use, and an emergency its mark as the +`ehds-emergency-access` entity. The surface answers `404` when the local +store is disabled. + +The subject-scoped ITI-81 read stays beside the [access-log +resources](access-log.md#reading-the-access-log-over-its-rest). It serves the ATNA records +as FHIR `AuditEvent`s to a portal that holds a `read_subject_audit` grant and +names the subject itself; `GET /ehr/{ehr_id}/access_log` serves the openEHR +access-log entries of the same accesses to the person, or their +representative, under the person's own credential. + +```bash +# Who accessed patient-42's data this month? +curl -u admin:pw \ + "https://cdr.example.org/ferroehr/rest/fhir/r4/AuditEvent?patient=patient-42&date=ge2026-07-01T00:00:00Z" +``` + +This is also the openEHR "record demerging" instrument: when data lands in +the wrong EHR, the patient-filtered audit search shows exactly who read it. + +> [!NOTE] +> Audit records are themselves sensitive (they name patients, subjects and +> actions) so this endpoint is a PHI-disclosure surface and is authorized like +> any other. + +## Node authentication (ITI-19, mutual TLS) + +ATNA's second half is node authentication. `[server.tls]` terminates TLS +natively and can demand a verified client certificate: + +```toml +[server.tls] +certificate_file = "/etc/ferroehr/server.pem" +key_file = "/etc/ferroehr/server.key" +min_version = "1.3" # 1.3 (default) | 1.2 +client_auth = "required" # none | optional | required +client_ca_file = "/etc/ferroehr/client-ca.pem" +``` + +The protocol floor is **TLS 1.3 only** by default, as RFC 9325 §3.1.1 has it +supported. Setting `min_version = "1.2"` enables +1.2 *alongside* 1.3, never instead of it, for a client that genuinely cannot +do 1.3, such as an older integration engine or a pinned Java runtime. TLS 1.1 +and 1.0 are refused when the configuration is read (RFC 8996). + +With `client_auth = "required"`, only clients presenting a certificate +chaining to your explicit trust anchor complete the handshake: the IHE +mutually-authenticated-node posture. Deployments terminating TLS at an +ingress leave `[server.tls]` unset and enforce mTLS there instead. + +> [!WARNING] +> The separate-port management listener (`management.listen`) stays **plain HTTP** +> even with `[server.tls]` set, and it binds all interfaces. Treat it as an +> internal surface and keep it off any publicly routed port. Under +> `deployment.profile = "production"` setting it opens the `plaintext_listener` +> gap, so the server refuses to start unless the gap is accepted by name. + +Complete the posture with time synchronisation (IHE Consistent Time): run +NTP/chrony on every node so audit timestamps align across systems. + +## Against independent ATNA implementations + +The transactions above are tested by FerroEHR's own suites, which read the +profiles the way FerroEHR's authors read them. EHDS Annex II 1.4 asks that a +component meant to work with other products does so reliably, so +[`scripts/interop/atna.sh`](https://github.com/FerroHEALTH/FerroEHR/blob/main/scripts/interop/atna.sh) +runs the quickstart against software FerroEHR's authors did not write, each +from a published image: + +| Transaction | Independent implementation | What the run requires | +|---|---|---| +| ITI-20 FHIR feed | HAPI FHIR, an open-source FHIR R4 server, as the Audit Record Repository, with IHE BALP 1.1.4 loaded | It accepts every record, and its validator finds no error against base R4 and the BALP profile each record names | +| ITI-20 syslog | syslog-ng over RFC 5425 TLS | Every message parses as RFC 5424, and its payload is a well-formed DICOM PS3.15 A.5.1 `AuditMessage` (libxml2) | +| ITI-81 | HAPI FHIR's AuditEvent search over the records the feed delivered | The same searches answer the same records on both | + +```shell +cargo build --release -p loadtest +bash scripts/interop/atna.sh ghcr.io/ferrohealth/ferroehr: \ + ghcr.io/ferrohealth/ferroehr-postgres: atna-out +``` + +It prints every disagreement and exits non-zero on any. A disagreement is +either FerroEHR's or a shared crate's defect, filed and fixed, or the other +side's, recorded with the profile text that shows it. + +The run of 2026-10-29 found no disagreement: HAPI FHIR accepted and validated +all 71 records of the window, syslog-ng parsed all 72 messages, and the ten +ITI-81 searches answered the same records on both repositories +([the record](https://github.com/FerroHEALTH/FerroEHR/blob/main/docs/conformance/interop/atna/2026-10-29.md)). diff --git a/website/book/src/audit.md b/website/book/src/audit.md index b8933da770..b132452aa0 100644 --- a/website/book/src/audit.md +++ b/website/book/src/audit.md @@ -26,6 +26,11 @@ as every version change): openEHR audit records what a version says about its own authorship; ATNA records security surveillance of *access*, including reads and rejected attempts. +This page covers the record and its sinks. The openEHR entry is on [The access +log](access-log.md), the EHDS elements on [The EHDS logging +elements](ehds-logging.md), and the seals, ITI-81 retrieval and node +authentication on [Tamper evidence, seals and retrieval](audit-integrity.md). + ## The record, in both official formats Every audited operation produces one record, rendered in the two formats the @@ -96,243 +101,6 @@ ever names an identity that did not authenticate. > identity provider, so neither mints a per-request login record. Rejections > are recorded regardless of this switch. -## The openEHR access-log entry - -Every access to EHR data is recorded as an openEHR access-log entry: an -`ACCESS_LOG_ENTRY` of the draft `org.openehr.rm.access_log` 0.1.0 model, -FerroEHR's proposal to openEHR, which no openEHR release defines yet. Reads, -writes, AQL queries, exports, refusals and reads of the access log itself each -write one. An access that reaches several EHRs writes one entry per EHR, and -the entries of one request share its request id, so a population query writes -one entry for each EHR that contributed a row, a statement that projects -only the EHR (`SELECT e/ehr_id/value FROM EHR e`) included. - -The administrative routes that touch an EHR write entries the same way, one -per EHR they touched: the physical EHR delete, one EHR or in bulk; the -restriction, research-objection, access-delay and access-repair registers and -the `EHR_ACCESS` settings commit that carries a restriction or an opt-out; -archiving an EHR and restoring it; its retention anchor and the retention hold -on one of its objects; the repository dump and load; and the EHR Extract -export and import. An export's entry names the request it answered, the bound -party and the provider, as every other access entry does. The import of another system's access log (`ferroehr -access-log import`) writes its `import` entry through the same path. SCIM -provisioning touches party data only and writes none. - -The entry names who accessed (the bound party, the groups, the provider, the -binding outcome and the credential by its issuer, subject, client and token -id), what (the EHR, the version or object, its categories and origins), why -(the declared purposes), under which authorisation (the agreement, the -representation, a data permit, a justification with the clinician's reason, -and the grounds of the access decision below), the outcome (`granted`, `refused` or `failed`) and -the request. It carries no data value of the EHR: -a query is named by its stored name or the SHA-256 of its text, never the -text, and a read of the access log through ITI-81 is named by the digest of -its search. - -**The grounds of the access decision.** The access evaluator's decision on -the EHR is in the entry's `authorisations`, each an `ACCESS_AUTHORISATION` -whose `name` and `version` name the document the ground is defined in: - -| Kind | When | What it names | -|---|---|---| -| `role` | always | each grant the caller held, by its operation code (`name`) and the `ROLE` that carries it (`reference`); each role the caller held | -| `subject of care` | the person reads their own record | | -| `consent` | a consent permit admitted the access, or the caller is a gate-keeper of the settings | `EHR_ACCESS` and the uid of its version; the directive by its uid, its first identifier or its position from 1, and its legal grounds | -| `representation` | a `delegation` permit admitted a representative | as `consent` | -| `treatment relationship` | the decision read a live care relationship, also when only a controller rule's exception reads it | in `care` the relationship the access rested on, with its `role` and `path`. A stored relationship is an `ACCESS_STORED_CARE_GROUND` under `ACCESS_POLICY` and the uid of its version: its target (`carer`: the professional's `PERSON` or `ROLE`, or the care team or unit), the uid of its version (`relationship`), whether the grace after its end admitted the access (`in_grace`), the carer it covers for (`covers_for`, with the carer's kind as its `type`), its `provider` and the episode of care it is scoped to (`episode`, absent for a relationship that names none). One a verified credential attests is an `ACCESS_ATTESTED_CARE_GROUND` on the `attested` path under the agreement's name and version: the `assertion` (`id`, `issuer`) and the `agreement` (the container uid of its `ROLE`, with the partner's federation issuer); the ground's `reference` names the assertion too. Where several admitted it, `direct` comes before `team` before `self_declared` before `attested`, then the order of the roles in the rule that matched | -| `justification` | a [justification](security.md#justified-access-outside-the-care-relationships) of the access policy admitted the caller outside its care relationships | `ACCESS_POLICY` and the uid of its version, the justification by its position from 1 (`reference`, type `justification`), and the clinician's own words in `reason`; an entry naming the objects it delivered names it only when one of them rested on it | -| `emergency` | an emergency justification admitted the access, or lifted a directive, a controller rule or steps 6 to 8 | for the justification itself, as `justification` with its `reason`; for each directive or rule it lifted, the directive, or the `ACCESS_POLICY` version with the rule by its uid, its first identifier or its position from 1, and no `reason`; an entry naming the objects it delivered names only the directives and rules whose data scope covers one of them | - -The entry of each EHR an AQL query served names the same grounds a read of -that EHR alone names. The query's condition is built from this replica's copy -of every EHR's settings, which holds each EHR's subject and the uid of its -`EHR_ACCESS` version beside the settings, so the record adds no database read. -For an EHR with no settings, which the copy does not hold, a care relationship -is named when only a caller in care could have been served its rows, without -the relationship itself. In the FHIR `AuditEvent` the care relationship's -role is an `agent.role` coding of the requestor, its HL7 code system named by -its canonical URL (`HL7_ParticipationType` as -`http://terminology.hl7.org/CodeSystem/v3-ParticipationType`), and the -policy version that named it is among the requestor's `agent.policy`. In -the DICOM message the same role follows the held roles as a `RoleIDCode` in -that code system. Both forms carry it, and a projection written from the log -reads the ground back, so it carries the role as the live record does. - -`accessor.binding` says how FerroEHR bound the login to the party, or why -it could not, in the `credential binding` group of the `openehr_access` -terminology: `bound`, `provisional`, `subject of care`, `external`, -`organisation` and `system` for a login it bound, and the cause for one it -refused, such as `unbound`, `party inactive`, `no agreement` or `treatment -relationship confirmation missing`. The draft terminology page lists every -code. - -A refusal names its code in `outcome.reason`, in the `openehr_access` -terminology, and in `outcome.description` the step that refused and the -directive or policy of that step, such as `step 2 (restriction): directive 1 -of EHR_ACCESS 5a1c…::cdr.example.org::2`. This holds for the `404` of an -opt-out or a restriction too: the response says nothing (EHDS Art. 8), and -the entry says why. A justified access and an emergency name their -justification with the reason, so the person sees them in their access log -(EHDS Art. 9 and 11(5)). The EHDS record -writes the versions the grounds name after the data permit at -`agent[user].policy`, "the policy or plan that authorized the activity being -recorded" (FHIR R4 `AuditEvent.agent.policy`), read from the entry's grounds -when the record is rendered. Which grounds are named is FerroEHR's own design. - -**The entry is the record.** The store keeps an access to EHR data as its -entry alone, in `audit.access_log_record`, sealed in windows (see -[Tamper evidence](#tamper-evidence)), and each entry states the date it is -kept until and why. The FHIR `AuditEvent` the ITI-81 search and the ITI-20 -FHIR feed serve, the DICOM message the syslog sink sends and the EHDS access -record are projections of the stored entry: each is written from what the -log keeps and from nothing else, and none is stored as a second record. -`audit.audit_event` keeps the records of accesses outside the access log: an -authentication, a template or party operation, an application activity. - -The entry is written with every other record of its request in one database -transaction before the response leaves, and an access whose entry cannot be -written is refused with `503` ([how a record is written](#how-a-record-is-written)). - -### The access log details - -The draft's core attributes are openEHR's: the action, the outcome, the -accessor, the items, the query, the authorisations, the channel. The facts -the BALP `AuditEvent`, the DICOM message and the EHDS access record carry -that the core holds no attribute for are kept in the entry's -`other_details`, which the draft gives to the fields a jurisdiction adds: one -`ITEM_TREE` under the archetype `openEHR-EHR-ITEM_TREE.access_log_details.v1`, -one `ELEMENT` per fact, named by its node id. A fact the core states as the -access holds it, such as the principal the credential names or the count the -outcome delivered, is not repeated there: read the core first and the -details beside it. They are part of the entry, so its window's seal covers -them, and a tombstone removes them with the rest of its content. - -The archetype is published, so another system reads the details of an -exported log by it. FerroEHR ships it among its default definitions -(`openEHR-EHR-ITEM_TREE.access_log_details.v1.0.0.adls`, stored at the -first boot like the [operational policy](operational-policy.md) -definitions, with its digest in `deploy/definitions/published.sha256`), and -you read it with `GET /definition/template/adl2/openEHR-EHR-ITEM_TREE.access_log_details.v1.0.0`. -The node ids are two-digit id-codes, so their byte order is their numeric -order, which is the order the elements of a tree are kept in. No openEHR -specification governs the details: they are FerroEHR's own. - -| Node id | Name | Value | Holds | -|---|---|---|---| -| `id11` | event action | `DV_TEXT` | the DICOM `EventActionCode`: `C`, `R`, `U`, `D` or `E` | -| `id12` | resource class | `DV_TEXT` | the class of resource the access addressed | -| `id13` | outcome indicator | `DV_COUNT` | the DICOM `EventOutcomeIndicator`: `0`, `4` or `8` | -| `id14` | principal | `DV_TEXT` | the login the access was made under | -| `id15` | issuer | `DV_TEXT` | the issuer of the caller's token | -| `id16` | client id | `DV_TEXT` | the client the token was issued to | -| `id17` | token id | `DV_TEXT` | the token's `jti` | -| `id19` | role | `DV_TEXT` | a role the caller held, one element each | -| `id20` | domain | `DV_TEXT` | the pseudonymisation domain, when it is not the resource class's own | -| `id21` | ehr id | `DV_TEXT` | the EHR the request named | -| `id22` | subject | `DV_IDENTIFIER` | the subject of care of the EHR, as `EHR_STATUS.subject` names it, with its namespace as the issuer | -| `id23` | subject lookup failed | `DV_BOOLEAN` | set when the subject could not be looked up | -| `id24` | object id | `DV_TEXT` | the object the request named; none for a read of the log, whose search the entry names by digest | -| `id25` | purpose | `DV_TEXT` | the purpose of use the caller declared | -| `id26` | legal basis | `DV_TEXT` | the legal basis the deployment attributes | -| `id27` | result count | `DV_COUNT` | how many records the access served | -| `id28` | origin | `DV_TEXT` | an origin of the data, one element each | -| `id29` | origin count | `DV_COUNT` | how many distinct origins the data had | -| `id30` | category map digest | `DV_TEXT` | the category map the access was classified through | -| `id31` | category content | `DV_PARSABLE` (`application/json`) | what the classification read | -| `id32` | acting mode | `DV_TEXT` | how the credential acted | -| `id33` | assurance level | `DV_TEXT` | the assurance level of the authentication | -| `id34` | assurance value | `DV_TEXT` | the claim value the level was read from | -| `id35` | professional id | `DV_TEXT` | the identifier of the natural person who accessed | -| `id36` | token attributes | `DV_PARSABLE` (`application/json`) | the purposes and roles the token stated | -| `id37` | binding | `DV_PARSABLE` (`application/json`) | the party binding with every field | -| `id38` | summary | `DV_PARSABLE` (`application/json`) | the count and EHRs of a summary of refusals | -| `id39` | event type | `DV_TEXT` | the DICOM `EventTypeCode` of an authentication record: `110122` Login, `110123` Logout | -| `id40` | review | `DV_CODED_TEXT` (`HL7_Confidentiality`) | the level, `R` or `V`, of the record a care relationship was written to, when the write is recorded for review | - -The subject of care is kept so the BALP `entity:patient` and the -`patient` search parameter name the patient as they did when the access -was recorded, whatever happens to the EHR after. An entry imported from -another system ([Seals, checkpoints and the transfer of a log](#seals-checkpoints-and-the-transfer-of-a-log)) -keeps that system's details, and FerroEHR projects none of it. - -To read the trail with SQL, `audit.access_trail` holds every record of -either form with the facts it states, in the audit vocabulary -(`operation`, `principal`, `binding`, `party` and the rest), an entry's read -from its content. `audit.access_detail(content::jsonb, 'id32')` reads one -access detail of an entry. The categories a classification computes are no -column there: the projection writes them. - -### The projections and their losses - -Each projection reads one stored entry and writes one target record. -"Loss" means the target has no place for the value; the entry keeps it. The -FHIR R4 `AuditEvent` follows IHE BALP 1.1.4; an access the category map did -not classify is a BALP exchange without the EHDS entities. Each row is a test -(`access_log::projection` in the source). - -**To the FHIR R4 `AuditEvent` (IHE BALP 1.1.4).** - -| Entry | `AuditEvent` | Loss | -|---|---|---| -| `action` | `action` (`C`, `R`, `U`, `D`, `E`), `type` `rest` and the FHIR interaction as the first `subtype`; an export or import is `type` Export or Import | the openEHR action has no code system of its own: `export` and `import` fold into `R` and `C` | -| `operation` | a `subtype` in `urn:openehr:its-rest:operation` | none | -| `time_recorded` | `recorded` | `occurred`: no `period` is written | -| `outcome.result` | `outcome`: `0` granted, `4` refused or a minor failure, `8` a serious failure | refused and a minor failure share `4`; `outcomeDesc` states the outcome in words and no reason code | -| `outcome.delivered` | the `delivered` detail of the `ehds-categories` entity | none, as a detail | -| `accessor.party` | the `ihe-otherId` typed `PRN` of `agent:user` (BALP 1.1.4 §3:5.7.5.4) | none | -| `accessor.credential` | `agent:user` `who.identifier` (issuer as `system`, subject as `value`), the token id as its first `policy`, the client as an agent of its own, the assurance as `ihe-assuranceLevel` | the authentication method has no element | -| `accessor.provider` | an agent naming the provider of the caller's party binding | none | -| `accessor.roles`, `accessor.kind` | `agent:user` `role`, the acting mode first | none | -| `accessor.groups`, `accessor.binding`, `accessor.delegation` | details of the `ehds-accessor` entity, one `actor` per actor in the chain's order | no element; details | -| `ehr_id` | the `ehr` entity, with the subject of care as the patient entity (`entity:patient`, role `1`) | none | -| `items` | `entity:data` (type `2`, role `4`) naming the version in `urn:openehr:object-id`; the categories and the template and archetype ids as details of `ehds-categories` | the RM type and the paths have no element | -| `items.origins` | one `origin` entity each | no element; entities | -| `query` | `entity:query` (role `24`), a stored query by its name | the text digest is not written | -| `purposes` | `purposeOfEvent` and `agent:user` `purposeOfUse` | none | -| `authorisations` | a permit as a `policy` of `agent:user` after the token id; an agreement in the `ehds-relayed` entity; a representation in `ehds-accessor` | legal grounds have no element; details | -| the `emergency` authorisation with a `reason` | the `ehds-emergency-access` entity naming the declared purpose that invoked it | the mark becomes an entity | -| an authorisation's `reason` | the `text` of `purposeOfEvent` and of `agent:user` `purposeOfUse` | none | -| `channel.request_id`, `channel.client_address` | the `X-Request-Id` entity; the client agent's `network.address` | none | -| `system_id` | `source.observer.identifier`; `source.site` from `[audit] enterprise_site_id` | none | -| `security_labels` | the `securityLabel` of the entity they label | no `meta.security` is written | -| `retention` | details of `ehds-categories` | no element; details | -| checkpoints | nothing | the seals do not travel; verify them on the openEHR side | -| `other_details` | the values it holds, where the rows above put them | the tree itself is not written | - -**To the DICOM PS3.15 A.5 audit message (the syslog sink).** - -| Entry | DICOM element | Loss | -|---|---|---| -| `action` | `EventActionCode`; `EventID` Patient Record (110110), Query (110112), Export (110106), Import (110107) | as in R4 | -| `operation` | `EventTypeCode` in `openEHR-ITS-REST` | none | -| `time_recorded` | `EventDateTime` | `occurred` | -| `outcome` | `EventOutcomeIndicator`, `EventOutcomeDescription` | the reason's code | -| `accessor.credential` | the requestor's `UserID` (the subject, or the professional a client acts for) | the issuer, the token id, the assurance | -| `accessor.roles` | `RoleIDCode` in the `codeSystemName` of `[audit] role_code_system`, by default the deployment's `[api] system_id`; the role of the care relationship the access rested on in its HL7 code system | none | -| `accessor.party`, `binding`, `groups`, `delegation` | details of the `ehds-accessor` participant object | no element; details | -| `accessor.provider` | nothing | lost | -| `system_id` | `AuditSourceID`, with `AuditEnterpriseSiteID` from the deployment | none | -| `channel.client_address` | `NetworkAccessPointID`, type `2` | none | -| `ehr_id` | the patient participant (type `1`, role `1`) names the subject of care | the `ehr_id` itself is not written | -| `items` | a System Object (type `2`, ID type URI) naming the version | the categories, origins, template and archetype | -| `query` | the query object of the Query event | the text digest | -| `purposes`, `authorisations` | nothing in the A.5.1 schema | lost | -| `retention`, `security_labels`, `other_details` | nothing | lost | - -**To the EHDS access record (`ehds-logging` `AccessRecord`).** - -| `AccessRecord` | Entry | Loss | -|---|---|---| -| `action` | `action` | export and import fold into `Read` and `Create` | -| `recorded` | `time_recorded` | none | -| `outcome`, `outcome_description` | `outcome.result` and the outcome indicator | a refusal shares `MinorFailure` with a minor failure | -| `accessor` (issuer, subject, client, token id, acting, roles, assurance, provider, party, groups, binding, actors, represents, relayed, purposes, policies) | `accessor`, `purposes`, `authorisations` and the access details | none | -| `subject.ehrs` | `ehr_id`, with the subject of care found | one record per entry; the entries of a request share its request id | -| `categories` | `items.categories`, computed again through the category map that classified the access | none | -| `delivered`, `origins`, `origin_count` | `outcome.delivered`, `items.origins`, the origin count | none | -| `request` (id, operation, resource, stored query, client address, correlation) | `channel`, `operation`, `items`, `query` | the query text is never carried | -| `retention`, `labels`, `emergency` | `retention`, the categories and origins, the `emergency` authorisation with a `reason` | none | - ## Reads are logged too, per record A write leaves its own trail in openEHR's contribution and audit chain. A read @@ -355,8 +123,8 @@ Each record additionally carries: |---|---| | `domain` | The pseudonymisation domain read: `ehr`, `demographic`, `linkage` for a crossing that resolves a party or a subject to its EHRs, or `system` for an operation that touches no domain. | | `purpose` | The purpose of use the caller declared in the `x-purpose-of-use` header, when the deployment accepts it. | -| `token_attributes` | The purposes of use and the professional roles the access token states, each with its code system, for an issuer with an `[auth.issuer..attributes]` table ([where the purpose comes from](#where-the-purpose-of-use-comes-from)). | -| `justification` | `{"kind": "justification" \| "emergency", "reason": …}` when the access rested on a justification of the access policy, with the reason the clinician stated; `NULL` otherwise ([justified and emergency access](#justified-and-emergency-access)). | +| `token_attributes` | The purposes of use and the professional roles the access token states, each with its code system, for an issuer with an `[auth.issuer..attributes]` table ([where the purpose comes from](ehds-logging.md#where-the-purpose-of-use-comes-from)). | +| `justification` | `{"kind": "justification" \| "emergency", "reason": …}` when the access rested on a justification of the access policy, with the reason the clinician stated; `NULL` otherwise ([justified and emergency access](ehds-logging.md#justified-and-emergency-access)). | | `legal_basis` | The basis the deployment processes under, from `[audit] legal_basis`. | | `result_count` | How many records the operation served. | | `request_id` | The `x-request-id` correlation id the response carried. | @@ -386,16 +154,16 @@ lives in the record: | NEN 7513 asks for | FerroEHR records it as | |---|---| -| The identity of the person who accessed the record | `principal` — the authenticated Basic username or OAuth `sub`; an unattributable denial is recorded as unattributed, never under a fabricated identity. With `[authz.professional]` configured, `professional_id` names the natural person when the token names a client application | -| The identity of the patient whose record was accessed | `patient_id` — the resolved EHR subject, which under the pseudonymisation boundary is an opaque pseudonym | +| The identity of the person who accessed the record | `principal`: the authenticated Basic username or OAuth `sub`; an unattributable denial is recorded as unattributed, never under a fabricated identity. When a client acts for a person, `professional_id` names that natural person | +| The identity of the patient whose record was accessed | `patient_id`: the resolved EHR subject, which under the pseudonymisation boundary is an opaque pseudonym | | Which record, or which part of it | `resource_class` + `resource_id`: the version uid, party uid or EHR id the operation touched | | The date and time | `recorded_at`, the event time; `stored_at` is when the row was persisted | | The kind of action | `action` (DICOM `C`/`R`/`U`/`D`/`E`) plus `operation`, the released ITS-REST operation id. It equals the served OpenAPI `operationId` except for the demographic CONTRIBUTION pair, served as `demographic_contribution_create` and `demographic_contribution_get` because the released `contribution_create` and `contribution_get` also name the EHR operations and one document needs unique ids | | Whether it succeeded | `outcome`, the DICOM outcome indicator (0 success, 4 minor, 8 serious, 12 major) | -| Under which role or authority | `roles` — the roles the caller held at access time (the RFC 9068 §2.2.3.1 claim carriers for a bearer, the user definition for Basic), rendered as FHIR `agent.role` on the requestor and as a `RoleIDCode` per role on the DICOM requesting participant | +| Under which role or authority | `roles`: the roles the caller held at access time (the RFC 9068 §2.2.3.1 claim carriers for a bearer, the user definition for Basic), rendered as FHIR `agent.role` on the requestor and as a `RoleIDCode` per role on the DICOM requesting participant | | On whose authority, and why | `purpose` and `legal_basis`, and `permit`, the identifier of the data permit a secondary-use caller declares it acts under ([Secondary use](compliance/secondary-use.md#the-access-record)) | | Which system, and from where | `AuditSourceID` and the source participant's network address (`client_ip`): the connection's peer, or the client a peer in `[server] trusted_proxies` names in its `forwarded_header` ([Server](installation/config-server.md)) | -| Who the person is in the demographic store, and for whom they act | `binding` and the fields beside it ([the binding outcome](#the-binding-outcome)): `party` (the bound `PERSON`), `party_groups`, `provider`, `representation` for a representative, and `acting_mode` (`person`, `delegated`, `external` or `system`); for a verified external accessor `external_fields` and `agreement` stand in for the party, and an `organisation` record names the organisation. The FHIR `AuditEvent`, the DICOM message and the syslog feed carry each in the `ehds-accessor` and `ehds-relayed` entities ([the binding fields in the renderings](#the-binding-fields-in-the-renderings)) | +| Who the person is in the demographic store, and for whom they act | `binding` and the fields beside it ([the binding outcome](ehds-logging.md#the-binding-outcome)): `party` (the bound `PERSON`), `party_groups`, `provider`, `representation` for a representative, and `acting_mode` (`person`, `delegated`, `external` or `system`); for a verified external accessor `external_fields` and `agreement` stand in for the party, and an `organisation` record names the organisation. The FHIR `AuditEvent`, the DICOM message and the syslog feed carry each in the `ehds-accessor` and `ehds-relayed` entities ([the binding fields in the renderings](ehds-logging.md#the-binding-fields-in-the-renderings)) | Two of these are the deployment's to supply. `purpose` is only as meaningful as the vocabulary you agree with your callers: set `[audit] purpose_codes` to that @@ -407,618 +175,6 @@ Mapping the recorded fields onto your own retention schedule and review process stays yours: the software records the events and serves them back, and no supplier document discharges the obligation to review them. -## The EHDS logging elements, mapped - -Annex II 3.2 of [Regulation (EU) 2025/327](https://eur-lex.europa.eu/eli/reg/2025/327/oj) -lists five things the European logging software component must record "on every -access event or group of events". This is where each one lands, or does not. -The elements were read from the published text on 2026-09-10; the regulation is -the authority and the wording below is a paraphrase. - -| Annex II 3.2 | Access-event field | DICOM PS3.15 | FHIR `AuditEvent` | State | -|---|---|---|---|---| -| (a) the healthcare provider or other individuals having accessed | `provider` of the binding (the provider of the caller's party binding, read from the CDR), or the `organisation` record of a verified external organisation | — (no such attribute) | the `acts-for` detail of the `ehds-accessor` entity | Recorded | -| (b) the specific natural person or persons having accessed | `principal` (+ `token_id`, `client_ip`), and `professional_id` + `acting_mode` for a caller its issuer classifies as a person or a delegate | `ActiveParticipant/@UserID` (the professional; a client application acting for one is a second, non-requesting participant; the token subject is `@AlternativeUserID` when it differs) | the `agent:user` slice, `who` the token's issuer and subject, the professional's identifier as its `ihe-otherId`, and the client application as an agent of its own (BALP 1.1.4 §3:5.7.5.4) | Recorded | -| (c) the categories of data accessed | `categories` + `category_basis` + `category_evidence` + `category_map_digest`, classified by `ehds-logging` through the audit category register (beside `resource_class`, `domain` and `result_count`) | none (no such element) | the `entity` named `ehds-categories`, with one `ehds-category` detail per category and its basis, each id the classification read and the map digest; each category is also a `meta.security` label | Recorded | -| (d) the time and date of access | `recorded_at` | `EventIdentification/@EventDateTime` | `recorded` | Recorded | -| (e) the origin or origins of data | `origins` + `origin_count` (the `FEEDER_AUDIT` originating systems of the served version bodies, or the server that created them, derived at commit onto `version.origins`) | — (no such element) | one `entity` named `origin` per origin, its `system-id` detail the originating system | Recorded | - -Read (a) beside (b): they are both about the accessing side, and the pair -distinguishes the **organisation** on whose behalf the access happened from the -**natural person** who made it. The principal answers (b); the provider of the -caller's party binding answers (a). It is read from the CDR, never from a token -claim, so the provider a record names is the one the deployment bound the -caller to. A caller with no binding, such as a Basic user with no `PERSON`, -leaves it empty rather than guessed. - -Element (b) asks for a **natural person**, and a bearer token can name a client -application instead. Each issuer's [`kind` and profile](security.md#assurance-level-and-the-natural-person-on-patient-data) -classify the caller, so every record says which it was and who stood behind it: - -| Field | Meaning | DICOM PS3.15 | FHIR `AuditEvent` | -|---|---|---|---| -| `acting_mode` | `person` when the token names a natural person, `client` when it names a client application | the participant split below | the agent split below | -| `professional_id` | the natural person: the person's own claim, or the professional a client token acts for | `ActiveParticipant/@UserID` of the requesting participant | the `ihe-otherId` extension of the `agent:user`, typed `NPI` | -| `principal` | the token subject, as before: the client application in `client` mode | a second `ActiveParticipant` with `UserIsRequestor="false"` and the network address; `@AlternativeUserID` in `person` mode when it differs from the professional | `agent:user` `who.identifier`, with the issuer as its system; the acting mode is its first `role` | -| `assurance_level` | the eIDAS level (`low`, `substantial`, `high`) the token's assurance claim maps to under `[authz.assurance]` | none (no such attribute) | the `ihe-assuranceLevel` extension of the `agent:user` | -| `assurance_value` | the raw claim value the level was read from, usually `acr` | none | none | - -[PS3.15 §A.5](https://dicom.nema.org/medical/dicom/current/output/chtml/part15/sect_A.5.html) -gives `ActiveParticipant` no assurance attribute, so the DICOM message and the -syslog feed carry no level. The FHIR export carries the level as the BALP -`ihe-assuranceLevel` extension (BALP 1.1.4 §3:5.7.5.4) and never the raw claim -value, which lives in the local store's column only. The tamper-evidence digest covers both columns, like every other column of -the record (see [Tamper evidence](#tamper-evidence) for records written before -the digest was versioned). - -For a system caller the mode and the professional stay empty and (b) is -answered by `principal`, which names the client application. Without `[authz.assurance] levels` the level stays empty; -the raw value is still recorded when the token carries the claim. A Basic -credential records none of the four. - -Element (c) asks for the **priority category** of the data, in the sense of -Art. 14(1): patient summaries, electronic prescriptions, electronic -dispensations, medical imaging, medical test results and discharge reports, -plus any category a Member State adds in national law. AQL selects archetypes -and templates, never categories, and no openEHR specification maps the one -onto the other, so the deployment declares the mapping in -[the audit category register](installation/config-audit.md#the-audit-category-register), an -[admin register](operational-policy.md#the-admin-registers): a -template id, or failing that the root archetype id, maps to a set of categories -(a priority category by its code in HL7 Europe's -`EEHRxFDocumentPriorityCategoryCS`, such as `Patient-Summaries` or -`Laboratory-Reports`, a national category as its `|`), or to -`none` for content that holds no data of any category. While you declare no -template and no archetype, the map FerroEHR ships applies: the published CKM -templates and COMPOSITION archetypes whose data sit in one priority category -([the shipped map](installation/config-audit.md#the-audit-category-register)). Your own -map replaces it, and `ehds-logging` classifies each access through the map in -force. - -Each record is classified when the access happens, from what it served or -wrote, and never at commit, because the map is your reading of your templates -and can change: - -- a composition read or write is classified by the version's template id, then - by its root archetype id; -- an AQL execution is classified by the template and root archetype ids of the - versions its result page came from; where the answer carries no version (a - `DISTINCT` or aggregate projection, or zero rows) by the query's positive - archetype and template constraints, so an operand under `NOT CONTAINS` or a - predicate under `NOT` never counts. Every id the query constrains to must be - mapped, and every content operand bound to an id, or the record is - `unclassified` beside what did map. Each per-EHR record of a query carries - the categories that EHR disclosed; -- a logical delete writes no content, so it is classified by the version it - deleted; a `VERSIONED_COMPOSITION` read by the composition it holds; -- a `CONTRIBUTION` read, with or without `Prefer: resolve_refs`, is classified - by the versions the contribution committed, a deleted version again by the - version it deleted; -- an EHR Extract export is classified by every version it carried, and an - Extract import by the newest content of every versioned object it landed; -- `EHR`, `EHR_STATUS`, `EHR_ACCESS`, the directory, item tags and revision - histories are recorded as `none`, by resource kind. - -An access the map cannot classify is recorded `unclassified`, with the -template and archetype ids as evidence, and is never refused; the FHIR record -says why (`unmapped`, `unbound`, `named-nothing`). A stored category is its -`|` token. `category_basis` says what the classification was read -from (`returned`, `written`, `queried` or `resource-kind`; records written -before 5.3.2 carry `template`, `archetype` or `query` and the earlier -spellings), and `category_map_digest` names the map that produced it, so a -later map never rereads an old record. The map's -digest is also on the boot line and on `GET /management/info` under -`audit.category_map`. The classification stays in the access log: it is never -written to the request log, a span or a metric label. The DICOM rendering has -no element for it (PS3.15 §A.5), so it travels in the local store and the FHIR -export only. - -Records in the demographic domain carry no classification, because no -priority category lives there. - -Element (e) asks where the DATA came from, which is not where the request came -from. openEHR models that provenance as `FEEDER_AUDIT` on the content itself, -so every committed version records the distinct set of -`FEEDER_AUDIT.originating_system_audit.system_id` values found in its body, or -this server's own system id when it carries none. A composition, status or -folder read then records the origins of the version it served, and an AQL -execution the union over the version rows its result page came from. The record -carries the true distinct count beside a set capped at 32, so a page drawing on -more origins than that says how many rather than looking complete. A version -committed before the column existed is assessed when it is read. - -One further element, adjacent to the five: **the declared purpose of use -reaches one export of the two**, and only one of them could carry it. It is -stored on the record, served by ITI-81, and rendered as -[`agent.purposeOfUse`](https://hl7.org/fhir/R4/auditevent.html) on the -requesting person's agent in the FHIR export. A declared code carries no -system: the vocabulary is the one you agree with your callers in `[audit] -purpose_codes`, which has no published code system URI, and attributing the -code to a system it does not come from would misdescribe it. A purpose the -access token states keeps the system the token gives it. -The -[DICOM Audit Message schema](https://dicom.nema.org/medical/dicom/current/output/chtml/part15/sect_A.5.html) -of PS3.15 §A.5 defines no purpose element at all — `EventIdentification`, -`ActiveParticipant`, `AuditSourceIdentification` and -`ParticipantObjectIdentification`, and none of them carries one — so on that -side it is a limit of the format, not something this code withholds. - -### Where the purpose of use comes from - -The purpose of use reaches the record from two places: - -- **The access token.** An issuer with an `[auth.issuer..attributes]` table - (`mapping = "iua"`) states its professionals' attributes in the token: the - IHE IUA `purpose_of_use` and `subject_role` claims under - `extensions.ihe_iua` (IHE ITI TF-2 §3.71.4.2.2.1.1), and with - `authorization_details_purposes` the `purpose_of_use` of each RFC 9396 - `authorization_details` entry. The record stores them in - `token_attributes`, and both renderings write them with their code systems: - the purposes at the requesting agent's `purposeOfUse`, the roles at its - `role`, beside the roles the caller held. -- **The `[audit] purpose_header`** (`x-purpose-of-use`), which the caller - sets. It works alone for an issuer without an `[auth.issuer..attributes]` table, - as before. - -The token is the authorization server's statement, so it decides. A request -whose header names a purpose the token, which states purposes, does not -state is refused with `403`, and the refusal is recorded as a failed -authentication naming the caller and the token's purposes. A header naming -one of the token's purposes is admitted and recorded with both. Which source -wins is FerroEHR's own design; no openEHR specification governs the purpose -of use. - -> [!NOTE] -> Every row of this table is asserted by a test -> (`app/ferroehr/tests/it/audit_ehds_mapping.rs`), **including the gaps**: the -> tests that record an absence fail the day the field arrives, so the table and -> the code cannot drift apart in either direction. - -The common specifications the regulation's Article 36 provides for have not -been adopted. When they are, this mapping is re-verified against them rather -than assumed to still hold; see the -[EHDS readiness page](https://ferrohealth.eu/docs/ehds/readiness.html). - -### The binding outcome - -Every record of an authenticated request carries `binding`: how the caller -was bound to a demographic party, or why the binding refused it. The -committer the same request writes into a version is on -[Who is the committer](security/committer.md). It answers -Annex II 3.2(a) and (b) where the token's subject alone does not. The columns -beside it hold what each outcome needs: - -| `binding` | The caller | Recorded beside it | -|---|---|---| -| `bound` | a person bound to a `complete` `PERSON` | `party`, `party_groups`, `provider`, `representation` for a representative, `actor_chain` for a delegated token | -| `provisional` | a person bound to an `incomplete` `PERSON` | `party`, `party_groups`, `provider` | -| `external` | a verified external person of a `federation` issuer | `external_fields`, `agreement`, `provider` | -| `organisation` | an organisation under an agreement with `accessor = "organisation"` | `external_fields`, `agreement` (with its legal ground and access class, and for a `chained` request `correlation_id` and `correlation_source`), `provider` | -| `system` | a client acting for nobody | `party`, the client's `ACTOR` in the policy parties; `provider`, the identifier of the `ORGANISATION` its acts-for relationship targets; `facilities` of the compositions it committed | -| `self` | the record's person, whose login the party binding binds to the `PERSON` an EHR's subject names | the principal; `party`, that `PERSON` | -| `refused-*` | a refusal of the binding or of a caller kind: `unbound`, `ambiguous`, `inactive`, `abandoned`, `deprovisioned`, `wrong-marker`, `representation-unrecorded`, `key-claim-missing`, `groups-unavailable`, `external-incomplete`, `trc-patient-mismatch`, `trc-missing`; and of a caller kind, `system-personal-scope` (a system caller holding a `user/` or `patient/` scope), `no-agreement` (no federation agreement admits the accessor) and `scope-beyond-agreement` (an external caller holding a scope its agreement does not read) and `correlation-missing` (a `chained` organisation request without an attested correlation id) | `party` for a party refused for its state or marker, `binding_detail` for what else the refusal names (`represented`, the subject a representative asserted; `claim`, the name of the key claim a token lacked, never its value) | - -`acting_mode` is `person`, `delegated` for a person through a declared client -or actor, `external` for a verified external accessor and `system` for a client -acting for nobody (`client` remains on records written before). The FHIR -`AuditEvent` writes each mode as the person's `agent.role`. A record of a -request with no authenticated caller carries no binding. The columns are in the -chain digest: version 2 hashes them, version 3 adds `token_attributes`, a new -record is version 3, and a record written before keeps verifying under its own -version. - -#### The binding fields in the renderings - -Neither BALP 1.1.4 §3:5.7.5.4 nor DICOM PS3.15 §A.5 has an element for the -binding fields beyond the bound person, so `ehds-logging` writes them as -details of two entities it adds, and FerroEHR hands it every field. The FHIR -`AuditEvent` carries each entity as an `entity` with its `name` and one -`detail` per value. The DICOM message carries each as a -`ParticipantObjectIdentification` of type `4` (Other) with the entity name as -its `ParticipantObjectName` and one `ParticipantObjectDetail` per value -(RESTful ATNA Rev. 3.6 Table 3.20.4.2.2.1-1), and the ITI-20 syslog feed -sends that message. Both renderings take the detail list from -`ehds-logging`, so they never disagree. - -| Recorded field | Rendered as | -|---|---| -| `binding` | `ehds-accessor`: `binding`, with `security-event` for `refused-trc-patient-mismatch` and `refused-trc-missing` | -| `party` | `ehds-accessor`: `party` as `\|\|`; in the FHIR `AuditEvent` also the person's `otherId` typed `PRN` | -| `party_groups` | `ehds-accessor`: one `group` per group, in the party's namespace with type `GROUP` | -| `provider` | `ehds-accessor`: `acts-for` as `\|` | -| `facilities` | `ehds-accessor`: one `facility` per facility, as `\|` | -| `representation` | `ehds-accessor`: `represents`, `represents-ground` and `represents-relationship`; a refusal's `represented` as `represents` alone | -| `actor_chain` | `ehds-accessor`: one `actor` per actor, `\|`, outermost first | -| `binding_detail` | `ehds-accessor`: `binding-claim` for `refused-key-claim-missing` | -| `external_fields` | `ehds-relayed`, marked `asserted` and naming the issuer by `relayed-issuer`: each 2026/2099 Annex field and eHDSI SAML attribute at its own detail (`hp-family-name`, `hp-identifier`, `provider-identifier` and the others), `consent.reference` as `agreement-consent`, and every other field as `asserted-field` `=` | -| `agreement` | `ehds-relayed`: `agreement-name`, `agreement-version`, `agreement-legal-ground` and `agreement-access-class` | -| `correlation_id`, `correlation_source` | the FHIR `AuditEvent`: `correlation-id` and `correlation-source` of the request id's entity; the DICOM message: the same two details of `ehds-relayed`, since it carries no request entity | -| `acting_mode` | the FHIR `AuditEvent`: the person's `agent.role`; DICOM: none | - -Every value goes through the renderers' escape: a control character, a -bidirectional control or a line separator is written as its code point, and -no value is cut. A DICOM detail value is base64-encoded as given (PS3.15 -§A.5.1.1). A binding record that lacks a field its code needs fails the -rendering, and the sender reports the failure, never a record without the -binding. - -### Refusal records and their budgets - -Every refused request is recorded as a failed user authentication, through the -same path as an operation record: a refusal whose record cannot be written is -answered `503`. A refusal of -the login binding or of a caller kind carries its `refused-*` code. Refusals -are charged to one of two budgets, which never draw on each other, so a flood -of invalid tokens cannot hide a verified caller's probing: - -| Budget | Charged to | Per caller in a window | Per window | -|---|---|---|---| -| Failed verification | the source network: the `/24` of an IPv4 address, the `/64` of an IPv6 one | 10 | 1000 | -| Verified caller | the token's `iss` and `sub` | 10 | 1000 | - -A window lasts 60 seconds. Past a caller's 10 records the rest of its -refusals in that window become one summary record, written when the window -closes: it names the caller and carries `summary`, the count and the EHR ids -the refused requests named (at most 64, while the count stays exact). Past a -budget's 1000 records, the refusals of every caller not yet recorded in that -window become one summary record per issuer and outcome, naming no caller. A -security event (`refused-trc-patient-mismatch`, `refused-trc-missing`) is -recorded once for every answered request and never summarised. A federation -caller above its agreement's `caller_rate`, a contact point's included, is -answered `429` before any patient lookup, and every such refusal goes into -that caller's summary record from the first, with `binding_detail` naming -`caller-rate`, so the count of security events stays bounded. A refusal -record the system log cannot take is counted in -`atna_audit_refusals_unwritten` and logged at `error`. - -> [!NOTE] -> The limits, the windows and the budgets are kept **per replica**. Behind a -> load balancer with three replicas, one caller can have up to 30 refusals -> recorded one by one in a window before the summaries begin, and each replica -> writes its own summary records. - -### Access through FerroBRIDGE's FHIR facade - -The openEHR REST API carries no end-user identity on a read, so when -FerroBRIDGE's FHIR facade reads or writes through FerroEHR, FerroEHR's record -names the bridge's credential under (b) and cannot name the natural person -behind the FHIR request. From FerroBRIDGE 0.0.16 the bridge records each -facade access itself when its `[audit]` section is on: it writes the Annex II -3.2 record with the person, the categories, the time and the origin through -the same `ehds-logging` crate, and sends it as an IHE BALP `AuditEvent` -through `ihe-atna` over the ITI-20 FHIR feed to the Audit Record Repository -you configure there. The bridge refuses a facade access whose record it -cannot take. Read the two records together: FerroEHR's says which data left -the CDR and to which client, and FerroBRIDGE's says which person asked for -it. FerroBRIDGE's -[access record](https://ferrobridge.eu/docs/operate/access-record.html) page -describes its record and its configuration. - -### Justified and emergency access - -A clinician opens a record outside their care relationships on a -[justification](security.md#justified-access-outside-the-care-relationships) -of your access policy, with a reason in `x-access-reason`; an emergency is a -justification that also lifts what EHDS Art. 11(5) lets an emergency lift. -Art. 11(5) requires such cases to be "logged in a clear and understandable -format" and "easily accessible for the data subject", and Art. 9(1) and -Annex II 3.2 count every access among the ones the person is told about. -FerroEHR records what the access decision rested on, never what the request -merely declared: - -- **The stored record:** the `justification` column holds the kind - (`justification` or `emergency`) and the reason as the clinician wrote it. - It is `NULL` for an access that rested on a care relationship or anything - else, and for a refused justified access, which names its refusal - instead; an emergency is recorded even when the access was refused. -- **The access-log entry:** the `justification` or `emergency` authorisation - under `ACCESS_POLICY` and its version, with the `reason`. -- **The FHIR `AuditEvent`:** the reason is the `text` of the - `CodeableConcept` beside the declared code on `purposeOfEvent` and on the - requestor's `agent.purposeOfUse` (FHIR R4 `AuditEvent`, IHE BALP). An - emergency also carries the `entity` named `ehds-emergency-access` that - `ehds-logging` writes, whose `description` states the mark in plain words - ("Emergency access: the accessor declared that the access was necessary - to protect the vital interests of the data subject (Regulation (EU) - 2025/327 Art 11(5)).") and whose `ehds-emergency-purpose` detail names the - purpose that invoked it. An app keys on the entity and shows its - description, and shows the reason for every justified access. -- **The DICOM syslog feed:** neither the reason nor the mark; the message - FerroEHR writes there carries no purpose of use. - -```mermaid -sequenceDiagram - participant C as Clinician - participant F as FerroEHR - participant S as Audit store - participant P as Patient (ITI-81) - C->>F: read, purpose ETREAT, reason "Unresponsive on arrival" - F->>F: emergency justification invoked, restriction lifted - F->>S: access record, justification {emergency, reason} - F-->>C: 200 - P->>F: GET AuditEvent?patient=... - F->>S: subject-scoped search - F-->>P: purposeOfEvent ETREAT with the reason, ehds-emergency-access entity -``` - -The person reads their own log, every justified access included, through the -[subject-scoped ITI-81 retrieval](#retrieving-audit-records-iti-81), and the -access-log resource filters on `justification=justification` or -`justification=emergency`. - -A justification lifts no restriction of the patient. A composition or EHR -restricted under GDPR Art. 18 stays refused with any justification, an -emergency included, because Art. 18(2) admits processing only with consent, -for legal claims, for the rights of another person or for an important -public interest, and the person's own vital interests are not on that list. -An EHDS Art. 8 restriction of access by health professionals yields only to -an emergency justification, where the directive's `emergency_override` -holds -([restriction of access](security.md#restriction-of-access-by-health-professionals-ehds-art-8)). - -### Retention, and who chooses it - -The controller decides how long the log keeps a record, in its access policy -(`ACCESS_POLICY.log_retention`, written through -[`/admin/access_policy`](operational-policy.md)). FerroEHR provides the -mechanism and names no national law of its own. `log_retention` holds: - -- `in_union`: whether Regulation (EU) 2025/327 binds the controller. When it - does, Art. 9(2) keeps the access information "available for at least three - years from each date of access to the data", and FerroEHR refuses a shorter - period. -- `period`: how long each record is kept from the date of access, in whole - years (`P5Y`) or whole days (`P1826D`). Absent keeps every record without - end. -- `floors` and `ceilings`: the minimum and maximum periods the controller's - law sets, each with the provision that sets it, coded in the terminology the - jurisdiction names (an `ACCESS_RETENTION_BOUND`). - -A policy whose period breaks a floor or ceiling it declares is refused when it -is written, with `400`, and the version in force stays. So is a ceiling below -a floor, a ceiling with no period (a record kept without end outlasts every -ceiling), a controller outside the Union with no floor, and a period in any -unit other than years or days. Years are counted on the calendar: three years -admit `P1096D` as a floor but not as a ceiling, since 1 096 days can outlast -three calendar years. A new version applies to every record written after it, -on every replica, with no restart. - -**With no `log_retention`, every record is kept without end.** That meets -every floor, so the log never forgets evidence a data subject's right of access -is served from. It is also undecided: GDPR Art. 5(1)(e) makes the period the -controller's to set. The `log_retention` readiness indicator reads `degraded` -until the access policy states it, and the instance stays in rotation. `ferroehr -config check` reads only the configuration file, so it cannot see the policy; -check the indicator on `GET /management/health` after the first policy write. - -A stored policy version whose `log_retention` does not read (a damaged store; -the write check refuses one) is named and held loud. Each replica keeps the -last retention that read and records every access under it, so the access log -never stops, while the reaper purges nothing and the `log_retention` -indicator reads `down`, naming the version, until a version that reads is -committed. - -Every record stores the first date it may be deleted on, and the reaper -deletes each record hourly on or after that date and never before it. A -record outside the access log ends the day after its date of access plus the -period in force when it was written. - -**An openEHR access-log entry states its own retention.** Each -`ACCESS_LOG_ENTRY` carries an `ACCESS_RETENTION` when it is written: -`retain_until`, the last day it is kept; `grounds`, the provisions that set -the period; and `policy`, the version of the access policy it was taken from. -An entry kept without end states no `retain_until`. The grounds are Art. 9(2) -for a controller in the Union, coded by the regulation's European Legislation -Identifier with the subdivision as the code -(`http://data.europa.eu/eli/reg/2025/327/oj`, `art_9.par_2`), then each -declared floor and ceiling as the controller coded it. The ELI coding is our -own design (Council conclusions 2012/C 325/02 define the identifier). The -same hourly worker replaces every entry whose `retain_until` has passed by an -`ACCESS_LOG_TOMBSTONE` in place, in any order of expiry. The tombstone keeps the -entry's uid, `system_id` and `time_recorded`, names the grounds of the period -that ended, and holds nothing else of the entry; its row keeps the entry's -content digest, so its window's seal verifies after the content is gone -([Tamper evidence](#tamper-evidence)). A -tombstone is never replaced again, and the database refuses any other change -to it. An erasure a law orders before the period ends takes the same path -through `POST {ext}/admin/access-log/erase`, with the law's provisions as the -tombstone's grounds; the erasure is an access record of its own -(`access-log-erasure:`) naming the administrator -([Admin APIs](operations-admin-apis.md)). - -**A tombstone is kept as long again, then its window folds.** A tombstone -holds no EHR, no accessor and no purpose, but its content digest is a hash -of the entry it replaced, and a copy of that entry elsewhere (a forwarded -BALP `AuditEvent`, an export, a backup) can be matched against it. It is -kept only while its window needs it to verify (GDPR Art. 5(1)(e)): for one -more retention horizon, its entry's own, so a tombstone stays as long after -its removal as its entry was kept before it. Once every record of a sealed -window is a tombstone past its end, the same hourly run removes the -window's entries and records the window as folded -(`audit.access_log_seal_fold`), with every ground its tombstones named and -when it was folded. The window's seal stays, so the seals still follow one -another, and a record that leaves the log any other way is reported as -tampering. A window folds whole: an entry kept longer keeps its window's -tombstones until it has folded too. An erasure a law orders is a tombstone -like any other and folds the same way. Several replicas fold on a -PostgreSQL advisory lock, so no window is folded twice. The metrics are -`access_log_folded_total` and `access_log_gaps_total` -([Access path](operations-access-path.md)). No configuration key sets the -second horizon. No openEHR specification governs audit retention: our own -design. - -**An imported entry ends at its own `retain_until` too.** An entry imported -with an EHR from another system -([Seals, checkpoints and the transfer of a log](#seals-checkpoints-and-the-transfer-of-a-log)) -keeps the `retain_until` its recording system stated, and the same hourly -run replaces it by its tombstone once that day has passed, on the entry's -own grounds. Its tombstone is kept as long again, as a local one is, and -then folds, leaving its uid, its bundle and its content digest -(`audit.access_log_imported_folded`), so its bundle still verifies. The -metrics count both logs, with `chain` = `local` or `imported`. No openEHR -specification governs this: our own design (#5664, #6242). - -Choosing the period is a legal question for the controller. NEN 7513 is the -Dutch reference for this log and the Besluit vaststelling bewaartermijn -logging sets its five years; SGB V § 309 Abs. 1 caps the German -telematics-infrastructure log at three years; DSV Art. 4 Abs. 5 keeps a Swiss -log at least one year. A controller bound by one of them declares it as a -floor or ceiling with its provision. Art. 9 applies from 26 March 2029 for -patient summaries, prescriptions and dispensations and from 26 March 2031 for -the other priority categories (Art. 105). FerroEHR holds the Art. 9(2) floor -from this release on, so a log kept today already meets it when Art. 9 -applies. One instance serves one access policy, so two controllers needing -different periods run two instances. -The retention in force is the access policy's (`GET {ext}/admin/access_policy`). -A record takes about 1.2 KB on disk, so the period decides how far the log -grows ([Storage sizing](operations.md#audit-retention)). - -### The access log at steady state - -With entries written at a rate of `r` a day and kept for `P` days, the log -levels off once the first tombstones fold, after `2P`: - -- the entries of the last `P` days: `r × P × 3.9 kB` (2.5 kB of row and 1.4 - kB of indexes each, measured when each entry still had its link row); -- their tombstones, kept another `P` days: `r × P × 1.1 kB`; -- the seals: one row of about 0.3 kB a minute, and one folded-window row for - each window the fold removed, kept without end. - -These figures predate the storage of #5703, which keeps the part an -entry's caller shares once and compresses each row in place; the -performance gate's summary states the bytes per entry of the tree it -measures. The access-path record of #5590 measures 2 518 bytes of row and 3 887 bytes -stored per entry, 1 079 bytes per tombstone, and 2.08 entries per request at -20 requests a second, which is 3.59 million entries a day. With the EHDS -floor of three years (`P` = 1 096 days) that is about 14 GB of entries a day, -and the log levels off near 15.3 TB of entries and 4.2 TB of tombstones, -where before it grew by 3.9 GB of tombstones a day for as long as the -deployment ran. `VACUUM` reuses the space a fold frees for later rows -(PostgreSQL 18 docs, Routine Vacuuming, Recovering Disk Space). - -### Getting the log out - -Three routes, and they answer different questions. - -- **The access log over ITS-REST:** the [access-log - resources](#reading-the-access-log-over-its-rest) serve the openEHR - access-log entries: one EHR's log to the person it is about and their - representative, and the full log to a reviewer. This is the person's own - route (EHDS Art. 9(2)). -- **ITI-81 retrieval:** the [audit search](#retrieving-audit-records-iti-81) - serves the records back as FHIR `AuditEvent` resources, filtered by patient, - agent, date and outcome. This is the operator's route and the one an IHE - Audit Consumer uses: everything Annex II 3.2 records is reachable through - it, including the purpose and the organisation, which the syslog feed's - DICOM form cannot carry. -- **The BALP feed:** records fan out to syslog and to a FHIR feed as they are - written, for a SIEM or a central Audit Record Repository. - -## Reading the access log over ITS-REST - -The openEHR access-log entries are served under the extensions root, -`/ferroehr/rest/extensions/v1`. No openEHR ITS-REST release defines these -resources: they are part of FerroEHR's access-log proposal to openEHR, and they -follow the ITS-REST 1.1.0 conventions, `offset` and `fetch` paging as the Query -API's and ISO 8601 date-times. - -| Method and path | Who | What | -|---|---|---| -| `GET /ehr/{ehr_id}/access_log` | the subject of care, their representative, a reviewer | The entries of one EHR, newest first. Filters: `from`, `to`, `action`, `outcome`, `accessor_kind` (each a term by its coded content, the token `terminology_id\|code`, such as `HL7_AuditEventAction\|R`, `openehr_access\|refused` or `HL7_SecurityRoleType\|datasubject`; a rubric or a bare code is a `400`), `emergency`, `include_self`; `offset`, `fetch` (1 to 1000, default 100). | -| `GET /ehr/{ehr_id}/access_log/{uid}` | as above | One entry. | -| `GET /admin/access-log` | a reviewer | Records across EHRs, entries and tombstones. Filters: `ehr_id`, `party_namespace`, `party_type`, `party_id`, `issuer`, `subject`, `request_id`, `from`, `to`, `outcome`, `emergency`; `offset`, `fetch`. | -| `GET /admin/access-log/seals` | a reviewer | The seal of each window that covers an entry id from `from_id` to `to_id` (less than 10000 apart), with whether the window was folded, for verification. | -| `GET /admin/access-log/checkpoint` | a reviewer | The newest stored checkpoint, or the one at `sequence`. | - -A list answers `offset`, `fetch` and `entries`, and no total count, since a -count over a large log costs a scan. A parameter a resource does not take, or a -value outside its form, is a `400`. - -**The caller's authorisation selects the view, and no parameter widens it.** - -- The **subject view** goes to the person the EHR is about and to their - representative, bound through the party binding: the person reads the EHRs - whose subject is their `PERSON`, and a representative reads the EHR of the - subject the representation names - ([Operational policy](operational-policy.md)). It shows who accessed (the - provider and the party), when, the action and outcome, the items and their - categories, the purposes and the emergency mark, and leaves out the - credential, the delegation chain, the binding outcome, the channel, the - query text and its digest, the security labels and `other_details`, and the - accessor members a - [restriction](#restricting-the-subject-view-ehds-art-93) withholds. An entry about a composition held from the person under EHDS Art. - 3(3) is left out until the hold ends, as in the [subject-scoped ITI-81 - read](#while-a-composition-is-held-from-the-person). Any other EHR answers - `404`, the same as an unknown one, so its existence is not disclosed. -- The **full view**, each record in its ITS-JSON form, goes to - a reviewer: a caller the admin class admits (`admin_role` under RBAC), the - same caller `GET /admin/access-log` admits. -- Every other caller is refused with `403`. The log has its own access - control: a clinical grant such as `patient/composition-*.r` or - `user/composition-*.r` reaches none of it. - -The person's own reads of their log are recorded like every other read and -are left out of their default view; `include_self=true` adds them. Every read -of these resources, refused and failed ones included, writes an access-log -entry whose item names the log it read (`ACCESS_LOG_RECORD` for an entry, -`ACCESS_LOG` for an EHR's whole log), with the filter named by its digest. A -tombstone keeps no EHR, so a removed entry is read through the review. - -### Restricting the subject view (EHDS Art. 9(3)) - -EHDS Art. 9(3) lets a Member State restrict the person's right to see who -accessed their data "in exceptional circumstances". If your law does, declare -the restriction in the controller's -[access policy](operational-policy.md), never in `ferroehr.toml`: each entry -of `log_restrictions` names the accessor kinds it applies to (the `accessor -kind` terms of the log, such as `person` or `external person` of -`openehr_access`, or `datasubject` of `HL7_SecurityRoleType` for the -subject of care), the -accessor members the subject view withholds (`accessor_party`, -`accessor_provider`, `accessor_roles`, `accessor_groups`, in -`openehr_access`), and the provisions that lay it down, coded in your -jurisdiction's terminology. FerroEHR ships no country's restriction. - -```json -"log_restrictions": [{ - "_type": "ACCESS_LOG_RESTRICTION", - "name": { "_type": "DV_TEXT", "value": "External accessor withheld" }, - "archetype_node_id": "id11", - "accessor_kinds": [{ "_type": "DV_CODED_TEXT", "value": "external person", - "defining_code": { "_type": "CODE_PHRASE", - "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, - "code_string": "external person" } }], - "withheld": [{ "_type": "DV_CODED_TEXT", "value": "accessor_party", - "defining_code": { "_type": "CODE_PHRASE", - "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, - "code_string": "accessor_party" } }], - "legal_grounds": [{ "_type": "DV_CODED_TEXT", "value": "your national provision", - "defining_code": { "_type": "CODE_PHRASE", - "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "urn:example:national-law" }, - "code_string": "art-x" } }] -}] -``` - -- The subject and their representative get the subject view of an entry - whose accessor is of a named kind without the withheld members. A reviewer - reads the full entry, and the stored entry never changes. -- A policy write applies on the next request on every replica, with no - restart. -- A write that changes the restrictions changes what the log means, so it - writes an access-log entry of its own (operation - `admin_access_policy_write`), and the policy history keeps every version. - When the entry cannot be written, the write is answered `503`. - -```bash -# Who accessed my record this month? (the person's own token) -curl -H "Authorization: Bearer $PATIENT_TOKEN" \ - "https://cdr.example.org/ferroehr/rest/extensions/v1/ehr/$EHR_ID/access_log?from=2026-11-01T00:00:00Z" -``` - -The same entries are queryable with AQL as the top-level class -`ACCESS_LOG_ENTRY`, under the same rules of who reads which view, and each such -query writes its own entry ([Querying the access log](querying-aql.md#querying-the-access-log)). - ## Sinks Records fan out to independently configured sinks (`[audit]` in @@ -1100,7 +256,7 @@ by one statement per batch, and is in every read from its commit on. A round on every replica's audit runtime, the **chainer**, about once a second moves the frontier of both logs, owes the records below it to the configured feeds, and about once a minute seals them in windows -([Seals, checkpoints and the transfer of a log](#seals-checkpoints-and-the-transfer-of-a-log)); +([Seals, checkpoints and the transfer of a log](audit-integrity.md#seals-checkpoints-and-the-transfer-of-a-log)); a graceful stop seals what both logs hold. The `audit_sender` readiness indicator reads `DEGRADED` when the oldest record of either log has waited longer than three minutes for its seal. A record is durable from its @@ -1125,11 +281,11 @@ indicator reads `DEGRADED` with their count and age, and the metrics ### While a composition is held from the person -With [the access-delay register](security.md#delayed-access-by-the-person-ehds-art-33) +With [the access-delay register](access-control.md#delayed-access-by-the-person-ehds-art-33) on, a new composition can be held from the person under [EHDS](https://eur-lex.europa.eu/eli/reg/2025/327/oj) Art. 3(3) until a professional releases it or its period passes. Only one route honours the -hold: the subject-scoped [ITI-81 read](#retrieving-audit-records-iti-81), the +hold: the subject-scoped [ITI-81 read](audit-integrity.md#retrieving-audit-records-iti-81), the one an app serves the person's own trail from, leaves out every record that names a held composition. Every other sink and stream is a feed to the controller's own systems and carries those records and events while the @@ -1159,397 +315,6 @@ controller who answers for it. What you must not do, while a hold is in force: The [shared-responsibility page](compliance/shared-responsibility.md#the-delay-of-the-persons-access-ehds-art-33) puts the same duty on the deployment's side. -## Tamper evidence - -An audit trail that anything with the application's database password can -quietly rewrite is a log, not an accountability record. The local store is -therefore tamper-**evident**. The system records (`audit.audit_event`, the -system chain) and the access log's entries are each sealed in windows, each -seal following the one before it and covering every record of its window by -its position and content digest -([Seals, checkpoints and the transfer of a log](#seals-checkpoints-and-the-transfer-of-a-log)). - -A request writes each system record once, in `audit.audit_event`, and never -changes it. Its position (`seq`) is drawn after its transaction took its -id, and its content digest is computed by the server when it writes the -record: the SHA-256 of the RFC 8785 form of the array -`["ferroehr.audit_event.v7", {column: value}]` over every column but `seq` -and the digest, with SQL `NULL` as `null`, booleans as booleans, text and -UUIDs as strings, integers (`integer[]` element by element) as decimal -strings, instants as `YYYY-MM-DDTHH:MM:SS.ffffffZ` in UTC, dates as -`YYYY-MM-DD`, `bytea` as lower-case hexadecimal and `jsonb` as its value -(`system_log::content_digest`, with the SQL that builds the object for an -auditor). A column added by a later release joins the digest under a new -form in the same release. A record a write still holds is in no search, no -feed and no window. Which records a sink still owes is told by its cursor -(`audit.delivery_cursor`): the records past it up to the delivery frontier, -and those it parked ([How a record is delivered](#how-a-record-is-delivered)). - -The store keeps a record's facts in columns and renders its FHIR `AuditEvent` -from them when the record is read (ITI-81) or delivered (the FHIR feed). What -the rendering takes from the configuration (`source_id`, `enterprise_site_id`, -`server_host`, `value_if_missing`, the access policy's log retention and the -audit category register) is kept once per distinct configuration in -`audit.audit_render_policy`, keyed by the SHA-256 of its text, and every record -names the policy it was written under. A record therefore renders the same -document after the configuration changes, and the verification below reports a -policy whose text no longer matches its digest, as it reports a changed record. -Release 5.6.0 starts on an empty audit store: its migration refuses a store -that holds records written by an earlier release, and names the remedy. - -Four controls sit on top of it, and they are separate on purpose: - -- **The table refuses the ordinary rewrite paths outright.** An `UPDATE`, a - `DELETE` and a `TRUNCATE` of a stored record are refused by the database, - and so are a change to a seal or to a reaped position. - Retention pruning goes through the one sanctioned deletion path, which keeps - each removed record's position and content digest - (`audit.audit_event_reaped`) so its window still verifies, and removes those - only once every record of a sealed window is reaped, recording the window as - folded; so reaping does not look like tampering, and tampering does not look - like reaping. -- **The privileges are narrow.** The runtime role may record an event, stamp it - forwarded, and read the trail back. It holds nothing that can rewrite a - record, remove one, or alter a reaped position. That posture is only - fully in force with `database.migrations = "verify"`; see - [Operations](operations.md#database-roles-and-least-privilege), because a - self-migrating server owns the schema and can therefore turn the enforcement - off. -- **Verification is something you can run yourself.** For the system - records it is `ferroehr audit-chain verify`, for the access log - `ferroehr access-log verify` (or `POST /admin/access-log/verify`); each - recomputes every sealed window, every record's content digest, and follows - every seal from the one before it to the seal state. No finding means the - trail is intact. A finding names one record or window (its position, the - record's id and time when it is still there) and what is wrong with it: - content modified after it was written, a render policy, search token or - search set changed or missing, a record changed, removed or inserted inside - a sealed window, or seals removed from the end. -- **The server runs the check itself, on a schedule.** With the local store on, - the check runs one minute after boot and then every - `[audit.store] verify_interval` (default `3600`, one hour; `0` turns - it off). Each run verifies the windows sealed since the newest window an - earlier run found intact, and the seal state, so its cost follows the - records sealed since rather than the size of the trail. It walks each - log's sealed windows from its own cursor, one snapshot per step, each - sized to take about half a - second, and each intact step moves the cursor, so a backlog of any size is - verified in one run and no statement nears the - `[database] statement_timeout`. After each step the run pauses at least as - long as the step took, and longer the more the step's cost per record rose - above the lowest the server has measured for that chain: a step that cost - twice as much pauses four times as long, up to 16 times. A catch-up - therefore takes about half a core of a quiet database and yields to the - requests under load, where the lag can grow until the load falls. How far - a cursor is behind is - the `audit_chain_verification_lag` and `audit_chain_unverified_age_seconds` - metrics; once the oldest unverified record has waited longer than - `[audit.store] max_verify_lag` (default four hours), the `audit_chain` - indicator reads `DEGRADED` and names the chain. - A full pass - runs every `[audit.store] full_verify_interval` (default `604800`, - one week; `0` leaves it to the commands above) and after every run that found - damage, so damage to an older record stays reported. A run that finds damage logs at `ERROR`, one summary line with the - finding count and one line per finding (the first 20), and adds the count to - the `atna_audit_chain_findings` counter with `kind = "damage"`. A run that - cannot verify at all counts as `kind = "unverifiable"`, because a trail that - cannot be checked is never a pass. The latest result is the `audit_chain` - indicator on `GET /health/readiness`: `UP` while intact and `DEGRADED` - when damaged or unverifiable; its detail on `GET /management/health` names - the first finding. It never flips - readiness, because the trail keeps recording while the damage is - investigated. Alert on the counter or on that component, and use the - commands above to see every finding. Each replica runs its own check. - -> [!IMPORTANT] -> This is **detection, not prevention**, and the boundary is worth stating -> plainly. The unsigned seals are unkeyed, so a party with unrestricted -> write access to the `audit` schema (the database owner, or a superuser) can -> delete a record and recompute every seal after it; a signed seal kept -> outside the database shows that. A record newer than the last seal, at -> most a minute plus the frontier's lag, is protected by the refused changes -> and the grants alone. What closes that case is keeping the trail -> somewhere that party does not control. Enable -> `[audit.syslog]` or `[audit.fhir_feed]` so records leave the box as they are -> written, and give the server an app-role-only DSN so it is not that party. - -## Seals, checkpoints and the transfer of a log - -The records of the openEHR access log (`audit.access_log_record`) hold only -the accesses to EHR data, apart from the `audit_event` records above, the -system chain (an authentication, a template, party or application -operation). Neither carries a chain (#6242). A request writes each entry or -system record once, before its response, and every reader, the delivery and -the sealer read that row. What follows holds for both logs, each with its -own id sequence, holds, seals and tag, unless it names one. - -- **The frontier.** A round on every replica's audit runtime, about once a - second, moves the log's frontier: the highest entry id at or below which - every entry is committed or never will be. Every insert takes its - transaction's id before any row draws its entry id, so an entry id the - round has seen belongs to a transaction that a later snapshot shows ended. - A long writing transaction anywhere in the database delays the frontier - and loses nothing: an entry is in the log from its own commit. The - entries of a write whose commit is not yet confirmed are held, in no read, - and the frontier the sealer and the delivery use stops below them. -- **A window a minute.** About once a minute the sealer seals every entry - id past the last window, up to that bound, as one window. A seal is the - SHA-256 of this text, which you can rebuild from the stored rows: - - ```text - 27:ferroehr.access_log.seal.v1 (the system records: 27:ferroehr.system_log.seal.v1) - : - : - : - : - 64: - then, for each entry of the window in id order: - : - 64: - ``` - - Each field is its length in bytes in decimal, a colon, the field and a - line feed; integers are decimal, digests lower-case hexadecimal. The first - window follows the SHA-256 of the version tag. A tombstone keeps the content - digest of the entry it replaced, and a reaped system record leaves its - position and content digest, so its window verifies after the content is - gone. `GET /admin/access-log/seals` answers the access log's seals over a - span of entry ids. -- **The signed checkpoint.** With an OpenPGP key in the version-signing - keyring, each seal is signed as the `ACCESS_LOG_CHECKPOINT` of the log up - to the window's last entry id, whose `digest` is the seal's digest, in the - form RM common `master04-generic_package.adoc` §Attestation gives - `ATTESTATION._proof_`. A deployment without a key seals without signing, - and `ferroehr access-log checkpoint` refuses. `ferroehr access-log - checkpoint` and `POST /admin/access-log/checkpoint` seal every committed - entry and answer the newest checkpoint; `GET /admin/access-log/checkpoint` - answers the newest stored one, or the one at `sequence`. -- **What is left unsealed.** A record of either log newer than the last - seal, at most a minute and the frontier's lag, is protected by the refused - `UPDATE` and `DELETE` and by the runtime role's grants alone. The CRA risk - assessment (C4, C5) and hazard H7 state that window. -- **Publish the checkpoints outside the database.** Someone who can write - the database can remove the newest windows together with their seals, and - nothing left in the database shows it. Set `[audit.access_log] - publish_directory` to storage that person cannot rewrite: every 30 seconds - the server writes the newest checkpoint there as its own file, - `access-log-checkpoint-.json`, created once and never - rewritten. Without it the `access_log_checkpoints` health indicator reads - `DEGRADED`. To verify the log against a published checkpoint, run - `ferroehr access-log verify --checkpoint ` with the newest file. -- **Verification.** `ferroehr access-log verify` and `POST - /admin/access-log/verify` recompute every window from its rows and every - column the log derives from an entry's content, follow the seals from one - to the next to the sealer's state, and check the checkpoint's signature and - that the seal at its position is the one it signs. A changed, removed or - inserted record inside a sealed window is reported, as is a removed seal. - They also verify every imported bundle. -- **The fold.** Once every record of a sealed window is a tombstone past its - end, the retention run removes the window's entries and records the window - as folded with the grounds its tombstones named. Its seal stays, so the - seals still follow one another. -- **Moving the log with the EHR.** `ferroehr access-log export ` and - `POST /admin/access-log/export?ehr_id=…` export one EHR's records as a - bundle: each record with its content digest, signed whole by this system's - keyring over its RFC 8785 form without its proof. It carries no record or - digest of another person. `ferroehr access-log import ` verifies the - signature against the certificates in `[audit.access_log] - trusted_key_files` and every entry's digest, keeps the records with their - `system_id`, `retain_until` and content digest, and records the import as - an entry of this log that names the bundle's digest and a digest over the - imported records' uids and content digests, so this log's seal covers - them. An imported entry ends at the `retain_until` it states; its - tombstone is kept as long again and then folds, leaving its uid, bundle - and content digest so the bundle still verifies. A repeated import stores - nothing twice. -- **The system records are sealed too.** The same sealer and key seal their - windows (`audit.audit_event_seal`), each signed as a seal naming the - window's last position and its digest. `ferroehr audit-chain seal` seals - every committed record on demand and prints the newest signed seal, and - `ferroehr audit-chain verify [--seal ]` recomputes every window, - checks the seal's signature and that the window ending at its position has - the digest it fixes, and exits 1 when the records do not verify. Retention - removes a system record at its own end and keeps its position and content - digest; once every record of a sealed window is reaped, the window's - reaped positions are removed and the window recorded as folded. -- **The erasure is recorded once.** `POST /admin/access-log/erase` writes the - tombstone and the entry that records the erasure in one transaction; the - erasure is not written a second time as an `audit_event` record. - -## Retrieving audit records (ITI-81) - -The RESTful-ATNA **ITI-81 Retrieve ATNA Audit Event** transaction is a FHIR -search on `AuditEvent`, so it is served at FerroEHR's FHIR R4 base, -`/ferroehr/rest/fhir/r4`, beside the openEHR API rather than under it, where a -FHIR client or an IHE Audit Consumer expects `[base]/AuditEvent`. It is the one -FHIR route FerroEHR serves: - -```text -GET /ferroehr/rest/fhir/r4/AuditEvent -``` - -It returns a FHIR `searchset` Bundle of the matching records' `AuditEvent` -documents, rendered from the store, newest first, with a `self` link and a -`next` link while more pages follow. The page carries the full match `total` -only when the query asks for it with `_total=accurate` or `_total=estimate` -(FHIR R4 Search §3.1.1.5.2): counting every match reads every record the -filter selects, and a page alone reads one record past what it serves. The query is read by `ihe-atna`, the family's audit -crate. At least one `date` parameter is required (RESTful ATNA -§3.81.4.1.2.1): a query without one is a `400`. Every search parameter -§3.81.4.1.2.2 says the repository shall support is applied. A parameter -with several comma-separated values matches any of them, and every -parameter of the query must match. A token takes the three forms of FHIR R4 -Search §3.1.1.4.10: `code`, `|code` (recorded without a system) and -`system|code` (or `system|` for any code of that system). FerroEHR records -identifiers without a system, except the object of an access record, whose -system is `urn:openehr:object-id`: `entity.identifier=urn:openehr:object-id|` -and `entity.identifier=` find it, and a query that names another system -for an identifier matches nothing. Every parameter answers through an index. A -parameter on an element of the document (`address` and the `.identifier`, -`entity-type`, `entity-role`, `type` and `subtype` parameters) matches the -search tokens the store takes from the record's rendered document -(`audit.audit_search_token`, `audit.audit_search_set` and the record's -`search_tokens`): a system record's when the store writes it, an access-log -entry's when the frontier round renders it from the stored entry into -`audit.access_log_index`, about once a second, which go with the entry's -content when a tombstone replaces it. A search on such a parameter first -moves the index past every entry written before it, so it finds an entry -written a moment ago; when an open database transaction keeps it from doing -so within 2 seconds, the search answers `503` with `Retry-After`. So the -search finds what the served document says and renders only the page it -serves. An `entity.identifier` that carries -the record's request id or the object it names (the version uid of a create) -is read from the record's own column instead, so a request adds no row to -`audit.audit_search_token`. One GIN index per record table holds the search -tokens and a key for each of the request id and the touched resource id -(`audit.search_keys`), which answers `entity` and such an `entity.identifier` -as well; the search then compares the text. Retention deletes the tokens -that no remaining system audit record, access-log entry or search set names, -and never one a kept record names. - -| Parameter | Matches | -|---|---| -| `date` | **required**, repeatable: a FHIR date value with a prefix (`eq` when none, `gt`, `lt`, `ge`, `le`, `sa`, `eb`); a day such as `2026-07-12` covers the whole day, read in UTC | -| `patient` | the recorded patient (EHR subject) id | -| `patient.identifier` | `entity.what.identifier` of the entity whose role is Patient | -| `agent` | the authenticated principal | -| `agent.identifier` | `agent.who.identifier` | -| `entity` | the touched resource id | -| `entity.identifier` | `entity.what.identifier` of any entity | -| `entity-type` | `entity.type` | -| `entity-role` | `entity.role` | -| `source.identifier` | `source.observer.identifier`, the audit source id | -| `type` | `type` | -| `subtype` | `subtype` (the REST interaction and the openEHR operation) | -| `address` | a part of `agent.network.address`, compared without regard to case | -| `outcome` | the outcome indicator: `0`, `4`, `8` or `12` (FerroEHR records `0`, `4` and `8`) | -| `action` | the action code: `C`, `R`, `U`, `D` or `E` | -| `_count` / `_offset` | paging; page size defaults to 50, capped at 1000; `_count=0` returns the total alone | -| `_total` | `accurate` or `estimate` adds the full match `total`; `none`, or no `_total`, serves the page without it; any other value is a `400` | - -A malformed value is a `400` carrying a FHIR `OperationOutcome` with -`invalid`; another FHIR R4 `AuditEvent` parameter, which §3.81.4.1.2.2 does -not ask for, is a `400` with `not-supported`; a parameter the crate does not -know is ignored -(§3.81.4.1.3). Under RBAC the -unscoped retrieval is **admin-only**; a caller holding a -`read_subject_audit` grant, an app acting for the people it -serves, reads it **scoped to one subject**: one -`patient` or `patient.identifier` with one value is required, and the caller -is refused with a `403` that names the parameter when it omits -it. Reading a subject's log is itself recorded as an access naming that -subject and the record count served. An -[justified access](#justified-and-emergency-access) in the subject's log carries the clinician's reason -as the text of its purpose of use, and an emergency its mark as the -`ehds-emergency-access` entity. The surface answers `404` when the local -store is disabled. - -The subject-scoped ITI-81 read stays beside the [access-log -resources](#reading-the-access-log-over-its-rest). It serves the ATNA records -as FHIR `AuditEvent`s to a portal that holds a `read_subject_audit` grant and -names the subject itself; `GET /ehr/{ehr_id}/access_log` serves the openEHR -access-log entries of the same accesses to the person, or their -representative, under the person's own credential. - -```bash -# Who accessed patient-42's data this month? -curl -u admin:pw \ - "https://cdr.example.org/ferroehr/rest/fhir/r4/AuditEvent?patient=patient-42&date=ge2026-07-01T00:00:00Z" -``` - -This is also the openEHR "record demerging" instrument: when data lands in -the wrong EHR, the patient-filtered audit search shows exactly who read it. - -> [!NOTE] -> Audit records are themselves sensitive (they name patients, subjects and -> actions) so this endpoint is a PHI-disclosure surface and is authorized like -> any other. - -## Node authentication (ITI-19, mutual TLS) - -ATNA's second half is node authentication. `[server.tls]` terminates TLS -natively and can demand a verified client certificate: - -```toml -[server.tls] -certificate_file = "/etc/ferroehr/server.pem" -key_file = "/etc/ferroehr/server.key" -min_version = "1.3" # 1.3 (default) | 1.2 -client_auth = "required" # none | optional | required -client_ca_file = "/etc/ferroehr/client-ca.pem" -``` - -The protocol floor is **TLS 1.3 only** by default, as RFC 9325 §3.1.1 has it -supported. Setting `min_version = "1.2"` enables -1.2 *alongside* 1.3, never instead of it, for a client that genuinely cannot -do 1.3, such as an older integration engine or a pinned Java runtime. TLS 1.1 -and 1.0 are refused when the configuration is read (RFC 8996). - -With `client_auth = "required"`, only clients presenting a certificate -chaining to your explicit trust anchor complete the handshake: the IHE -mutually-authenticated-node posture. Deployments terminating TLS at an -ingress leave `[server.tls]` unset and enforce mTLS there instead. - -> [!WARNING] -> The separate-port management listener (`management.listen`) stays **plain HTTP** -> even with `[server.tls]` set, and it binds all interfaces. Treat it as an -> internal surface and keep it off any publicly routed port. Under -> `deployment.profile = "production"` setting it opens the `plaintext_listener` -> gap, so the server refuses to start unless the gap is accepted by name. - -Complete the posture with time synchronisation (IHE Consistent Time): run -NTP/chrony on every node so audit timestamps align across systems. - -## Against independent ATNA implementations - -The transactions above are tested by FerroEHR's own suites, which read the -profiles the way FerroEHR's authors read them. EHDS Annex II 1.4 asks that a -component meant to work with other products does so reliably, so -[`scripts/interop/atna.sh`](https://github.com/FerroHEALTH/FerroEHR/blob/main/scripts/interop/atna.sh) -runs the quickstart against software FerroEHR's authors did not write, each -from a published image: - -| Transaction | Independent implementation | What the run requires | -|---|---|---| -| ITI-20 FHIR feed | HAPI FHIR, an open-source FHIR R4 server, as the Audit Record Repository, with IHE BALP 1.1.4 loaded | It accepts every record, and its validator finds no error against base R4 and the BALP profile each record names | -| ITI-20 syslog | syslog-ng over RFC 5425 TLS | Every message parses as RFC 5424, and its payload is a well-formed DICOM PS3.15 A.5.1 `AuditMessage` (libxml2) | -| ITI-81 | HAPI FHIR's AuditEvent search over the records the feed delivered | The same searches answer the same records on both | - -```shell -cargo build --release -p loadtest -bash scripts/interop/atna.sh ghcr.io/ferrohealth/ferroehr: \ - ghcr.io/ferrohealth/ferroehr-postgres: atna-out -``` - -It prints every disagreement and exits non-zero on any. A disagreement is -either FerroEHR's or a shared crate's defect, filed and fixed, or the other -side's, recorded with the profile text that shows it. - -The run of 2026-10-29 found no disagreement: HAPI FHIR accepted and validated -all 71 records of the window, syslog-ng parsed all 72 messages, and the ten -ITI-81 searches answered the same records on both repositories -([the record](https://github.com/FerroHEALTH/FerroEHR/blob/main/docs/conformance/interop/atna/2026-10-29.md)). - ## Configuration summary Auditing defaults to on with the local store only; see the diff --git a/website/book/src/behind-ferrosmart.md b/website/book/src/behind-ferrosmart.md index b9c0e670e1..c1840d7f67 100644 --- a/website/book/src/behind-ferrosmart.md +++ b/website/book/src/behind-ferrosmart.md @@ -182,7 +182,7 @@ treats it as the person, exactly as their own login: - It reads only the EHR whose subject is the patient's `PERSON`. Any other EHR is refused `403` with `refused-not-subject`. -- A composition the [access delay](security.md#delayed-access-by-the-person-ehds-art-33) +- A composition the [access delay](access-control.md#delayed-access-by-the-person-ehds-art-33) holds reads as absent until a professional releases it (EHDS Art. 3(3)). - Below the `[authz.assurance]` floor it is refused `401` with the RFC 9470 §3 step-up challenge, so FerroBRIDGE sends the person back to FerroSMART @@ -215,7 +215,7 @@ minimum = "substantial" The floor holds every patient-data request, a professional's included, and a Basic credential carries no level, so it is refused on patient data -([Authentication & access](installation/config-auth.md#authzassurance-the-assurance-level-patient-data-requires)). +([Authentication & access](installation/config-authz.md#authzassurance-the-assurance-level-patient-data-requires)). ## The discovery document describes FerroSMART diff --git a/website/book/src/beyond-core/demographics.md b/website/book/src/beyond-core/demographics.md index d617498f06..a21cddc7b4 100644 --- a/website/book/src/beyond-core/demographics.md +++ b/website/book/src/beyond-core/demographics.md @@ -43,7 +43,7 @@ database refuses the mix in both directions: a version with no owning EHR cannot enter the clinical schema, and one that has an owner cannot enter `party`. Point `[database.party] url` at a role of its own and the schema separation becomes a credential separation as well. See [Operations → Database roles and least -privilege](../operations.md#database-roles-and-least-privilege) for the roles +privilege](../database-operations.md#database-roles-and-least-privilege) for the roles and [the pseudonymisation boundary](../security.md#the-pseudonymisation-boundary) for what the split is for. diff --git a/website/book/src/beyond-core/federation-node.md b/website/book/src/beyond-core/federation-node.md index 34da65d860..2775807a56 100644 --- a/website/book/src/beyond-core/federation-node.md +++ b/website/book/src/beyond-core/federation-node.md @@ -114,7 +114,7 @@ their rights come from an agreement, never from a role facility types the caller's token attests and the purpose it declares, each with the provision it rests on in its `legal_grounds`. The node refuses such a caller with `403` as `refused-policy-denied` and records the - provision ([Controller rules](../operational-policy.md#controller-rules)). + provision ([Controller rules](../access-policy.md#controller-rules)). - **Wabvpz Art. 15a consent.** Every NL federation read needs the consent decision reference, from Mitz or from the data holder's own registration (`consent = "mitz"` or `"local"`), carried in the token. diff --git a/website/book/src/beyond-core/index.md b/website/book/src/beyond-core/index.md index be4bdfb32b..8c9ffbdede 100644 --- a/website/book/src/beyond-core/index.md +++ b/website/book/src/beyond-core/index.md @@ -16,7 +16,7 @@ you have to turn it on, and how to consume it. > separate server that maps between FHIR and openEHR with FHIRconnect mappings > and reaches FerroEHR over the ITS-REST API. On Kubernetes the FerroEHR chart > deploys it beside the CDR with `bridge.enabled=true` -> ([FerroBRIDGE](../installation/kubernetes.md#ferrobridge-the-fhir-bridge-off-by-default)). +> ([FerroBRIDGE](../installation/kubernetes-integrations.md#ferrobridge-the-fhir-bridge-off-by-default)). > FerroEHR keeps two uses of FHIR: > the access log rendered as FHIR `AuditEvent` with the ITI-81 retrieval > ([Audit](../audit.md)), and the client for external FHIR terminology servers @@ -89,8 +89,8 @@ for the exact list of settings a slim binary rejects. - **[Change events (outbox feed)](outbox-feed.md):** a transactional outbox that records a PHI-free event for every commit and serves it, in order and at least once, to the readers you name, so downstream systems can respond to - changes instead of polling. FerroBRIDGE 0.0.15 and later deliver the events - on to an AMQP broker. + changes instead of polling. FerroBRIDGE delivers the events on to an AMQP + broker. - **[S3 multimedia](s3-multimedia.md):** threshold-based, content-addressed offload of large `DV_MULTIMEDIA` blobs to any S3-compatible object store, with integrity verification on the way back in. diff --git a/website/book/src/beyond-core/messaging.md b/website/book/src/beyond-core/messaging.md index 7ce6b06830..119800288b 100644 --- a/website/book/src/beyond-core/messaging.md +++ b/website/book/src/beyond-core/messaging.md @@ -15,7 +15,7 @@ for. FerroEHR implements whole-EHR export, import into a new or an existing EHR > claim. Unlike the admin extensions, they are **not** admin-gated: they carry > the same ordinary authentication as the clinical API. The four routes, with > their bodies, parameters, and status codes, are in -> [Admin & messaging APIs](../operations-admin-apis.md#ehr-extract-export-and-import). +> [Admin & messaging APIs](../storage-admin-apis.md#ehr-extract-export-and-import). diff --git a/website/book/src/beyond-core/outbox-feed.md b/website/book/src/beyond-core/outbox-feed.md index ab16dfd3c2..0056ccc2c8 100644 --- a/website/book/src/beyond-core/outbox-feed.md +++ b/website/book/src/beyond-core/outbox-feed.md @@ -7,8 +7,7 @@ serves those events to the readers you name over a cursor feed. The events carry identifiers and metadata, never the record content. FerroEHR publishes to no message broker. FerroBRIDGE, the family's export and -import server, delivers the events to an AMQP broker such as RabbitMQ from 0.0.15 -on: its `[events]` lane reads this feed and publishes each event with its own +import server, delivers the events to an AMQP broker such as RabbitMQ: its `[events]` lane reads this feed and publishes each event with its own exchange, routing keys and queues, and moves its cursor only after the broker confirmed the event ([FerroBRIDGE issue 1367](https://github.com/FerroHEALTH/FerroBRIDGE/issues/1367)). @@ -179,23 +178,3 @@ A row left out is served once the mark is lifted or the directive no longer denies it, as long as the reader's cursor has not passed it. A page is never cut short by what it leaves out: the read goes on past those rows until it holds the page or reaches the tail. - -## Moving from FerroEHR's own RabbitMQ publisher - -Earlier releases of FerroEHR published to RabbitMQ themselves, under -`[events]`, with subscription rows under `/admin/event_subscription`. Both are -gone. To keep the events flowing to the same broker through FerroBRIDGE 0.0.15 -or later: - -1. Grant FerroBRIDGE's client a `read_change_feed` grant naming its reader, - and give the client the `__ferroehr.outbox` scope. -2. Configure FerroBRIDGE's events lane with the broker URL, the exchange and - the queues your subscriptions used to declare. -3. Remove `[events]` from FerroEHR's configuration, `secrets.eventsUrl` from the - chart values, and `plaintext_broker` from `deployment.accepts`: the server - refuses to start on any of them. - -A new reader starts at cursor `0`, so FerroBRIDGE delivers every row still in -the outbox: the ones the publisher had not sent, and the ones it had sent inside -the retention window, which a consumer that deduplicates on `contribution_id` -skips. diff --git a/website/book/src/beyond-core/s3-multimedia.md b/website/book/src/beyond-core/s3-multimedia.md index df24ae682b..0a0d870880 100644 --- a/website/book/src/beyond-core/s3-multimedia.md +++ b/website/book/src/beyond-core/s3-multimedia.md @@ -172,7 +172,7 @@ still act on it, rather than at the first multimedia commit. ### On Kubernetes Every key above is reachable as `config.multimedia.*` -([Any server setting is reachable](../installation/kubernetes.md#any-server-setting-is-reachable)); +([Any server setting is reachable](../installation/kubernetes-integrations.md#any-server-setting-is-reachable)); the S3 credentials go through `secrets.*`, which the chart mounts as files: ```yaml diff --git a/website/book/src/beyond-core/terminology.md b/website/book/src/beyond-core/terminology.md index 227a853f0c..7f5efc3cb0 100644 --- a/website/book/src/beyond-core/terminology.md +++ b/website/book/src/beyond-core/terminology.md @@ -187,7 +187,7 @@ that gives you both. [FerroTERM](https://github.com/FerroHEALTH/FerroTERM) is the terminology server FerroEHR ships with: the `docker-compose.terminology.yml` overlay of the quickstart starts it beside the CDR and points `[terminology]` at -`http://ferroterm:8080/r4b`, the [compose page](../installation/compose.md#the-terminology-overlay-ferroterm) +`http://ferroterm:8080/r4b`, the [compose page](../installation/compose-overlays.md#the-terminology-overlay-ferroterm) has the commands. The hosted sandbox at runs the same pair on one machine, so the coded-text binding you see resolving there is a real round trip to a real terminology server. @@ -268,7 +268,7 @@ sandbox machine, beside the licence-free shaped seed the compose profile ships. ## Running one locally (development and CI) The quickest local terminology server is the quickstart's -[terminology overlay](../installation/compose.md#the-terminology-overlay-ferroterm): +[terminology overlay](../installation/compose-overlays.md#the-terminology-overlay-ferroterm): FerroTERM beside the CDR, the shaped seed served, the CDR wired, one command and no checkout. The conformance lane runs the same server from a checkout of the repository, with the shaped seed mounted read-only out of @@ -305,10 +305,10 @@ opt-in that adds FerroTERM to it. ## On Kubernetes `terminology.enabled=true` runs FerroTERM in the cluster and wires the CDR at it -([FerroTERM on Kubernetes](../installation/kubernetes.md#ferroterm-a-terminology-server-beside-the-cdr-off-by-default)). +([FerroTERM on Kubernetes](../installation/kubernetes-integrations.md#ferroterm-a-terminology-server-beside-the-cdr-off-by-default)). A server outside the cluster goes through the `config` passthrough, which renders the keys verbatim into the server's configuration file -([Any server setting is reachable](../installation/kubernetes.md#any-server-setting-is-reachable)): +([Any server setting is reachable](../installation/kubernetes-integrations.md#any-server-setting-is-reachable)): ```yaml # values.yaml diff --git a/website/book/src/caller-facts.md b/website/book/src/caller-facts.md new file mode 100644 index 0000000000..a7809e3337 --- /dev/null +++ b/website/book/src/caller-facts.md @@ -0,0 +1,506 @@ +# Roles, care relationships and representatives + +The facts the access evaluator reads about a caller: the roles it performs, its care +relationships and the persons it represents. How they take part in a decision is on +[How FerroEHR decides access](explanation/access-model.md). + + + +## Caller facts: roles and care relationships + +What FerroEHR stores and decides on, and what it leaves to your applications +and your deployment, is listed in +[What the CDR leaves to the application](application-boundary.md). + +Beside its grants, a caller carries the facts the access evaluator reads: +the roles it performs, the care teams it belongs to and the providers it +acts for. A patient carries its care relationships. FerroEHR reads them in +any archetype (a membership by `openehr_access` `member_of`, care by +`under_care_of`), never by an archetype id, and holds them +on every replica beside the grants, so a request reads them with no +transaction of its own. + +**Roles.** A `ROLE` whose `name` is a `DV_CODED_TEXT` of the terminology +your jurisdiction names, such as a national professional role code, is a +role its `performer` holds while the `ROLE` is in force: its `time_validity` +holds the date of the request and it is not deleted. The role's type is its +name (RM Demographic IM, `PARTY.type()`), so a nurse is one `ROLE` per nurse, +each named by the nurse code. A [controller rule](access-policy.md#controller-rules) names a +role in an `applies_to` entry, compared by terminology and code. A `ROLE` +named in text, or by a code of `openehr_access`, names no role. A +token's role claims never count for a rule: they decide only the coarse RBAC +class gate ([Security](security.md)). The one exception is a caller admitted +under a [federation agreement](operational-policy.md#federation-agreements): the professional +roles its token attests in `professional.hp_professional_role` are its roles, +each a code of the system the value names, because no `ROLE` of this store +describes a partner's professional. Which sensitivities a caller may read +and which purposes it may declare are rules of the access policy too, never +elements of a capability. A SCIM client writes these `ROLE`s from a User's +`roles`, within the roles its grant admits +([SCIM roles](installation/config-scim.md#roles)), so your identity +provider assigns roles and the access policy says what each may do. + +**Organisation types.** An `ORGANISATION` whose `name` is a `DV_CODED_TEXT` +of the terminology your jurisdiction names, such as a national care +provider type, is of that type, read as a `ROLE`'s name is. A system client +acting for that provider acts for an organisation of that type, and a +caller admitted under a federation agreement acts for one of each type its +token attests in `provider.facility_type`. A [controller +rule](access-policy.md#controller-rules) names them in an `applies_to` entry's +`organisation_type`, compared by terminology and code. + +**Memberships.** A `PARTY_RELATIONSHIP` in a `PERSON`'s `relationships` +whose `name` or `details` carry `member_of` of `openehr_access` makes the +professional a member of the care team or unit its `target` names, for as +long as its `time_validity` holds. A membership of a party other than a +`PERSON` or an `ORGANISATION`, and one whose target is no party of this +store, is refused `422`. + +**Care relationships.** A care relationship is a `PARTY_RELATIONSHIP` of +its own, written at `/demographic/party_relationship`, each versioned with +its own audit details (draft access control package, Care Relationships and +The Relationship Store). Its `name` is the code `under_care_of` of +`openehr_access`, its `source` is the patient's `PERSON`, and its `target` +is the carer: a professional's `PERSON`, a `ROLE` a professional performs, a +care team's `GROUP` or an `ORGANISATION` unit. Its `details` hold elements +named by codes of `openehr_access`: + +| Element | Occurrences | Value | +| --- | --- | --- | +| `care_role` | 1..1 | A `DV_CODED_TEXT`: the part the carer plays in the patient's care, of the value set the access policy binds for `care_role`, or of `HL7_ParticipationType` when it binds none, such as `RESP`, `ATND` or `PART` when the role is not stated | +| `provider` | 1..1 | A `DV_IDENTIFIER` of type `ORGANISATION`: the healthcare provider in whose care the relationship is, by the namespace of its reference and its id, or by the issuer and id of its identifier | +| `covers_for` | 0..1 | A `DV_IDENTIFIER` in the provider's form: the carer the target replaces, its `issuer` the namespace of the carer's reference, its `id` the carer's container and its `type` the carer's kind (`PERSON`, `ROLE`, `GROUP` or `ORGANISATION`), never the target itself | +| `episode` | 0..1 | A `DV_IDENTIFIER`: the episode of care the relationship is scoped to, by the `issuer` and `id` the care delivery environment gives it | +| `basis` | 0..1 | `assigned` (the default); `self_declared` where the policy sets `self_declared_care` ([Writing a care relationship](access-policy.md#writing-a-care-relationship)) | + +A caller holds a live care relationship when the relationship's `target` +names its `PERSON` or a `ROLE` it performs (the `direct` path), or a care +team or unit it is a member of (the `team` path), or, for a `self_declared` +relationship, its own `PERSON` (the `self_declared` path), the access +declares no purpose or one of the policy's `care_purposes`, and it acts for +the relationship's `provider`: a bound professional acts for the provider the party binding +names (`[authz.party_binding.provider]`, or the table of its tenant when the +binding names one per tenant), and a system client for the `ORGANISATION` +its `AGENT` acts for, matched by that organisation's own reference (its +namespace and id) or by its identifier (issuer and id), and for the +`GROUP`s that provider is a member of. Its `time_validity` is the period of the care: the end is the +upper bound, and the relationship stays, so the evaluator can apply a grace +period after it. A relationship without a `care_role` or a `provider`, with a +role outside its value set, or with a target of another kind is refused +`422`, as is one whose `provider` names no `ORGANISATION` of the store by +the identifier it carries, or whose `covers_for` names no party of its +`type`, names the target, or lacks its issuer, container id or type. A care relationship held in a `PERSON`'s `relationships` is refused +`422`, naming `/demographic/party_relationship`. The default definitions ship +`openEHR-DEMOGRAPHIC-PARTY_RELATIONSHIP.member_of.v1.0.1` and +`openEHR-DEMOGRAPHIC-PARTY_RELATIONSHIP.under_care_of.v2.0.0` as examples +([Default demographic definitions](installation/default-demographic-definitions.md)). + +**Placing a composition in an episode of care.** A COMPOSITION names the +episodes of care it belongs to with an `ELEMENT` anywhere in its +`context.other_context` whose `name` is the code `episode` of +`openehr_access` and whose value is the episode's `DV_IDENTIFIER` (`issuer` +and `id`), as the care delivery environment identifies it. FerroEHR keeps +the episodes of each composition's current version. A directive, a rule of +your access policy, a classification or a delegation names an episode's +data with `episodes` in its `ACCESS_DATA_SCOPE`, each a `DV_IDENTIFIER` +compared by `issuer` and `id`: a patient's restriction of one episode hides +that episode's compositions and nothing else, and data placed in no episode +match no entry. A persistent composition (`openehr::431`) that names an +episode, and an `episode` element without a `DV_IDENTIFIER` carrying an +issuer and an id, are refused `422` on a commit, a CONTRIBUTION, an EHR +Extract import and an archive load. So is a composition placed in an episode +that no care relationship of its EHR's subject names, live or ended: write +the relationship with its `episode` before the data placed in it. An import +is judged against the relationships this CDR holds and those in the +extract's demographics chapter, an archive load against those it holds and +those in the archive. Your template must admit the element, for example in +a CLUSTER of an `other_context` slot. + +A `relationship_validity` entry of the access policy with +`episode_required` set refuses `422` a care relationship of the roles and +provider types it covers that names no `episode`. + +**Care scoped to an episode.** A care relationship that names an `episode` +admits on care only the data of that episode, the data placed in no +episode and the data your access policy's `episode_shared` names. A +relationship that names no episode covers the whole record, as before. A +patient admitted to cardiology and seen by dermatology has two episodes: a +cardiologist whose one live relationship names the cardiology episode reads +the cardiology data and the unplaced data, is refused the dermatology data +with `refused-outside-episode` (`403`, step 7 of the access record), and no +query, count or page shows it. An access service caller also reads the data +of the EHDS priority categories (Art. 14(1)) through the category map. An +emergency, the patient, a permit directive and a gate-keeper decide as they +do without episodes. A query can narrow your caseload further to named +episodes with `caseload_episodes` ([Narrowing a query to your +caseload](querying-aql.md#narrowing-a-query-to-your-caseload)). + +**Group memberships of a provider.** A `PARTY_RELATIONSHIP` in an +`ORGANISATION`'s `relationships` carrying `member_of` makes that provider a +member of the `GROUP` its `target` names, such as the providers of a +regional health network, for as long as its `time_validity` holds. A system +client acting for the `ORGANISATION` then acts for the `GROUP` too, so a +consent permit naming the regional `GROUP`, such as one copied from the +region's IHE BPPC opt-in policy, admits it. FerroEHR resolves one level: a +`GROUP` that is itself a member of another `GROUP` adds nothing. An +`ORGANISATION` carrying `under_care_of` is refused `422`. The same +`write_care_relationship` rule guards a change of an `ORGANISATION`'s +memberships. + +**Who writes them.** The care delivery environment does, as openEHR's +security overview asks: "the evaluation of a role category such as 'care +deliverer' into particular identities ... must be done in each care +delivery environment, not in the EHR" (BASE Architecture Overview, §The +Problem of Roles). A care relationship, its change or its deletion, and a +version of a `PERSON` that adds, changes or removes a membership, commits +only for a caller holding a `write_care_relationship` grant that covers it, +such as your hospital's ADT system, or for an administrator; anyone else is +refused `403`. A version that leaves the memberships as they were needs no +grant. The grant covers what its elements name (draft access control +decision procedure, Writing Relationships): + +- **A care relationship** is covered when one `provider` element names its + `provider` and one `target_kind` element names the RM type of its target. +- **A membership** is covered when one `provider` element names a provider + of the `ORGANISATION` it targets, or of the `ORGANISATION` the `GROUP` it + targets belongs to. A `GROUP` belongs to an `ORGANISATION` by its own + `member_of` relationship to it; a `GROUP` that belongs to none, such as a + region, takes memberships from an administrator alone. + +A grant with no `provider` or no `target_kind` element writes nothing it +would need them for. The operator grants one with typed flags: + +```sh +ferroehr party-binding grant --issuer https://machines.example --client-id adt \ + --operation write_care_relationship \ + --provider-issuer urn:oid:2.999.7 --provider-id sint-example \ + --element target_kind=GROUP --element target_kind=PERSON +``` + +**A writer never admits itself.** Each caller fact and each row of the care +projection names the party that wrote it: the `PERSON` of a professional or +the client `ACTOR` of a system, as the commit audit's committer names it in +`external_ref`. A caller is never admitted on a care relationship or a +membership that it, or a party among its principals, wrote, so a +professional who rosters themselves onto a ward reads nothing through it. +The one exception is a `self_declared` care relationship where the policy +allows it ([Writing a care relationship](access-policy.md#writing-a-care-relationship)). +FerroEHR compares what each relationship says (its code, target, role, +provider and validity), never its position in `relationships`, so removing +another relationship before it changes none. + +The care delivery environment reaches FerroEHR on two channels, and a +deployment uses either or both: + +- **The ADT or rostering system** writes memberships (`member_of`) and `under_care_of` + through the Demographic API. On the `PERSON` of a SCIM User, which the + party binding protects, a version whose only change is to its care + relationships commits under the grant; any other change it makes stays + `403`, so the ADT system rosters a professional and touches nothing the + identity provider owns. It reads the `PERSON` to write it, so it sees the + professional's binding key and SCIM attributes. +- **The identity provider** marks a SCIM Group as a care team + ([Care teams provisioned over SCIM](#care-teams-provisioned-over-scim)). + +The two never undo each other: a SCIM Group change touches only +memberships of the membership archetype, and the ADT system's relationships +are of its own archetype. + +**When a change applies.** An admission, a transfer and a discharge decide +the next request on every replica. The commit stamps the patient whose facts +changed, and each replica reads only the facts of the parties stamped since +its copy, in one indexed read. + +No openEHR specification gives a role or a relationship an access meaning: +reading a `ROLE`'s coded name as the role a rule names, reading +relationships as care relationships and group memberships, the +`write_care_relationship` rule, and holding them in memory are FerroEHR's +own design. + +### The care relationship resources + +These resources are an extension of the openEHR REST API: ITS-REST 1.1.0 +has no resource for a relationship, so FerroEHR serves them under the +extensions root (`/ferroehr/rest/extensions/v1`), after the draft access +control package (ITS-REST Resources, Care Relationships). Each is the +`under_care_of` `PARTY_RELATIONSHIP` above in a narrower form, so a write +needs the same `write_care_relationship` grant and commits a version with its +audit details in a contribution. + +| Resource | What it does | +| --- | --- | +| `GET /care_relationship?subject_id=&subject_namespace=` | The care relationships of the subject that reference names, live ones by default; `at=YYYY-MM-DD` the day they are live on, `all=true` ended ones too | +| `GET /demographic/person/{uid_based_id}/care_relationship` | The same, for the subject this `PERSON` is | +| `POST` on either | Adds a relationship whose `source` is that subject's `PERSON`: `201` with `ETag` and `Location`; `422` for a body that is no care relationship of that subject | +| `GET /care_relationship/{relationship_uid}` | One relationship, its current version or the version the uid names; `204` once it is deleted | +| `PUT /care_relationship/{relationship_uid}` | Changes the role or the period, with `If-Match` naming the current version (`400` without it, `412` with `ETag` naming the current one when it is stale); closing `time_validity` ends it | +| `DELETE /care_relationship/{relationship_uid}` | Removes one written in error, with `If-Match`; its earlier versions keep it | +| `GET /versioned_care_relationship/{relationship_uid}`, `.../revision_history`, `.../version/{version_uid}` | The versioned object, its revision history with the audit details of each version, and one version | +| `GET /care_relationship?carer={uid}` | The relationships that reach a carer's party, `role=terminology_id\|code` and `path=direct` or `team` to narrow them, `at` as above, paged by `offset` and `fetch` (100 by default, at most 1000) | + +That a person is under the care of a given professional or service is data +concerning health (GDPR Art 4(15), Art 9), so every read is decided per +subject it reveals. A relationship is served only to a caller who may read +the subject's record, judged as a read of each of the subject's EHRs, or to a +caller who writes care relationships for the relationship's provider (an +administrator, or a `write_care_relationship` grant naming that provider). A +list leaves every other relationship out, and a read of one answers `404`, so +its role and context never reach that caller. A subject with no EHR has no +record to read, so only a writer for the provider sees its relationships. +Each read writes one access record per subject it reveals: an access-log +entry on the subject's EHR, or, for a subject with no EHR, an access record +naming its `PERSON`. The resources carry the Demographic API's SMART +requirement: a client granted `access_demographic`, or the product scope. + +```sh +curl "$BASE/ferroehr/rest/extensions/v1/demographic/person/$PATIENT/care_relationship" \ + -H "Authorization: Bearer $ADT_TOKEN" +``` + +The resources, the per-subject decision and the writer's exception are +FerroEHR's own design over its draft access control package; no openEHR +specification defines them. + +### Care teams provisioned over SCIM + +A SCIM Group is a care team when its client creates it with +`careTeam = true` in FerroEHR's Group extension +`urn:ietf:params:scim:schemas:extension:ferrohealth:2.0:Group`. RFC 7643 +§4.2 leaves what a Group means to the service provider, and the openEHR +Demographic IM names "the specialist care team, e.g. cardiology team" as +the typical `GROUP`, so this reading is FerroEHR's own design. The Demographic +IM makes a party's type its name (`PARTY.type()`, invariant +`Type_valid: type = name`, and `PARTY_RELATIONSHIP.type()` likewise), so its +`GROUP` is named by the coded `care_team` and each member's membership by the +coded `member_of`, and the evaluator counts the member in the team's care on +the next request. FerroEHR reads the kind by that code, never by the template +or a path. `careTeam` is immutable (RFC 7643 §2.2): a +Group never changes kind with its members in it. + +Creating a care-team Group, and every membership change of one, needs the +client's `write_care_relationship` grant in the CDR beside its +`scim_provision` grant; without it the request is refused `403` naming the +grant. The Group belongs to the provider the client acts for: its `GROUP` +carries a `member_of` relationship to the client's `acts_for` `ORGANISATION`, +written when the Group is created, so the grant's `provider` element names +that provider's identifier. A client that acts for no provider creates no +care-team Group (`403`). A membership from SCIM has no `time_validity`, since RFC 7643 has +none: it holds until the client removes the member or the Group. Plain +Groups, with `careTeam` left out or `false`, carry no care relationship and +need no grant. + +### Deprovisioning a team member + +A SCIM client deactivates or deletes a professional who holds care +relationships without the `write_care_relationship` grant. Revoking access +is never blocked: removing a leaver's access rights is a control that has to +work at once (ISO/IEC 27001:2022 Annex A 5.18), and neither request changes +what the care relationships say. + +- **Deactivation** (`active = false`, RFC 7643 §4.1.1) writes an `inactive` + version of the `PERSON` that keeps every care relationship, whoever wrote + it: the ADT system's rosters and the memberships of care-team Groups. Plain + Group memberships are dropped ([Groups](installation/config-scim.md#groups)). + **Reactivation** (`active = true`) restores the login, and the care + relationships are as they were. +- **Deletion** writes a logical `deleted` version of the `PERSON` and its + professional `ROLE`s (RM common §Logical Deletion). The earlier versions + stay, with the teams the professional belonged to, so the record still + answers "was this nurse on Ward 3 on that date". The User answers `404` + from then on (RFC 7644 §3.6). SCIM never erases the identity; only the + erasure process does, under the exemptions of GDPR Art. 17(3). + +The care check compares what each care relationship says (its kind, target +and `time_validity`), and each record subject the `PERSON` declares, in the +new version with the last version that holds a body. A lifecycle state is no relationship content, and a deletion holds no +body, so neither needs the grant. + +The login is refused on its next request on every replica, because each +request reads the binding with no cache: an inactive `PERSON` with +`refused-inactive`, and a login whose key only a deleted `PERSON` carried +with `refused-deprovisioned`. The access evaluator never sees the caller, so +the care relationships it would read do not matter. + +The ADT system writes no version of a deactivated `PERSON`: an `inactive` +version takes no update (RM common master06 §Version Lifecycle: editing +resumes only through `reactivate` or `retrieve`), and a roster cannot change +the lifecycle state, so such a write is refused `403` and the `PERSON` stays +`inactive`. That costs nothing: a deactivated person's memberships decide no +access, since the login is refused at binding. A leaver's roster is cleaned +up by the SCIM deletion, a logical `deleted` version that ends every +relationship while the earlier versions keep the history (master06 +§Logical Deletion), or by the ADT system after the User is reactivated. +Apart from the cited lifecycle rules, this section is FerroEHR's own design. + +## Representatives + +A parent, a guardian or a proxy the patient chose reads the patient's record +through an app as the patient's representative. Regulation (EU) +2025/327 Art. 4(2) asks for proxy services that let natural persons +authorise others to access their personal electronic health data on their +behalf, and let legal representatives access the data of the persons whose +affairs they administer, "in accordance with national law"; Member States +set the rules for both. Who represents whom, and until when, is therefore +data the deployment keeps in the CDR. FerroEHR builds in no country's rules. + +### The representation + +A representation is a `PARTY_RELATIONSHIP` of its own, written at +`POST /demographic/party_relationship` (FerroEHR's extension), from the +representative's `PERSON`, its source, to the subject's `PERSON`, its +target. Its `name` is `openehr_access::represents`, and its `details` hold +the elements of the `representation element` group, each named by its code: + +| Element | Occurrences | Value | +|---|---|---| +| `basis` | 1..1 | `DV_CODED_TEXT`: why the representative may act for the subject, a code of the value set the access policy binds for `representation_basis`, or of `HL7_RoleCode` (such as `GUARD`, `RESPRSN`, `DELEGATEE`) when it binds none | +| `provider` | 1..1 | `DV_IDENTIFIER` of type `ORGANISATION` with an `issuer` and an `id`: the healthcare provider for which the representation is recorded | +| `evidence` | 0..1 | `DV_IDENTIFIER`: the court order, register entry or written authorisation | + +Any archetype may model it; FerroEHR reads the codes, never the archetype +id. It may also name how the two are related with a `DV_CODED_TEXT` of the +openEHR `subject_relationship` group (`254|parent|`, `264|guardian|`), which +the committer and the access log carry. The shipped +`openEHR-DEMOGRAPHIC-PARTY_RELATIONSHIP.representation.v2` is an example. +A representation held in a `PERSON`'s `relationships` is refused `422`, +naming the resource to write it at, and so is one without a readable +`basis` or `provider`, or with a `basis` outside its value set. Each +representation is versioned on its own, with the commit audit of whoever +wrote it, and is ended by closing its `time_validity`. + +It holds while its `time_validity` covers today's date in UTC. These +callers write one: + +- an administrator; +- a caller holding a `write_representation` grant whose `provider` + elements name the representation's provider, before and after the write; + a grant that names no provider writes none; +- the patient it represents, on the basis `HL7_RoleCode::DELEGATEE` alone: + the patient authorises a proxy of their choice (EHDS Art. 4(2)). Any other + basis, such as a parent's or a court-appointed guardian's, is written by an + administrator or a `write_representation` holder. + +FerroEHR admits a representative only on a representation that is live on +the day of the request, whose `provider` is the provider the deployment acts +for (`[authz.party_binding.provider]`), and that the representative did not +write itself. A representative with no such representation is refused `403` +with `refused-representation-unrecorded`. The access record of +every admitted request names the representation's container, which the +access log's `representation` authorisation carries as its reference. + +The representative's `PERSON` is of a template +`[[authz.party_binding.person.template]]` maps and carries a binding key: a +`DV_IDENTIFIER` whose `issuer` is the `identifier_issuer` of the party table +of the issuer they sign in at, and whose `id` is their login there (their +`sub`). An administrator or an identity feed writes it through the +Demographic API; SCIM provisions a workforce only. The `PERSON` carries the +representative marker once it is the source of a representation, and no +professional `ROLE`. EHDS Art. 4(2) gives the authorisation to the patient +(a) and to the legal representative under national law (b), so the patient, +an administrator or a `write_representation` holder records it. + +### Legal capacity + +How old a minor must be before their parents no longer see their record, and +when someone may act for an adult, is national law. It reaches FerroEHR as +the representations the deployment records and the `time_validity` it gives +them: the deployment, or the national identity or authorisation service it +follows, ends a parent's representation on the date the child decides +alone, and ends or adds a representation when a court or the patient changes +who may act. FerroEHR checks only that a live representation for its +provider covers today, so a change is effective on the next request, and +holds no age band, no capacity rule, no country table and no archetype id of +its own (draft access control package, The Representation as a Stored +Fact). + +### Signing in + +A representative signs in at a trusted issuer one of two ways: + +- **As a `RelatedPerson`.** Their token's `fhirUser` is a `RelatedPerson` + (SMART App Launch 2.2.0, Scopes and Launch Context, `fhirUser`), and its + launch context names the patient's EHR (`ehrId`). +- **As a user whose `PERSON` is a representative's alone.** Their token + names no `RelatedPerson`, and their login binds a `PERSON` carrying the + representative marker and no professional `ROLE`. + +Either way FerroEHR binds the login, by the token's `sub` under its +issuer's party table, to the `PERSON` whose binding key it is, and admits +the request while that `PERSON` holds a live representation of the subject: +the subject of the launch EHR, else of the EHR the request names, else the +`PERSON` an EHR lookup by subject names. The request is confined to that +subject's EHRs, or to the launch EHR when the token names one. The +representation is read from the CDR, never from the token (EHDS Art. 4(2)). +A representative with no representation yet, one whose representation ended +or was deleted, and one who represents someone else are refused `403` with +`refused-representation-unrecorded`, so a former representative never becomes +the patient. A representative reaching their own record reaches it as the +person themself (EHDS Art. 3). The patient themself is the one whose login +is a binding key of the `PERSON` the EHR's subject names: the party binding +is the one source of own access, and the token's claims are never trusted on +their own. This is FerroEHR's own design. + +Each access is recorded bound to the representative's `PERSON`, naming the +subject they represent and the relationship (EHDS Annex II 3.2), and a commit +records the representative as a `PARTY_RELATED` committer. + +### The patient authorises a proxy + +The patient authorises a proxy with a `PARTY_RELATIONSHIP` of its own, from +the proxy's `PERSON` to their own: + +```sh +curl -X POST "$BASE/ferroehr/rest/extensions/v1/demographic/party_relationship" \ + -H "Authorization: Bearer $PATIENT_TOKEN" \ + -H 'Content-Type: application/json' \ + -d '{ + "_type": "PARTY_RELATIONSHIP", + "archetype_node_id": "openEHR-DEMOGRAPHIC-PARTY_RELATIONSHIP.representation.v1", + "archetype_details": { "_type": "ARCHETYPED", "rm_version": "1.1.0", + "archetype_id": { "_type": "ARCHETYPE_ID", "value": "openEHR-DEMOGRAPHIC-PARTY_RELATIONSHIP.representation.v1" } }, + "name": { "_type": "DV_CODED_TEXT", "value": "Authorised proxy", + "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "local" }, "code_string": "at12" } }, + "details": { "_type": "ITEM_TREE", "archetype_node_id": "id3", + "name": { "_type": "DV_TEXT", "value": "Details" }, + "items": [ + { "_type": "ELEMENT", "archetype_node_id": "id4", "name": { "_type": "DV_TEXT", "value": "Representation code" }, + "value": { "_type": "DV_CODED_TEXT", "value": "represents", + "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "represents" } } }, + { "_type": "ELEMENT", "archetype_node_id": "id6", "name": { "_type": "DV_TEXT", "value": "Relationship" }, + "value": { "_type": "DV_CODED_TEXT", "value": "unknown", + "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr" }, "code_string": "253" } } } ] }, + "time_validity": { "_type": "DV_INTERVAL", "lower": { "_type": "DV_DATE", "value": "2026-11-13" }, + "lower_unbounded": false, "upper_unbounded": true, "lower_included": true, "upper_included": false }, + "source": { "_type": "PARTY_REF", "namespace": "demographic", "type": "PERSON", + "id": { "_type": "HIER_OBJECT_ID", "value": "" } }, + "target": { "_type": "PARTY_REF", "namespace": "demographic", "type": "PERSON", + "id": { "_type": "HIER_OBJECT_ID", "value": "" } } + }' +``` + +The patient's own credential reaches the writes of +`/demographic/party_relationship`, and FerroEHR admits only a representation +whose target is the subject of the patient's launch EHR, before and after +the write. The committer is the patient, a `PARTY_IDENTIFIED` naming their +`PERSON`. The patient revokes the authorisation with +`DELETE /demographic/party_relationship/{uid}`, or ends it with a `PUT` whose +`time_validity` ends; the proxy's next request is refused. The patient +changes only a representation they inserted themself: one an administrator +recorded, such as a court-appointed guardian's, is the administrator's +(EHDS Art. 5). + +### Where this is our own design + +No openEHR specification governs these points; each is FerroEHR's own +design: + +- **A representation is recognised by its code**, as the acts-for + relationship is, so a deployment models it in any archetype. +- **Legal capacity is the recorded representations and their validity.** + The rules are national law (EHDS Art. 4(2)), so FerroEHR holds no rule of + its own. +- **A login binds by the token issuer.** The representative's binding key + is a `DV_IDENTIFIER` under the identifier issuer of the party table of the + issuer that signs their login. +- **A patient writes the representation of themselves**, and the party + protection holds them to it. diff --git a/website/book/src/capacity.md b/website/book/src/capacity.md index 577951af05..74fc2f0a2b 100644 --- a/website/book/src/capacity.md +++ b/website/book/src/capacity.md @@ -167,7 +167,7 @@ are held by the integration test `care_caseload_plans`; its figures are on A latency from a shared or virtualised host can carry more of the host than of FerroEHR. Every step records what it ran on, so a reader can tell, and -the harness has a way around each distortion measured in #5777. +the harness has a way around each distortion. **The path to the server.** The Podman VM on macOS forwards every published port, and the forwarder adds about 1.6 milliseconds to each request the @@ -313,13 +313,13 @@ cores approach what the host gives it while PostgreSQL has room, the server saturated; profile it with `capacity.sh profile`, which samples the server with `sample` on macOS or `perf record` on Linux. The server's own `/management/flamegraph` is not used while its unwinder can stop the server -inside an Ed25519 signature (#5723). When the pool's +inside an Ed25519 signature. When the pool's acquire time rises and the active backends sit at the pool size, the pool saturated. When one statement's total time grows faster than the rate, or backends wait on one lock, that statement or lock is the limit. ## Where the measurements are -The tracker issue of each run holds its result, with the hardware it ran on: -the first is #5722. A knee is a property of one deployment on one host, so +The tracker issue of each run holds its result, with the hardware it ran on. +A knee is a property of one deployment on one host, so the book publishes the method and never a figure without its host. diff --git a/website/book/src/care-relationships.md b/website/book/src/care-relationships.md index 68c0c8515a..7ed63480ea 100644 --- a/website/book/src/care-relationships.md +++ b/website/book/src/care-relationships.md @@ -17,8 +17,8 @@ EHR" (BASE Architecture Overview, Security, The Problem of Roles). FerroEHR therefore stores the outcome as a fact, the care relationship, and decides every access and every query on it. This page explains the model. The fields, the policy attributes and the refusals are in -[Caller facts: roles and care relationships](operational-policy.md#caller-facts-roles-and-care-relationships) -and [Care relationship facts](operational-policy.md#care-relationship-facts), +[Caller facts: roles and care relationships](caller-facts.md#caller-facts-roles-and-care-relationships) +and [Care relationship facts](access-policy.md#care-relationship-facts), and where care sits among the other steps of a decision is on [How FerroEHR decides access](explanation/access-model.md). diff --git a/website/book/src/compliance/claims-review.md b/website/book/src/compliance/claims-review.md index b185e45f16..dc3f65820e 100644 --- a/website/book/src/compliance/claims-review.md +++ b/website/book/src/compliance/claims-review.md @@ -189,7 +189,7 @@ the deployment posture too; it names `GET /management/status` now. - **FOSSA**: no text in scope names FOSSA, a FOSSA badge or a FOSSA lane after its removal in this release. - **The patient scope and `patient_namespace`**: the - [`[authz.abac]`](../security.md#a-patients-own-ehr) table and its + [`[authz.abac]`](../access-control.md#a-patients-own-ehr) table and its patient-scope list state the EHR-only queries, the direct-route refusals and the namespace rule as they ship; the [security](../security.md) page's fail-closed box is unchanged by them. @@ -201,7 +201,7 @@ the deployment posture too; it names `GET /management/status` now. sealed-identifier section, the operations guide and the admin API page state the per-version rows, the sealed write response, the plaintext refusal on import and load, and the erasure of sealed rows. -- **The audit chain**: the [audit trail](../audit.md#tamper-evidence) page +- **The audit chain**: the [audit trail](../audit-integrity.md#tamper-evidence) page states both digest versions and the downgrade finding. - **AQL**: [querying with AQL](../querying-aql.md) and the AQL engine concept page state the row rules and say AQL 1.1.0 does not define them. @@ -248,7 +248,7 @@ the dump and load archive on zip 9.0.4 (#3798). and the [server configuration](../installation/config-server.md#usage_report) table states the two variables. - **The dump and load archive**: the - [admin APIs](../operations-admin-apis.md#dump-and-load) page names no zip + [admin APIs](../storage-admin-apis.md#dump-and-load) page names no zip library and its `compression_format` values are unchanged. - **The README, `SECURITY.md`, the crate READMEs, the image labels and the Helm chart's description**: unchanged by this release, and none names the usage @@ -402,7 +402,7 @@ accepted by name. indefinite number of natural persons". The settings take role entries (`role:nurse`), so one entry covers a whole role, and the admin role can always reach the record to write them - ([per-EHR access control](../security.md#per-ehr-access-control-ehr_access)). + ([per-EHR access control](../access-control.md#per-ehr-access-control-ehr_access)). - **Restriction of processing.** A record under restriction is refused on every read path. The controller sets the mark under GDPR Art. 18; it is a restriction the organisation decides on, not one the software imposes diff --git a/website/book/src/compliance/cra-risk-assessment.md b/website/book/src/compliance/cra-risk-assessment.md index 4d5557d900..780b33d3a6 100644 --- a/website/book/src/compliance/cra-risk-assessment.md +++ b/website/book/src/compliance/cra-risk-assessment.md @@ -284,8 +284,8 @@ available updates to users, and the option to temporarily postpone them" - **Evidence:** [`SECURITY.md`](https://github.com/FerroHEALTH/FerroEHR/blob/main/SECURITY.md#supported-versions); `app/ferroehr/src/support.rs`; `app/ferroehr/src/banner.rs` (`banner_states_the_support_period`); - [how long a version is supported](../operations.md#how-long-the-version-you-pinned-is-supported); - [upgrades](../operations.md#upgrades). + [how long a version is supported](../upgrades.md#how-long-the-version-you-pinned-is-supported); + [upgrades](../upgrades.md). - **Status:** met for the security-update and notification limbs, with the notice delivered outside the product as stated above. - **Open:** none. @@ -346,8 +346,8 @@ transit by state of the art mechanisms, and by using other technical means" pseudonymisation domains on separate credentials, checked by `production`; secrets that never render; log sanitising. - **Evidence:** `[server.tls]` in `ferroehr.default.toml`; - [B1](../threat-model.md#b1--network-and-protocol), - [B6](../threat-model.md#b6--the-database), + [B1](../threat-model.md#b1-network-and-protocol), + [B6](../threat-model.md#b6-the-database), [national identifiers stay in the master patient index](../threat-model.md#national-identifiers-stay-in-the-master-patient-index), [the go-live checklist](../security/go-live-checklist.md#9-the-database-volumes-and-backups-are-encrypted-at-rest), [TLS and database security](../operations.md#tls-and-database-security). @@ -415,7 +415,7 @@ corruptions" `app/ferroehr/migrations/clinical/0010_baseline_grants.sql` and its party twin; `app/ferroehr/src/config/strict.rs`; - [tamper evidence](../audit.md#tamper-evidence); + [tamper evidence](../audit-integrity.md#tamper-evidence); [verifying releases](../verifying-releases.md). - **Status:** met. A signature failure on read is refused and logged. The server verifies the sealed windows of the system records and the access log one @@ -463,7 +463,7 @@ denial-of-service attacks" - **Evidence:** `app/ferroehr-rest/src/overload.rs`; `app/ferroehr-rest/src/rate_limit.rs`; `app/ferroehr-rest/src/limits.rs`; [request limits](../security.md#request-limits-and-rate-limiting); - [backup and recovery](../operations.md#backup-and-point-in-time-recovery). + [backup and recovery](../database-operations.md#backup-and-point-in-time-recovery). - **Status:** met. The residual risk is stated in the threat model: an authorised caller holding resources is not defended against, and the limiter is per process. @@ -552,7 +552,7 @@ to other products or systems, ensure that this is done in a secure manner" `app/ferroehr/tests/it/decommission.rs`; [decommissioning](../operations-decommissioning.md); [physical deletion](../operations-admin-apis.md#physical-deletion); - [dump and load](../operations-admin-apis.md#dump-and-load). + [dump and load](../storage-admin-apis.md#dump-and-load). - **Status:** met, shipped in #3642. The decommissioning page lists what the erase cannot reach and the deploying organisation removes: backups, WAL archives and replicas, the chart's Secrets and claims, the database roles, diff --git a/website/book/src/compliance/cra-user-information.md b/website/book/src/compliance/cra-user-information.md index e70cc67fb4..fe43af62ff 100644 --- a/website/book/src/compliance/cra-user-information.md +++ b/website/book/src/compliance/cra-user-information.md @@ -202,7 +202,7 @@ to be handled and to receive security updates;" notes, and the running server states it on its boot banner, in `ferroehr --version`, under `support` in `GET /management/info` and as `support.status` in `GET /management/status` - ([how long the version you pinned is supported](../operations.md#how-long-the-version-you-pinned-is-supported)). + ([how long the version you pinned is supported](../upgrades.md#how-long-the-version-you-pinned-is-supported)). A release itself is supported only while it is the newest. - **The type of support:** Cadasto B.V. handles vulnerabilities in FerroEHR, and the security update ships in the newest release, as a security-only @@ -264,7 +264,7 @@ data;" - **Upgrades.** A release can carry database migrations. They are append-only, and a rolling upgrade stays compatible with the previous schema for the window in which both versions run; take a backup first - ([upgrades](../operations.md#upgrades)). + ([upgrades](../upgrades.md)). - **Changes to the source.** A binary or image built from modified source is not a Cadasto B.V. release: its build provenance and signatures do not verify, and the risk assessment of the release does not describe it. @@ -281,9 +281,9 @@ Subscribe to the release feed security advisories; the server does not look for newer releases itself. Verify the new release ([verifying releases](../verifying-releases.md)), take a backup, then deploy it by digest and let it apply its migrations -([upgrades](../operations.md#upgrades)). On Kubernetes that is a +([upgrades](../upgrades.md)). On Kubernetes that is a `helm upgrade` to the chart version that ships the new release -([Kubernetes & Helm, upgrades](../installation/kubernetes.md#upgrades)). +([Kubernetes & Helm, upgrades](../upgrades.md#upgrading-the-helm-release)). ### 8(d) Secure decommissioning, and removing user data diff --git a/website/book/src/compliance/hazard-log.md b/website/book/src/compliance/hazard-log.md index 0583dff9aa..f415d267b4 100644 --- a/website/book/src/compliance/hazard-log.md +++ b/website/book/src/compliance/hazard-log.md @@ -44,7 +44,7 @@ retention register in `ferroehr::storage::marks`. The middleware is installed outermost on the API router, around the authentication layer, so it sees every response of the openEHR REST surface, refusals included. What each record holds, field by field against Annex II 3.2, is on the -[audit trail](../audit.md#the-ehds-logging-elements-mapped) page. +[audit trail](../ehds-logging.md#the-ehds-logging-elements-mapped) page. Test paths below are relative to the repository root. Each was read for this log; "no test" means none exists. @@ -301,7 +301,7 @@ unless accepted by name. **Remains:** a local store shares the fate of its database, so backups and an off-box sink are the deploying organisation's -([B7](../threat-model.md#b7--the-audit-trail)). +([B7](../threat-model.md#b7-the-audit-trail)). ## H6: a patient cannot read their log diff --git a/website/book/src/compliance/index.md b/website/book/src/compliance/index.md index 4246239c19..f23837e3a4 100644 --- a/website/book/src/compliance/index.md +++ b/website/book/src/compliance/index.md @@ -190,14 +190,14 @@ repository actually touches. | **Art. 4(5)** pseudonymisation: identifying data kept separately, under technical measures | Clinical and demographic data in two schemas under non-overlapping `NOINHERIT` roles, enforced by grants, by a boot-time self-check in both directions and by a check on every table; separated credentials and clusters are asserted by the `production` [deployment profile](../installation/configuration.md#deploymentprofile). The patient-to-EHR cross-reference lives outside the CDR by default, in an IHE patient identity source asked over PIXm ([`[pixm]`](../installation/config-integrations.md#pixm)), which mints the pseudonym; with the opt-in `subject_index = "local"` it is the EHR's own `EHR_STATUS.subject`. FerroEHR never resolves a pseudonym back to a person | shipped, [#3153](https://github.com/FerroHEALTH/FerroEHR/issues/3153), [#3158](https://github.com/FerroHEALTH/FerroEHR/issues/3158), [#3226](https://github.com/FerroHEALTH/FerroEHR/issues/3226), [#3380](https://github.com/FerroHEALTH/FerroEHR/issues/3380) | Run the production profile with the separations it asserts, run the identity source under its own controls, and hold any additional information the CDR never sees to the same standard | | **Art. 5(1)(f)** integrity and confidentiality | TLS 1.3 with optional mutual authentication, [authentication and authorization](../security.md), per-version digest [record.signing](../signing/index.md), a tamper-evident audit chain | shipped | Terminate TLS correctly, run the identity provider, hold the keys | | **Art. 5(1)(e)** storage limitation: data kept in identifying form no longer than the purposes need | A [retention register](retention.md#the-retention-register) of the period per content category and jurisdiction with the citation it rests on, a per-EHR anchor, and a view of what has run out. The repository deletes no clinical content on a timer: an openEHR record is indelible, so the register produces a list | shipped, [#3346](https://github.com/FerroHEALTH/FerroEHR/issues/3346) | Choose the periods, which follow from the law you run under and not from the software, and decide record by record what to do with the list | -| **Art. 5(2)** accountability: being able to demonstrate compliance | An audit trail of every access, [retrievable over ITI-81](../audit.md#retrieving-audit-records-iti-81), plus openEHR's own contribution and audit chain on every write | shipped | Keep the records, define retention, be able to produce them | -| **Art. 9** special categories of data | Object-level [`EHR_ACCESS`](../security.md#per-ehr-access-control-ehr_access) settings and the access evaluator, RBAC, and the domain-separated database roles | shipped | Establish the Art. 9(2) condition and the national derogation that permits the processing | +| **Art. 5(2)** accountability: being able to demonstrate compliance | An audit trail of every access, [retrievable over ITI-81](../audit-integrity.md#retrieving-audit-records-iti-81), plus openEHR's own contribution and audit chain on every write | shipped | Keep the records, define retention, be able to produce them | +| **Art. 9** special categories of data | Object-level [`EHR_ACCESS`](../access-control.md#per-ehr-access-control-ehr_access) settings and the access evaluator, RBAC, and the domain-separated database roles | shipped | Establish the Art. 9(2) condition and the national derogation that permits the processing | | **Art. 12(3)** action on a rights request within one month, by electronic means where the request came electronically | Every right in the rows below is served by an API call, so the record is read, exported, corrected or deleted in the run that answers the request | shipped | Start the clock at receipt, verify the requester's identity, and use the two-month extension only with the reasons 12(3) asks for | -| **Art. 15(1)** and **15(3)** access, and a copy of the data undergoing processing | The full record over the REST API in canonical openEHR JSON or XML, and [EHR Extract export](../beyond-core/messaging.md#exporting-an-ehr) for a whole record; the recipients 15(1)(c) asks about come from the [per-patient trail search](../audit.md#retrieving-audit-records-iti-81) | shipped | Supply what the software cannot know: the purposes of 15(1)(a) and the storage period of 15(1)(d) are your configuration and your retention schedule. Authenticate the requester and build the patient-facing route | +| **Art. 15(1)** and **15(3)** access, and a copy of the data undergoing processing | The full record over the REST API in canonical openEHR JSON or XML, and [EHR Extract export](../beyond-core/messaging.md#exporting-an-ehr) for a whole record; the recipients 15(1)(c) asks about come from the [per-patient trail search](../audit-integrity.md#retrieving-audit-records-iti-81) | shipped | Supply what the software cannot know: the purposes of 15(1)(a) and the storage period of 15(1)(d) are your configuration and your retention schedule. Authenticate the requester and build the patient-facing route | | **Art. 16** rectification, and completion by a supplementary statement | A correction commits a new version while the prior one stays in the append-only history, which is the supplementary statement the article allows for incomplete data | shipped | Decide what is inaccurate or incomplete, and reconcile the correction with the record-keeping duty your national law imposes | | **Art. 17(1)** erasure, subject to the grounds in **17(3)(b) to (d)** | `DELETE {base}/admin/ehr/{ehr_id}` ([physical deletion](../operations-admin-apis.md#physical-deletion)) removes, in one transaction, the EHR and everything it owns over both storage tiers: compositions, `EHR_STATUS`, item tags, folder memberships, contributions, every historical version, the restriction and retention marks and its change events. The externalized multimedia blobs no surviving version references are deleted from the object store, and an erasure tombstone on the change-event stream tells each consumer to delete what it derived (Art. 19). What stays is the audit trail naming the `ehr_id`, because Art. 17(3)(b) withholds erasure where processing is necessary for compliance with a legal obligation and the access-logging periods are that obligation | shipped, [#3347](https://github.com/FerroHEALTH/FerroEHR/issues/3347) | Decide whether a 17(3) ground refuses the request, a legal obligation, public health, or research under Art. 89(1), and record that decision. Backups, replicas and copies outside the CDR are reached by your own rotation, not by the call | | **Art. 18** restriction of processing, which Art. 4(3) defines as marking stored data to limit its future processing | A [restriction register](retention.md#restriction-of-processing) at two grains, a whole EHR or one versioned object in it: a marked object stays in storage and every path that would process it stops, the point read, the versioned read and the revision history with **403**, AQL at every scope, the EHR Extract, the event stream and any write. The register keeps the request and stamps it lifted, so the sequence 18(3) turns on survives. On a write the restriction is the last gate: content validation answers **422** and the preconditions outside the commit transaction answer **409**, because the mark is read inside that transaction so a concurrent lift is serialised with the write, so a refusal status names the gate that stopped the write rather than the state of the mark | shipped, [#3324](https://github.com/FerroHEALTH/FerroEHR/issues/3324) | Record the 18(1) ground on the request, hold the restriction in the systems around the CDR, and tell the subject before you lift it (18(3)) | -| **Art. 19** communicating a rectification, erasure or restriction to each recipient, and naming those recipients to the subject on request | Every read and export is an access record naming the agent, the patient, the action, the outcome and the time, so the recipient list is answerable from the [trail](../audit.md#retrieving-audit-records-iti-81) | shipped | Send the communications. The trail records who received data; it notifies nobody. How far back the recipient list reaches is your `retention`: the regulation sets no retention period for an access log | +| **Art. 19** communicating a rectification, erasure or restriction to each recipient, and naming those recipients to the subject on request | Every read and export is an access record naming the agent, the patient, the action, the outcome and the time, so the recipient list is answerable from the [trail](../audit-integrity.md#retrieving-audit-records-iti-81) | shipped | Send the communications. The trail records who received data; it notifies nobody. How far back the recipient list reaches is your `retention`: the regulation sets no retention period for an access log | | **Art. 20(1) and (2)** portability in a structured, commonly used and machine-readable format, and direct transmission where technically feasible | Canonical openEHR JSON and XML, the [simplified FLAT and STRUCTURED formats](../using-the-api/content-negotiation.md#simplified-formats-flat-and-structured), and the [EHR Extract](../beyond-core/messaging.md#exporting-an-ehr), which another openEHR system imports directly | shipped | Check the trigger before answering: 20(1)(a) reaches processing based on consent or on a contract, and 20(3) excludes processing for a task carried out in the public interest, which is the basis much care runs on | | **Art. 21(1)** objection, and **21(6)** objection to research processing under Art. 89(1) | A [research objection](retention.md#objection-to-research-processing) per EHR: while it stands, the record leaves every full-population query, every export and the event stream, the three surfaces a secondary-use consumer reads the repository through, while a query naming the `ehr_id` and a read for care are untouched. The public-interest override 21(6) admits is recorded beside it and says on whose authority | shipped, [#3325](https://github.com/FerroHEALTH/FerroEHR/issues/3325) | Weigh the compelling legitimate grounds 21(1) asks for, record the outcome, and carry the objection into the systems outside the CDR | | **Art. 25** data protection by design and by default | Deny-by-default authorization, an `EHR_ACCESS` default that can be set to restricted, audit on by default. The default that favours compatibility, the `open` per-EHR access default, stops a `production` deployment booting: it is a named gap (`open_ehr_access_default`) that the deployment either closes or accepts by name in `deployment.accepts`, which is then stated on every boot and on `/management/status` | shipped, [#3323](https://github.com/FerroHEALTH/FerroEHR/issues/3323) | Choose the restrictive settings, or record the decision to keep a compatibility default and carry it in `deployment.accepts` | @@ -231,9 +231,9 @@ the regulation's own final provisions rather than today. | Chapter | What FerroEHR ships | Tracker | What the deploying organisation must do | |---|---|---|---| -| **Chapter II**, primary use, including the patient's access to their data and to a record of who accessed it | An [access trail](../audit.md) of every read, write and refusal, searchable by patient and by agent, read for one patient through a [subject-scoped grant](../audit.md#retrieving-audit-records-iti-81), with the clinician's reason on every [justified access](../audit.md#justified-and-emergency-access) outside the care relationships and the emergency mark on an access in the patient's vital interests (Art. 11(5)), and the [Art. 8 restriction of access by health professionals](../security.md#restriction-of-access-by-health-professionals-ehds-art-8), under which restricted data reads as absent unless an emergency justification of the access policy is invoked with a reason, and the [Art. 5 rules for information a person inserts](../security.md#information-a-person-inserts-ehds-art-5): a commit under a `patient/` token is marked `PARTY_SELF` and may not alter a professional's version, and the [Art. 3(3) delayed access](../security.md#delayed-access-by-the-person-ehds-art-33), which holds newly registered data from the person until a professional releases it or the period ends. [Shared responsibility](shared-responsibility.md#ehds-chapter-ii-right-by-right) maps each Chapter II right to what FerroEHR provides and what stays with you | shipped, [#4350](https://github.com/FerroHEALTH/FerroEHR/issues/4350) for Art. 5, [#4351](https://github.com/FerroHEALTH/FerroEHR/issues/4351) for Art. 3(3); the Art. 10 opt-out is planned, [#4516](https://github.com/FerroHEALTH/FerroEHR/issues/4516) | Build the patient-facing access route on the subject-scoped grant and authenticate the person. Give the person's access service `patient/` scopes only, and clinicians' apps `user/` scopes. Record a restriction on the person's instruction through the admin route, write the justifications of your access policy, and have your EHR send the clinician's reason in `x-access-reason` | -| **Art. 3(3)**, a Member State's delay of the person's access to their data until a health professional has explained it | Off by default, so the access of Art. 3(1) is immediate. With [the access-delay register](../installation/config-auth.md#the-access-delay-register) on, a new composition of a configured category reads as absent to a patient-context request until a professional releases it or the configured limit passes; professionals read it as before, and placing, releasing and expiry of a hold are access records ([delayed access by the person](../security.md#delayed-access-by-the-person-ehds-art-33)) | shipped, [#4351](https://github.com/FerroHEALTH/FerroEHR/issues/4351) | Turn it on only where your Member State's rule provides for the delay, list the categories and set the period that rule names, and have a professional release each held result once it has been explained | -| **Chapter III**, EHR systems: a European interoperability software component and a European logging software component, with published technical documentation | The [EHDS readiness page](https://ferrohealth.eu/docs/ehds/readiness.html) maps every Annex II requirement to a status with its evidence, the [technical documentation](https://ferrohealth.eu/docs/ehds/technical-documentation.html) page maps the Annex III elements to the documentation tree, and the access trail records the logging component's elements ([audit](../audit.md#the-ehds-logging-elements-mapped)) | readiness shipped, [#3168](https://github.com/FerroHEALTH/FerroEHR/issues/3168), [#3169](https://github.com/FerroHEALTH/FerroEHR/issues/3169), [#3170](https://github.com/FerroHEALTH/FerroEHR/issues/3170), [#3171](https://github.com/FerroHEALTH/FerroEHR/issues/3171); the interoperability component is FerroBRIDGE's, and the exchange format waits on implementing acts under Article 15(1). From FerroBRIDGE 0.0.16 the bridge records each access of its FHIR facade itself, naming the natural person FerroEHR's record of the bridge's read cannot ([access through FerroBRIDGE](../audit.md#access-through-ferrobridges-fhir-facade)) | Configure the deployment as the [instructions for use](https://ferrohealth.eu/docs/ehds/instructions-for-use.html) say, and give FerroBRIDGE's facade an Audit Record Repository when you run it. The conformity assessment and the EU declaration are Cadasto B.V.'s as manufacturer of each release; a self-hosted deployment of an unmodified release does not make you the manufacturer | +| **Chapter II**, primary use, including the patient's access to their data and to a record of who accessed it | An [access trail](../audit.md) of every read, write and refusal, searchable by patient and by agent, read for one patient through a [subject-scoped grant](../audit-integrity.md#retrieving-audit-records-iti-81), with the clinician's reason on every [justified access](../ehds-logging.md#justified-and-emergency-access) outside the care relationships and the emergency mark on an access in the patient's vital interests (Art. 11(5)), and the [Art. 8 restriction of access by health professionals](../access-control.md#restriction-of-access-by-health-professionals-ehds-art-8), under which restricted data reads as absent unless an emergency justification of the access policy is invoked with a reason, and the [Art. 5 rules for information a person inserts](../access-control.md#information-a-person-inserts-ehds-art-5): a commit under a `patient/` token is marked `PARTY_SELF` and may not alter a professional's version, and the [Art. 3(3) delayed access](../access-control.md#delayed-access-by-the-person-ehds-art-33), which holds newly registered data from the person until a professional releases it or the period ends. [Shared responsibility](shared-responsibility.md#ehds-chapter-ii-right-by-right) maps each Chapter II right to what FerroEHR provides and what stays with you | shipped, [#4350](https://github.com/FerroHEALTH/FerroEHR/issues/4350) for Art. 5, [#4351](https://github.com/FerroHEALTH/FerroEHR/issues/4351) for Art. 3(3); the Art. 10 opt-out is planned, [#4516](https://github.com/FerroHEALTH/FerroEHR/issues/4516) | Build the patient-facing access route on the subject-scoped grant and authenticate the person. Give the person's access service `patient/` scopes only, and clinicians' apps `user/` scopes. Record a restriction on the person's instruction through the admin route, write the justifications of your access policy, and have your EHR send the clinician's reason in `x-access-reason` | +| **Art. 3(3)**, a Member State's delay of the person's access to their data until a health professional has explained it | Off by default, so the access of Art. 3(1) is immediate. With [the access-delay register](../installation/config-auth.md#the-access-delay-register) on, a new composition of a configured category reads as absent to a patient-context request until a professional releases it or the configured limit passes; professionals read it as before, and placing, releasing and expiry of a hold are access records ([delayed access by the person](../access-control.md#delayed-access-by-the-person-ehds-art-33)) | shipped, [#4351](https://github.com/FerroHEALTH/FerroEHR/issues/4351) | Turn it on only where your Member State's rule provides for the delay, list the categories and set the period that rule names, and have a professional release each held result once it has been explained | +| **Chapter III**, EHR systems: a European interoperability software component and a European logging software component, with published technical documentation | The [EHDS readiness page](https://ferrohealth.eu/docs/ehds/readiness.html) maps every Annex II requirement to a status with its evidence, the [technical documentation](https://ferrohealth.eu/docs/ehds/technical-documentation.html) page maps the Annex III elements to the documentation tree, and the access trail records the logging component's elements ([audit](../ehds-logging.md#the-ehds-logging-elements-mapped)) | readiness shipped, [#3168](https://github.com/FerroHEALTH/FerroEHR/issues/3168), [#3169](https://github.com/FerroHEALTH/FerroEHR/issues/3169), [#3170](https://github.com/FerroHEALTH/FerroEHR/issues/3170), [#3171](https://github.com/FerroHEALTH/FerroEHR/issues/3171); the interoperability component is FerroBRIDGE's, and the exchange format waits on implementing acts under Article 15(1). From FerroBRIDGE 0.0.16 the bridge records each access of its FHIR facade itself, naming the natural person FerroEHR's record of the bridge's read cannot ([access through FerroBRIDGE](../ehds-logging.md#access-through-ferrobridges-fhir-facade)) | Configure the deployment as the [instructions for use](https://ferrohealth.eu/docs/ehds/instructions-for-use.html) say, and give FerroBRIDGE's facade an Audit Record Repository when you run it. The conformity assessment and the EU declaration are Cadasto B.V.'s as manufacturer of each release; a self-hosted deployment of an unmodified release does not make you the manufacturer | | **Chapter IV**, secondary use, including **Art. 66(3)** (data in pseudonymised format, the means to reverse it held only by the access body or a trusted third party) | The [batch surface](secondary-use.md) FerroBRIDGE loads the OMOP CDM from, with the restriction and objection marks taking an EHR out of every batch and the purpose and data permit on every access record; [cohort queries across the pseudonymisation boundary](../querying-aql.md#cohort-queries-across-the-pseudonymisation-boundary) with small-cell suppression. Pseudonymisation for research happens in FerroBRIDGE; the CDR gates the data | shipped, [#3159](https://github.com/FerroHEALTH/FerroEHR/issues/3159), [#3379](https://github.com/FerroHEALTH/FerroEHR/issues/3379) | Deal with the health data access body; a CDR is not a data-holder's permit process. Have the secondary-use caller declare its purpose and permit | ## National law @@ -283,7 +283,7 @@ one that states requirements a piece of software meets directly. | Standard | What FerroEHR ships | Tracker | What the deploying organisation must do | |---|---|---|---| | **[NEN 7510-1](https://www.nen.nl/nen-7510-1-2024-nl-331311)** and **[7510-2](https://www.nen.nl/nen-7510-2-2024-nl-331314)**, the management system and its controls | Technical controls an ISMS can point at, documented per control with their residual risk | shipped | Run the ISMS and hold the [certification](https://www.nen.nl/certificatie-en-keurmerken-nen-7510); a product cannot be certified against a management-system standard | -| **[NEN 7512](https://www.nen.nl/nen-7512-2022-nl-297137)**, the trust basis for data exchange | Mutually authenticated TLS ([IHE ITI-19](../audit.md#node-authentication-iti-19-mutual-tls)), OAuth2 and OIDC with an [enterprise identity provider](../identity-providers.md), signed and verifiable [releases](../verifying-releases.md) | shipped | Agree the trust basis with each counterparty and operate the certificate estate | +| **[NEN 7512](https://www.nen.nl/nen-7512-2022-nl-297137)**, the trust basis for data exchange | Mutually authenticated TLS ([IHE ITI-19](../audit-integrity.md#node-authentication-iti-19-mutual-tls)), OAuth2 and OIDC with an [enterprise identity provider](../identity-providers.md), signed and verifiable [releases](../verifying-releases.md) | shipped | Agree the trust basis with each counterparty and operate the certificate estate | | **[NEN 7513](https://www.nen.nl/nen-7513-2018-nl-245399)**, logging actions on electronic patient records | An IHE ATNA trail that records every operation including refusals, in FHIR `AuditEvent` and DICOM PS3.15 form, hash-chained in the database and retrievable per patient | shipped | Map the recorded fields onto the standard's own list, set retention, and review the trail | ### Germany: BDSG, SGB V, GDNG and § 203 StGB @@ -313,7 +313,7 @@ health insurer or gematik, the row says so. | **SGB V § 339 Abs. 3 and 5, § 352, § 361**, access to the ePA and to prescriptions only with a professional credential, a verifiable log of who accessed which data and who authorised a delegated access, and a closed per-role matrix of read and write scopes | Role- and attribute-based authorization over the roles the identity provider asserts, and an access trail naming the agent, its roles, the patient, the action and the outcome, refusals included | shipped | Bind the identity provider to the HBA and SMC-B credentials; these sections bind access to the ePA itself, which the CDR is not, and the CDR encodes the § 352 matrix only as far as the roles reach it | | **SGB V §§ 346 to 348**, the duty to write treatment data into the patient's ePA, conditioned on the provider's system holding it in semantically and syntactically interoperable form, with discharge letters, laboratory and imaging reports named outright | Every record is structured against an openEHR template and served over the [REST API](../getting-started.md) and as an [EHR Extract](../beyond-core/messaging.md#exporting-an-ehr), so a hospital's data meets the condition that triggers the duty | shipped | Run the transport into the ePA: the connector, the telematics infrastructure and the information objects § 355 prescribes are outside the CDR | | **SGB V § 347 Abs. 1, 4 and 6, § 348 Abs. 3 to 6, § 353 Abs. 3 and 5**, every objection, consent and refusal ground recorded verifiably in the treatment documentation; genetic results only by the responsible physician on explicit consent | A consent, objection or refusal recorded as a composition is versioned, attributed and audited like every other entry; FerroEHR ships no dedicated consent register and no per-category export gate | shipped, as versioned content | Model the consent and objection records in your templates, and gate the ePA transfer on them in the transport | -| **SGB V § 309**, the telematics-infrastructure access log: attempted accesses as well as successful ones, who accessed which data, three years' retention and deletion on expiry, person-identifiable from 2030 | The trail records attempts and refusals with the agent and the object touched; the access policy's `log_retention` and the [retention reaper](../audit.md#retention-and-who-chooses-it) implement the period, and a [declared ceiling](retention.md#the-audit-trail-and-the-access-log-ceiling) with § 309 Abs. 1 as its provision makes a policy write that keeps the log longer, keep-forever included, a refusal | shipped, [#3346](https://github.com/FerroHEALTH/FerroEHR/issues/3346), [#5660](https://github.com/FerroHEALTH/FerroEHR/issues/5660) | This section binds the controllers of TI applications under § 307; a CDR outside the TI is not one. Declare the ceiling only if you are one, set the period you owe, and review the trail | +| **SGB V § 309**, the telematics-infrastructure access log: attempted accesses as well as successful ones, who accessed which data, three years' retention and deletion on expiry, person-identifiable from 2030 | The trail records attempts and refusals with the agent and the object touched; the access policy's `log_retention` and the [retention reaper](../ehds-logging.md#retention-and-who-chooses-it) implement the period, and a [declared ceiling](retention.md#the-audit-trail-and-the-access-log-ceiling) with § 309 Abs. 1 as its provision makes a policy write that keeps the log longer, keep-forever included, a refusal | shipped, [#3346](https://github.com/FerroHEALTH/FerroEHR/issues/3346), [#5660](https://github.com/FerroHEALTH/FerroEHR/issues/5660) | This section binds the controllers of TI applications under § 307; a CDR outside the TI is not one. Declare the ceiling only if you are one, set the period you owe, and review the trail | | **SGB V § 355**, interoperability of ePA content: international standards, the BfArM terminologies, a versioned terminology server | openEHR archetypes and templates as the content model, terminology bindings resolved at commit time against any FHIR R4B terminology server through [`[terminology]`](../installation/config-integrations.md), which is the interface gematik's terminology server exposes | shipped | Point `[terminology] url` at the server gematik runs and adopt the information objects the KBV publishes; the text names no serialization, and neither does this page | | **SGB V § 360 Abs. 16**, electronic prescription transport outside the telematics infrastructure is prohibited | Nothing, and nothing planned: the CDR carries no prescription transport | not planned | Run prescriptions through the TI | | **GDNG § 6**, a provider's own patient data reprocessed for quality assurance, research and statistics: pseudonymised, anonymised as soon as possible, under a rights-and-roles concept with logging, deleted after thirty years at the latest, and disclosable to the subject by kind, scope and concrete purpose | Per-domain roles that keep a research credential off the identifying data, [cohort queries](../querying-aql.md#cohort-queries-across-the-pseudonymisation-boundary) named by a digest of their predicates and withheld under a small-cell threshold, an access record per query carrying the deployment's declared `purpose` and `legal_basis`, and the [retention register](retention.md#the-retention-register) as where the thirty-year limit for the repository's own copies is written down and read back | shipped, [#3159](https://github.com/FerroHEALTH/FerroEHR/issues/3159), [#3346](https://github.com/FerroHEALTH/FerroEHR/issues/3346); research pseudonyms are made in FerroBRIDGE, which loads the research database ([Secondary use](secondary-use.md)) | Write the rights-and-roles concept, publish the purposes, run the thirty-year clock against the register, and answer subjects' requests from the trail | @@ -342,14 +342,14 @@ binds a community or the identity issuers, the row says so. |---|---|---|---| | **DSG Art. 7**, data protection by design and by default: processing arranged from the planning stage so the Art. 6 principles hold, and defaults that limit processing to the minimum | Deny-by-default [authorization](../security.md#authorization), tenancy that fails closed, audit on by default, and a `production` [deployment profile](../installation/configuration.md#deploymentprofile) that refuses to start while a separation is missing | shipped | Choose the restrictive settings. Two defaults favour compatibility instead: the per-EHR access default is `open`, and the audit fail mode is `open` | | **DSG Art. 8 and DSV Art. 2 and 3**, the minimum security measures: need-to-know access control, storage and transport control, restoration, malfunction reporting, system security, entry control, disclosure control, breach detection | Role- and attribute-based [authorization](../security.md#authorization) and per-EHR `EHR_ACCESS`; one database role per domain; TLS 1.3 with optional mutual authentication; health and readiness endpoints; a locked, advisory-gated dependency set and [signed releases](../verifying-releases.md); every write attributed and versioned; an [access trail](../audit.md) naming who read what, refusals included | shipped | Run the backup and restore path, patch on the release cadence, and detect breaches from the trail and the metrics; the DSV names the controls, the deployment supplies everything below the application | -| **DSV Art. 4 Abs. 1, 4 and 5**, logging for large-scale processing of sensitive data: storing, changing, disclosing, deleting, destroying and reading, each entry with the actor, the kind, the date, the time and the recipient, kept at least one year separately from the processing system and readable only by the oversight roles | The trail records every operation including reads and refusals with the agent, the patient, the action, the outcome and the time, in a dedicated `audit` schema retrievable by an admin caller only, with [forwarding sinks](../audit.md#getting-the-log-out) (syslog, IHE ITI-20) that put a copy outside the system; the access policy's `log_retention` sets the period. The separation Abs. 5 asks for is the deployment's DSN choice, and the server reports on it: the audit pool's own cluster is read at boot like every other domain's, so an audit database sharing a cluster with a pseudonymisation domain is a `shared_cluster` gap on `/management/status` rather than an invisible co-location | shipped for the trail and the posture reading; the separation itself is the deployment's, [#3398](https://github.com/FerroHEALTH/FerroEHR/issues/3398) | Forward the trail to a repository outside the CDR, declare the one-year floor of DSV Art. 4 Abs. 5 in the access policy with `in_union` false, which then refuses a shorter period, and restrict who may read it, [#3319](https://github.com/FerroHEALTH/FerroEHR/issues/3319), [#5660](https://github.com/FerroHEALTH/FerroEHR/issues/5660) | +| **DSV Art. 4 Abs. 1, 4 and 5**, logging for large-scale processing of sensitive data: storing, changing, disclosing, deleting, destroying and reading, each entry with the actor, the kind, the date, the time and the recipient, kept at least one year separately from the processing system and readable only by the oversight roles | The trail records every operation including reads and refusals with the agent, the patient, the action, the outcome and the time, in a dedicated `audit` schema retrievable by an admin caller only, with [forwarding sinks](../ehds-logging.md#getting-the-log-out) (syslog, IHE ITI-20) that put a copy outside the system; the access policy's `log_retention` sets the period. The separation Abs. 5 asks for is the deployment's DSN choice, and the server reports on it: the audit pool's own cluster is read at boot like every other domain's, so an audit database sharing a cluster with a pseudonymisation domain is a `shared_cluster` gap on `/management/status` rather than an invisible co-location | shipped for the trail and the posture reading; the separation itself is the deployment's, [#3398](https://github.com/FerroHEALTH/FerroEHR/issues/3398) | Forward the trail to a repository outside the CDR, declare the one-year floor of DSV Art. 4 Abs. 5 in the access policy with `in_union` false, which then refuses a shorter period, and restrict who may read it, [#3319](https://github.com/FerroHEALTH/FerroEHR/issues/3319), [#5660](https://github.com/FerroHEALTH/FerroEHR/issues/5660) | | **DSG Art. 12 and DSV Art. 24**, the register of processing activities, from which large-scale processing of sensitive data has no small-organisation exemption | The effective configuration as a redacted JSON tree at `GET /ferroehr/rest/extensions/v1/admin/config`, [records of processing](../security/records-of-processing.md) pre-filled with what the software does, and the retention and security-measure inputs Art. 12 Abs. 2 lit. e and f ask for | shipped | Write and maintain the register; the software cannot know your purposes or recipients | | **DSG Art. 22 Abs. 2 lit. a**, a data protection impact assessment before large-scale processing of sensitive data | The [DPIA page](../security/dpia.md) with the processing description, the data categories per schema, the roles, the retention, a risk register and the shipped controls by issue | shipped, [#3161](https://github.com/FerroHEALTH/FerroEHR/issues/3161) | Run the assessment; it is the controller's. Art. 22 Abs. 5 lets a private controller skip it for a system certified under Art. 13, and FerroEHR holds no such certification | | **DSG Art. 24**, notifying the EDÖB of a breach as soon as possible, with its kind, consequences and measures | The evidence a notification is written from: the trail with refusals attributed to the caller, the hash chain that shows tampering, the boot-time domain self-check | shipped | Detect, assess and notify; nothing in the software sends a notification | -| **DSG Art. 25 Abs. 2, 3 and 7, DSV Art. 16 and 18**, the right of access within 30 days: the data themselves, the purpose, the retention, the provenance and the recipients, in an understandable form, health data deliverable through a designated health professional | The full record over the openEHR REST API and as an [EHR Extract](../beyond-core/messaging.md#exporting-an-ehr), a [per-patient search of the trail](../audit.md#retrieving-audit-records-iti-81) that answers who received the data, and the [retention register](retention.md#the-retention-register), which is where the Abs. 2 lit. d answer, the retention period or the criteria that fix it, is read from rather than recalled | shipped, [#3346](https://github.com/FerroHEALTH/FerroEHR/issues/3346) | Identify the requester (DSV Art. 16 Abs. 5), render the answer in an understandable form, route it to the patient or the designated professional, and meet the 30 days | +| **DSG Art. 25 Abs. 2, 3 and 7, DSV Art. 16 and 18**, the right of access within 30 days: the data themselves, the purpose, the retention, the provenance and the recipients, in an understandable form, health data deliverable through a designated health professional | The full record over the openEHR REST API and as an [EHR Extract](../beyond-core/messaging.md#exporting-an-ehr), a [per-patient search of the trail](../audit-integrity.md#retrieving-audit-records-iti-81) that answers who received the data, and the [retention register](retention.md#the-retention-register), which is where the Abs. 2 lit. d answer, the retention period or the criteria that fix it, is read from rather than recalled | shipped, [#3346](https://github.com/FerroHEALTH/FerroEHR/issues/3346) | Identify the requester (DSV Art. 16 Abs. 5), render the answer in an understandable form, route it to the patient or the designated professional, and meet the 30 days | | **DSG Art. 28 and DSV Art. 21**, data portability in a common electronic format that another controller can reuse | Canonical openEHR JSON and XML, the simplified FLAT and STRUCTURED formats, and the EHR Extract, all published open formats | shipped | Decide which data are subject-provided or observed and which are derived (DSV Art. 20 Abs. 2), and export accordingly | | **DSG Art. 6 Abs. 4 and Art. 31 Abs. 2 lit. e**, destruction or anonymisation once the purpose lapses, and research on the condition that data are anonymised as soon as the purpose allows, with measures against identifiability meanwhile | Clinical and demographic data in separate schemas under separate roles, [cohort queries](../querying-aql.md#cohort-queries-across-the-pseudonymisation-boundary) with small-cell suppression, admin deletion and archival of a record, and the [retention register](retention.md#the-retention-register) that says when a purpose has lapsed and lists what is due | shipped, [#3158](https://github.com/FerroHEALTH/FerroEHR/issues/3158), [#3159](https://github.com/FerroHEALTH/FerroEHR/issues/3159), [#3346](https://github.com/FerroHEALTH/FerroEHR/issues/3346); research pseudonyms are made in FerroBRIDGE, which loads the research database ([Secondary use](secondary-use.md)) | Set the retention the cantonal health law requires, decide when anonymisation is possible, and hold the research ground | -| **EPDG Art. 9 and 10, EPDV Art. 1 to 4, 10 and 12, EPDV-EDI Anhang 5**, the EPD: three confidentiality levels and grantable access rights, emergency access with notification of the patient, every processing logged and the logs kept ten years, EPD data stored separately and encrypted, data stores in Switzerland, and the IHE profiles a community speaks (ATNA with Record Audit Event ITI-20 and Authenticate Node ITI-19, CH:ATC with Retrieve ATNA Audit Event ITI-81, IUA, XUA, XDS, MHD) | What a community integration consumes: [IHE ATNA](../audit.md) audit events over ITI-20 with [ITI-19 mutual TLS](../audit.md#node-authentication-iti-19-mutual-tls) and ITI-81 retrieval, the record in published formats, a self-hosted deployment with no dependency outside the operator's control, and the [retention register](retention.md) for Art. 10's twenty-year destruction, with the per-object hold Abs. 2 lit. b asks for | shipped, [#3346](https://github.com/FerroHEALTH/FerroEHR/issues/3346); an emergency access is [recorded with its reason in the access log](../audit.md#justified-and-emergency-access) and lifts only what the access policy's emergency justification allows, and FerroEHR notifies no one; it encrypts no field, so encryption at rest is the database's and the disk's | These provisions bind the certified community, which the CDR is not. Feed the EPD through a community's access point, place the data stores in Switzerland, and carry the confidentiality level on each document you contribute | +| **EPDG Art. 9 and 10, EPDV Art. 1 to 4, 10 and 12, EPDV-EDI Anhang 5**, the EPD: three confidentiality levels and grantable access rights, emergency access with notification of the patient, every processing logged and the logs kept ten years, EPD data stored separately and encrypted, data stores in Switzerland, and the IHE profiles a community speaks (ATNA with Record Audit Event ITI-20 and Authenticate Node ITI-19, CH:ATC with Retrieve ATNA Audit Event ITI-81, IUA, XUA, XDS, MHD) | What a community integration consumes: [IHE ATNA](../audit.md) audit events over ITI-20 with [ITI-19 mutual TLS](../audit-integrity.md#node-authentication-iti-19-mutual-tls) and ITI-81 retrieval, the record in published formats, a self-hosted deployment with no dependency outside the operator's control, and the [retention register](retention.md) for Art. 10's twenty-year destruction, with the per-object hold Abs. 2 lit. b asks for | shipped, [#3346](https://github.com/FerroHEALTH/FerroEHR/issues/3346); an emergency access is [recorded with its reason in the access log](../ehds-logging.md#justified-and-emergency-access) and lifts only what the access policy's emergency justification allows, and FerroEHR notifies no one; it encrypts no field, so encryption at rest is the database's and the disk's | These provisions bind the certified community, which the CDR is not. Feed the EPD through a community's access point, place the data stores in Switzerland, and carry the confidentiality level on each document you contribute | | **EPDV Art. 5 and 7, EPDV-EDI Anhang 1**, the patient identification number (eighteen digits with a published check digit, entered manually only under a check-digit control, never a source of inference about the patient) | FerroEHR holds the number as an opaque value and reads no value's shape, so it neither checks nor detects it in clinical content ([#6081](https://github.com/FerroHEALTH/FerroEHR/issues/6081)); the one-year access-log floor of DSV Art. 4 Abs. 5 is enforced once the controller declares it in the access policy | shipped, [#3319](https://github.com/FerroHEALTH/FerroEHR/issues/3319) | Treat the number as opaque, and keep it out of clinical content in your templates and feeds | ## Where to go next diff --git a/website/book/src/compliance/intended-purpose.md b/website/book/src/compliance/intended-purpose.md index e68a3bd9f2..097f3c3985 100644 --- a/website/book/src/compliance/intended-purpose.md +++ b/website/book/src/compliance/intended-purpose.md @@ -136,7 +136,7 @@ semi-trusted actor. available) or by an ingress or proxy in front of it. The shipped default leaves `[server.tls]` unset; the hop behind a proxy is the deploying organisation's, and the server cannot see whether it is encrypted - ([B1 network and protocol](../threat-model.md#b1--network-and-protocol), + ([B1 network and protocol](../threat-model.md#b1-network-and-protocol), [server configuration](../installation/config-server.md)). - **An identity provider.** Users and their credentials live in the deploying organisation's OpenID Connect provider, which issues the tokens FerroEHR @@ -150,10 +150,10 @@ semi-trusted actor. restricted to the server, with TLS to the database, encryption at rest at the volume layer, and backups taken per domain. Anyone with a database connection is past every API control - ([B6 the database](../threat-model.md#b6--the-database), - [database roles](../operations.md#database-roles-and-least-privilege), + ([B6 the database](../threat-model.md#b6-the-database), + [database roles](../database-operations.md#database-roles-and-least-privilege), [TLS and database security](../operations.md#tls-and-database-security), - [backup and recovery](../operations.md#backup-and-point-in-time-recovery)). + [backup and recovery](../database-operations.md#backup-and-point-in-time-recovery)). - **The platform.** A hardened cluster or host, operators the organisation trusts, and network policy around the instance ([cluster hardening](../installation/kubernetes-hardening.md): @@ -164,7 +164,7 @@ semi-trusted actor. [secrets, detection and response](../installation/hardening-detection-response.md)). - **Off-box copies.** A forwarding sink for the access log that the server's identity cannot rewrite, and a monitored backup - ([B7 the audit trail](../threat-model.md#b7--the-audit-trail)). + ([B7 the audit trail](../threat-model.md#b7-the-audit-trail)). ## Reasonably foreseeable use and misuse @@ -189,11 +189,11 @@ Foreseeable misuse, and what FerroEHR does about it: | The quickstart Compose file in production, with its development user and RBAC off | the README and the Compose file call these development defaults; `production` refuses RBAC off unless `rbac_off` is accepted by name | nothing refuses it under `sandbox`; the [go-live checklist](../security/go-live-checklist.md) is the control | | `auth.enabled = false` on a reachable network | `production` refuses it at boot unless `auth_off` is accepted by name (#3638) | an accepted gap is stated on every boot; the `sandbox` profile does not refuse it | | A plaintext listener on a routable address with no TLS ingress in front | `production` refuses it at boot unless `plaintext_listener` is accepted by name; a loopback bind is exempt (#3638); a separate management listener (`management.listen`), which binds every interface in plain HTTP, opens the same gap (#3668) | a deployment behind a TLS-terminating ingress accepts `plaintext_listener`, and nothing checks that the ingress exists or that the management port is unreachable off the host | -| Several organisations in one instance | no tenant model exists to misconfigure; one instance per organisation is documented | nothing in the software can detect it ([B5](../threat-model.md#b5--instance-separation)) | +| Several organisations in one instance | no tenant model exists to misconfigure; one instance per organisation is documented | nothing in the software can detect it ([B5](../threat-model.md#b5-instance-separation)) | | Real patient data on the public sandbox | the sandbox is labelled as demo data and wiped nightly | nothing refuses it | | The access log switched off in production | `production` refuses `audit_off` unless it is accepted by name; with the log on, an access whose record cannot be written is refused | an accepted gap is stated on every boot, and the organisation owns it | | The access log shipped over plaintext syslog | the syslog feed sends over RFC 5425 TLS only, through `ihe-atna` (#3887) | none for the feed; the repository's own TLS configuration is the deployment's | -| Reads and writes straight against the database | the domain roles limit what each credential reaches | such access bypasses authorisation and the access log ([B6](../threat-model.md#b6--the-database)) | +| Reads and writes straight against the database | the domain roles limit what each credential reaches | such access bypasses authorisation and the access log ([B6](../threat-model.md#b6-the-database)) | | Structural validation taken for clinical correctness | validation checks structure, invariants and terminology bindings only | clinical governance is the organisation's ([threat model](../threat-model.md#what-is-explicitly-not-defended-against)) | | openEHR conformance results, or these pages, taken for regulatory conformity | the [compliance overview](index.md) says FerroEHR holds no certification or declaration | none | | A release run after a newer one is published | only the newest release is supported (`SECURITY.md`), and the release feed and advisories announce each new one; the end month of the five-year commitment is in every release's notes and the running server states it on the boot banner, in `ferroehr --version`, on `GET /management/info` and `GET /management/status`, and logs a warning at boot and daily once it has passed (#3639) | nothing refuses to run; the server does not look for newer releases | diff --git a/website/book/src/compliance/logging-checklist.md b/website/book/src/compliance/logging-checklist.md index 1aaab0252a..e2878a0ca7 100644 --- a/website/book/src/compliance/logging-checklist.md +++ b/website/book/src/compliance/logging-checklist.md @@ -33,10 +33,10 @@ Audit Record Repository; the row then names the component. | Item | EHDS | Evidence | State | |---|---|---|---| -| `log-UserAccess`: per access by a health professional or other user, the healthcare provider, the natural person, the categories of data, the time and date and the origin of the data | Annex II 3.2(a) to (e), Art. 9(1) | One access record per access, written before the response leaves; the five elements field by field on [the EHDS logging elements, mapped](../audit.md#the-ehds-logging-elements-mapped). Tests: `app/ferroehr/tests/it/audit_ehds_mapping.rs` (`element_a_the_accessing_organisation_is_recorded_and_rendered_in_fhir`, `element_b_the_person_who_accessed_is_recorded_and_rendered`, `element_c_the_priority_category_is_recorded_and_rendered_in_fhir_only`, `element_d_the_time_of_access_is_recorded_and_rendered`, `element_e_the_origin_of_the_data_is_recorded_and_rendered_in_fhir`); `app/ferroehr-rest/tests/it/audit_route_coverage.rs` (`every_route_writes_exactly_one_access_record`); `app/ferroehr-rest/tests/it/audit_e2e.rs` (`a_request_whose_record_cannot_be_written_is_refused`) | Evidenced | +| `log-UserAccess`: per access by a health professional or other user, the healthcare provider, the natural person, the categories of data, the time and date and the origin of the data | Annex II 3.2(a) to (e), Art. 9(1) | One access record per access, written before the response leaves; the five elements field by field on [the EHDS logging elements, mapped](../ehds-logging.md#the-ehds-logging-elements-mapped). Tests: `app/ferroehr/tests/it/audit_ehds_mapping.rs` (`element_a_the_accessing_organisation_is_recorded_and_rendered_in_fhir`, `element_b_the_person_who_accessed_is_recorded_and_rendered`, `element_c_the_priority_category_is_recorded_and_rendered_in_fhir_only`, `element_d_the_time_of_access_is_recorded_and_rendered`, `element_e_the_origin_of_the_data_is_recorded_and_rendered_in_fhir`); `app/ferroehr-rest/tests/it/audit_route_coverage.rs` (`every_route_writes_exactly_one_access_record`); `app/ferroehr-rest/tests/it/audit_e2e.rs` (`a_request_whose_record_cannot_be_written_is_refused`) | Evidenced | | `log-APIAccess`: per access through the API, the accessing EHR system, the categories, the time and date and the origin | Annex II 3.2 | The client application is the record's `principal` in `client` mode and its own agent in the FHIR `AuditEvent`, beside the person it acts for. Tests: `app/ferroehr-rest/tests/it/caller_kinds_http.rs` (`a_system_callers_records_carry_its_client_and_provider`, `a_system_clients_write_and_read_are_recorded_under_one_client_identity`); `app/ferroehr/tests/it/audit_ehds_mapping.rs` (`element_b_the_professional_behind_a_client_is_recorded_and_rendered`); `app/ferroehr-rest/tests/it/exchanged_patient_token_http.rs` (`the_access_record_names_the_patient_the_client_and_the_level`); categories, time and origin by the tests of the row above | Evidenced | | `log-UserID`: unambiguous electronic identification of each end user | Annex II 3.1, 3.2(b), Art. 16(1) | FerroSMART signs the person in at an eIDAS-recognised eID and carries the level of assurance in the token (FerroHEALTH/FerroSMART#784). FerroEHR checks the level on every request for patient data against `[authz.assurance]` and records it with the person ([assurance level and the natural person](../security.md#assurance-level-and-the-natural-person-on-patient-data)). Tests: `app/ferroehr-rest/tests/it/patient_data_assurance.rs` (`a_token_below_the_minimum_gets_the_step_up_challenge`, `a_delegate_acting_for_a_professional_passes_and_is_recorded`); `app/ferroehr/tests/it/audit_ehds_mapping.rs` (`the_assurance_level_is_recorded_and_reaches_the_fhir_rendering_as_a_level`) | Evidenced | -| `log-Review`: tools to review and analyse the log, or support for external ones | Annex II 3.3, Art. 9(2) | ITI-81 `GET /fhir/r4/AuditEvent` searches the local store by patient, agent, action and date, and a `read_subject_audit` grant reads one subject's records ([retrieving audit records](../audit.md#retrieving-audit-records-iti-81)); the access log is also served over ITS-REST and AQL ([reading the access log](../audit.md#reading-the-access-log-over-its-rest)). The family's Audit Record Repository with the Retrieve Audit Message option shipped in FerroHEALTH/FerroAUDIT#278. Tests: `app/ferroehr-rest/tests/it/audit_iti81.rs` (`searchset_bundle_with_filters_and_paging`, `a_subject_audit_grant_reads_one_subjects_log_and_nothing_else`); `app/ferroehr-rest/tests/it/access_log_http.rs` (`a_read_of_the_log_writes_an_entry_naming_the_log`) | Evidenced | +| `log-Review`: tools to review and analyse the log, or support for external ones | Annex II 3.3, Art. 9(2) | ITI-81 `GET /fhir/r4/AuditEvent` searches the local store by patient, agent, action and date, and a `read_subject_audit` grant reads one subject's records ([retrieving audit records](../audit-integrity.md#retrieving-audit-records-iti-81)); the access log is also served over ITS-REST and AQL ([reading the access log](../access-log.md#reading-the-access-log-over-its-rest)). The family's Audit Record Repository with the Retrieve Audit Message option shipped in FerroHEALTH/FerroAUDIT#278. Tests: `app/ferroehr-rest/tests/it/audit_iti81.rs` (`searchset_bundle_with_filters_and_paging`, `a_subject_audit_grant_reads_one_subjects_log_and_nothing_else`); `app/ferroehr-rest/tests/it/access_log_http.rs` (`a_read_of_the_log_writes_an_entry_naming_the_log`) | Evidenced | | `log-interoperability` (should): a standard format and exchange for the log | Annex II 3.3 | Every record renders as an IHE BALP FHIR `AuditEvent` and as a DICOM PS3.15 audit message, sent over the ITI-20 syslog and FHIR feeds ([sinks](../audit.md#sinks)); the check of the BALP mapping against the D8.2 and D5.2 fields shipped in FerroHEALTH/FerroAUDIT#279. Tests: `app/ferroehr/src/system_log/fhir/tests.rs` (`dicom_and_fhir_agree_on_the_data_flow_direction`, `query_record_carries_the_origins_of_the_served_data`); `app/ferroehr/tests/it/audit_feed.rs` (`arr_outage_leaves_rows_pending_then_delivers_on_recovery`) | Evidenced | ## Checklist items outside automated testing @@ -48,7 +48,7 @@ Audit Record Repository; the row then names the component. | `Gen-Documentation`: detailed installation and configuration documentation for the operator | Annex II 1.2, Art. 37, Art. 38 | This book: [installation](../installation/index.md), the [configuration reference](../installation/configuration.md), [operations](../operations.md) and [decommissioning](../operations-decommissioning.md); the [instructions for use](https://ferrohealth.eu/docs/ehds/instructions-for-use.html) and the [information sheet](https://ferrohealth.eu/docs/ehds/information-sheet.html) in the FerroHEALTH book | Evidenced | | `gen-performanceSafety`: in normal use, the component does not prevent the intended purpose, impact performance meaningfully or put patient safety at risk | Annex II 1.1 | The [hazard log](hazard-log.md) states each hazard with its control and test, and the [intended performance](logging-performance.md) states the latency, throughput and completeness claims that `scripts/perf/audit-verdict.sh` checks on every release candidate | Evidenced | | `gen-noUndueBurden`: no feature that prohibits, restricts or burdens authorised access, sharing or use | Annex II 2.5 | The openEHR ITS-REST API in full, measured by the [conformance](../conformance.md) record of every release. The licence gates no feature, endpoint or limit (`app/ferroehr/src/licence/mod.rs`, [licensing](../licensing.md)). The Annex II 2.5 re-assessment is on the [claims review](claims-review.md) | Evidenced | -| `gen-SystemReplacement`: authorised export of the stored data for replacing the system, in reasonable time and without impediment | Annex II 2.6 | The whole repository leaves as an archive in canonical JSON or canonical XML, standalone parties included, and loads back ([dump and load](../operations-admin-apis.md#dump-and-load)); one EHR leaves as an openEHR EHR Extract ([exporting an EHR](../beyond-core/messaging.md#exporting-an-ehr)), and the capacity run measures the EHR export ([capacity](../capacity.md)). Tests: `app/ferroehr/tests/it/service_dump_load.rs` (`export_then_load_into_fresh_db_round_trips_byte_equal`, `the_canonical_xml_archive_holds_original_version_documents_under_the_published_root`) | Evidenced | +| `gen-SystemReplacement`: authorised export of the stored data for replacing the system, in reasonable time and without impediment | Annex II 2.6 | The whole repository leaves as an archive in canonical JSON or canonical XML, standalone parties included, and loads back ([dump and load](../storage-admin-apis.md#dump-and-load)); one EHR leaves as an openEHR EHR Extract ([exporting an EHR](../beyond-core/messaging.md#exporting-an-ehr)), and the capacity run measures the EHR export ([capacity](../capacity.md)). Tests: `app/ferroehr/tests/it/service_dump_load.rs` (`export_then_load_into_fresh_db_round_trips_byte_equal`, `the_canonical_xml_archive_holds_original_version_documents_under_the_published_root`) | Evidenced | Each item names its evidence, and no item is a gap. The checklist is read again with the hazard log, in the release that changes any module of the diff --git a/website/book/src/compliance/retention.md b/website/book/src/compliance/retention.md index 8fe6cdab17..8c17689c0b 100644 --- a/website/book/src/compliance/retention.md +++ b/website/book/src/compliance/retention.md @@ -9,8 +9,8 @@ FerroEHR carries them as its own extension and this page is where they are written down. Nothing here deletes anything. A record in an openEHR repository is indelible -by design — a deletion commits a new version whose content is removed, and the -history stays — so a retention period in FerroEHR produces a **list**, and +by design: a deletion commits a new version whose content is removed, and the +history stays, so a retention period in FerroEHR produces a **list**, and acting on that list is the controller's decision, taken record by record and carried out through [physical deletion](../operations-admin-apis.md#physical-deletion). @@ -43,7 +43,7 @@ on one, the citation, when the period expired, and two counts: the objects that and the objects exempted by a per-object hold. Ship the register empty and declare the periods your organisation is subject -to. The periods are not the software's to choose — they follow from the law the +to. The periods are not the software's to choose: they follow from the law the deployment runs under, and two of the provisions in the [compliance overview](index.md) ask for exactly this register: GDPR Art. 30(1)(f) wants the envisaged time limits for erasure per category of data in the record of @@ -152,14 +152,14 @@ they are. An EHR under a whole-record hold does not appear at all. GDPR Art. 4(3) defines restriction as marking stored data to limit its future processing, and Art. 18(2) says what is left once the mark is set: storage, and nothing else without the subject's consent or one of the named exceptions. -FerroEHR implements that literally, at two grains — a whole EHR, or one +FerroEHR implements that literally, at two grains: a whole EHR, or one versioned object inside it. A restricted object stays in storage untouched, and every path that would process it stops: - a point read, a versioned read and a revision history answer **403** with a - body naming the restriction — distinct from the authorization **403**, because + body naming the restriction, distinct from the authorization **403**, because the same caller with the same rights is refused until the restriction is lifted; - AQL results omit it, at every scope, so naming the `ehr_id` does not make the @@ -195,7 +195,7 @@ Content-Type: application/json ``` Omit `vo_id` to restrict the whole record. `ground` is one of the four -Art. 18(1) points — `gdpr-18-1-a` through `gdpr-18-1-d` — or `national` for a +Art. 18(1) points (`gdpr-18-1-a` through `gdpr-18-1-d`) or `national` for a member-state rule that goes beyond them, which is how German BDSG § 35 Abs. 2 and Abs. 3 are carried. @@ -215,7 +215,7 @@ unless the processing is necessary for a task carried out for reasons of public interest. That is narrower than Art. 18: it reaches research, not care. While an objection stands, the EHR is absent from every full-population AQL -query, from every export, and from the change-event stream — the three surfaces +query, from every export, and from the change-event stream, the three surfaces a secondary-use consumer reads this repository through. A query that names the `ehr_id` and a read of the record by the treating clinician are untouched. @@ -291,7 +291,7 @@ imported with an EHR from another system ends the same way at the `retain_until` it states, and its tombstones fold once no imported record still kept needs them to verify. Retention of the trail itself is described in -[Audit](../audit.md#retention-and-who-chooses-it). +[Audit](../ehds-logging.md#retention-and-who-chooses-it). ## What this page does not claim diff --git a/website/book/src/compliance/shared-responsibility.md b/website/book/src/compliance/shared-responsibility.md index c456d02ab9..868a64f9f6 100644 --- a/website/book/src/compliance/shared-responsibility.md +++ b/website/book/src/compliance/shared-responsibility.md @@ -42,17 +42,17 @@ repository and on how you configure it. |---|---|---|---| | **EHDS [Art. 3(1)](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, access to one's own priority-category data "immediately after the personal electronic health data have been registered", free of charge, readable and consolidated | A committed version is readable at once over the openEHR REST API and AQL; nothing stands between the commit and the read but the authorization checks. A token with a SMART `patient/` scope is [held to one EHR](../smart-app-launch.md#launch-context-binding-to-one-ehr). The [audit category register](../installation/config-audit.md#the-audit-category-register) tells which templates hold which priority category | Run, or connect the repository to, the Member State's access service: identify and authenticate the person, issue their token with `patient/` scopes, and fill the category map for your templates | The readable, consolidated presentation and the "free of charge" are the access service's (Art. 4(1)). A CDR serves structured data to callers and has no person-facing interface | | **EHDS [Art. 3(2)](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, a downloadable electronic copy in the European electronic health record exchange format | The whole record as an openEHR EXTRACT, `GET /ferroehr/rest/extensions/v1/message/export/{ehr_id}`, or a selection with `POST …/message/export` ([exporting an EHR](../beyond-core/messaging.md#exporting-an-ehr)) | Offer the download in the access service, and run the conversion to the exchange format | FerroEHR writes openEHR, never the exchange format: the European interoperability software component of the FerroHEALTH EHR system is FerroBRIDGE's, and the format's specifications come from the implementing acts under Art. 15(1) | -| **EHDS [Art. 3(3)](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, a Member State's delay of the person's access "until a health professional is able to properly communicate and explain" it | The [delayed access](../security.md#delayed-access-by-the-person-ehds-art-33) under [the access-delay register](../installation/config-auth.md#the-access-delay-register), off by default: a new composition in a listed category is held from any request that may be the person's for at most the access-delay register's `max_delay`, the treating professional releases it with `POST /ferroehr/rest/extensions/v1/ehr/{ehr_id}/versioned_composition/{versioned_object_uid}/access-delay/release`, and every hold ends by itself when its period passes. The person's subject-scoped audit read leaves out the records about a held composition until then. Shipped, [#4351](https://github.com/FerroHEALTH/FerroEHR/issues/4351) | Turn the section on only where your Member State's law provides the delay, list the categories and the period that law sets, and have the professional release the data once explained. The hold does not filter the [audit feeds](../audit.md#sinks) or the change-event stream, so a notification you build for the person on either must hold back what is held | Which information "can have a significant impact" on a person, and how long a delay may last, is the Member State's rule under GDPR Art. 23; the conversation that explains the information is the professional's | -| **EHDS [Art. 4(2)](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, access by a person the natural person authorises, or by a legal representative, through a proxy service | A token in a patient context reaches that one EHR whoever holds it; a COMPOSITION a representative inserts names them as composer (`PARTY_RELATED`, see the Art. 5 row); every access record names the authenticated caller and the patient ([the logging elements](../audit.md#the-ehds-logging-elements-mapped)) | Run the proxy service, or connect to the Member State's: check the authorisation, its scope and its duration before you issue a token in the person's context | The register of who may act for whom, and the rules on guardians, are the Member State's proxy service (Art. 4(2) to (4)); the repository sees a token, never the authorisation behind it | -| **EHDS [Art. 5](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, inserting information in one's own EHR, "clearly distinguishable", without being able to "directly alter" what health professionals inserted | [Information a person inserts](../security.md#information-a-person-inserts-ehds-art-5): every version a `patient/`-only token commits records `PARTY_SELF` as committer, written by the server whatever the request names; the contribution list flags it `inserted_by_person`; an update or deletion by the person of a version anyone else committed is refused with **403**. Shipped, [#4350](https://github.com/FerroHEALTH/FerroEHR/issues/4350) | Give the person's access service `patient/` scopes only and clinicians' applications `user/` scopes, and decide which templates the person may write | Showing the person's entries as theirs to a reader is the presenting application's; the marker it reads is on every version | +| **EHDS [Art. 3(3)](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, a Member State's delay of the person's access "until a health professional is able to properly communicate and explain" it | The [delayed access](../access-control.md#delayed-access-by-the-person-ehds-art-33) under [the access-delay register](../installation/config-auth.md#the-access-delay-register), off by default: a new composition in a listed category is held from any request that may be the person's for at most the access-delay register's `max_delay`, the treating professional releases it with `POST /ferroehr/rest/extensions/v1/ehr/{ehr_id}/versioned_composition/{versioned_object_uid}/access-delay/release`, and every hold ends by itself when its period passes. The person's subject-scoped audit read leaves out the records about a held composition until then. Shipped, [#4351](https://github.com/FerroHEALTH/FerroEHR/issues/4351) | Turn the section on only where your Member State's law provides the delay, list the categories and the period that law sets, and have the professional release the data once explained. The hold does not filter the [audit feeds](../audit.md#sinks) or the change-event stream, so a notification you build for the person on either must hold back what is held | Which information "can have a significant impact" on a person, and how long a delay may last, is the Member State's rule under GDPR Art. 23; the conversation that explains the information is the professional's | +| **EHDS [Art. 4(2)](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, access by a person the natural person authorises, or by a legal representative, through a proxy service | A token in a patient context reaches that one EHR whoever holds it; a COMPOSITION a representative inserts names them as composer (`PARTY_RELATED`, see the Art. 5 row); every access record names the authenticated caller and the patient ([the logging elements](../ehds-logging.md#the-ehds-logging-elements-mapped)) | Run the proxy service, or connect to the Member State's: check the authorisation, its scope and its duration before you issue a token in the person's context | The register of who may act for whom, and the rules on guardians, are the Member State's proxy service (Art. 4(2) to (4)); the repository sees a token, never the authorisation behind it | +| **EHDS [Art. 5](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, inserting information in one's own EHR, "clearly distinguishable", without being able to "directly alter" what health professionals inserted | [Information a person inserts](../access-control.md#information-a-person-inserts-ehds-art-5): every version a `patient/`-only token commits records `PARTY_SELF` as committer, written by the server whatever the request names; the contribution list flags it `inserted_by_person`; an update or deletion by the person of a version anyone else committed is refused with **403**. Shipped, [#4350](https://github.com/FerroHEALTH/FerroEHR/issues/4350) | Give the person's access service `patient/` scopes only and clinicians' applications `user/` scopes, and decide which templates the person may write | Showing the person's entries as theirs to a reader is the presenting application's; the marker it reads is on every version | | **EHDS [Art. 6](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, requesting rectification online under GDPR Art. 16 | A correction is a new version: the prior version stays in the versioned object's revision history, with the committer and the server's commit time on each ([composition version history](../using-the-api/resources.md#composition-version-history)) | Take the online request in the access service, verify the accuracy with a health professional where appropriate, and commit the correction under a professional's token. Under the Art. 5 rule the person cannot change a professional's version themselves | Receiving the request and deciding it are the controller's (GDPR Art. 16); the repository holds the outcome | -| **EHDS [Art. 7](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, transmission to another provider "without hindrance from the healthcare provider or from the manufacturers", across borders in the exchange format, and one-way to a social security recipient | The REST API, AQL and the EXTRACT export, whose routes are [not admin-gated](../operations-admin-apis.md#ehr-extract-export-and-import), so any authorized caller can take the whole record or a part of it | Transmit the data to the recipient the person names, one-way for a social security recipient (Art. 7(3)), through the exchange format where Art. 7(2) asks for it | Cross-border transmission runs through the infrastructure of Art. 23 (MyHealth@EU and the national contact points), which no CDR is part of; the exchange format is FerroBRIDGE's, as in the Art. 3(2) row | -| **EHDS [Art. 8](https://eur-lex.europa.eu/eli/reg/2025/327/oj)** with **[Art. 11(5)](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, restricting professionals' access, invisible to providers, with access "where necessary in order to protect the vital interests of the data subject", logged | The [restriction of access](../security.md#restriction-of-access-by-health-professionals-ehds-art-8) a `restriction` directive of the EHR's own `EHR_ACCESS`, for a whole EHR or named versioned objects, committed and lifted on the person's instruction with `POST /ferroehr/rest/extensions/v1/admin/ehr-access`: restricted data reads as absent on every professional route, and no status, header or count says a restriction exists. An emergency [justification](../security.md#justified-access-outside-the-care-relationships) of the access policy, invoked with the clinician's reason, overrides it, and the access record names the emergency with the reason ([justified and emergency access](../audit.md#justified-and-emergency-access)) | Record the restriction on the person's instruction, tell the person that it may affect their care (Art. 8, second paragraph), write the emergency justification in your access policy, and apply your Member State's rules and safeguards | The grain stops at the versioned object, as the [restriction section](../security.md#restriction-of-access-by-health-professionals-ehds-art-8) explains; the rules and safeguards of the mechanism are the Member State's (Art. 8, fourth paragraph) | -| **EHDS [Art. 9](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, information on every access, including through automatic notifications, available "for at least three years from each date of access" | An [access record](../audit.md) of every read, write and refusal with the elements Art. 9(2)(a) to (c) name; a [subject-scoped ITI-81 read](../audit.md#retrieving-audit-records-iti-81) for one patient under a `read_subject_audit` grant in the CDR, which a patient portal can hold without an admin credential; the emergency mark of Art. 11(5); and a [retention floor](../audit.md#retention-and-who-chooses-it) of three years that refuses an access policy write keeping the log shorter for a controller that declares itself in the Union | Present the trail to the person in the access service, send the automatic notifications, keep the retention at three years or more, and apply any exception your Member State makes under Art. 9(3) | Notifying the person is the access service's (Art. 9(2)); the repository has no channel to the person. A portal built on the subject-scoped read gets the Art. 3(3) filter, while one built on the feeds does not | -| **EHDS [Art. 10](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, a reversible opt-out from access through the access services of Arts. 4 and 12, where a Member State's law provides one, with access to protect vital interests | The [opt-out mark](../security.md#opt-out-from-the-access-services-ehds-art-10) on a whole EHR, an `opt_out` directive of the EHR's own `EHR_ACCESS` committed and reversed with `POST /ferroehr/rest/extensions/v1/admin/ehr-access`, kept with its history as `EHR_ACCESS` versions: a caller holding an `access_service` grant in the CDR reads the EHR as absent at every route, query and export, and every other caller, your own care included, reads it as before. An access-service caller an emergency justification of the access policy names, stating a reason and not acting for the person, overrides it, recorded with the reason. Recording, reversing and the override are access records. Off by default. Shipped, [#4516](https://github.com/FerroHEALTH/FerroEHR/issues/4516) | Allow `access_service` in `[authz.grants] allowed` and grant it to your access services, record and reverse the opt-out on the person's instruction, write the emergency justification, and apply your Member State's law and its safeguards (Art. 10(2)); where the Member State enforces the opt-out in its own services, leave the mark unused | Whether the right exists at all, and its rules and safeguards, are the Member State's (Art. 10(1) and (2)) | -| **EHDS [Art. 11(1) and (3)](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, professionals' access to the data of persons under their treatment, under the Member State's rules on the categories each category of professional may reach | Per-EHR [`EHR_ACCESS`](../security.md#per-ehr-access-control-ehr_access) and its [access directives](../security.md#access-directives), which the access evaluator decides over the controller's rules by role and kind of data, the caller's care relationships and purpose and the data's category and origin | Write the access policy and its rules that carry your Member State's rules, provision the `ROLE`s your professionals perform, and record the care relationships they turn on | The rules themselves are the Member State's (Art. 11(3)); cross-border access (Art. 11(2) and (4)) runs through the Art. 23 infrastructure | -| **EHDS [Art. 12](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, health professional access services open only to professionals holding recognised electronic identification means | [`[authz.assurance]`](../security.md#assurance-level-and-the-natural-person-on-patient-data) refuses patient data below a minimum eIDAS level, and `[authz.professional]` refuses a client token that names no natural person | Run the identity provider that issues the recognised means, map its levels, and set the minimum | The professional access service and its "user-friendly" presentation are the Member State's and the clinical application's | -| **EHDS [Art. 13(4)](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, second subparagraph: a registration or update identifies the professional, the provider and the time | Every version carries the server's `time_committed`, the `system_id`, and the committer the caller names; the access record of the write names the authenticated person, with `[authz.professional]` the professional behind a client, and the organisation where the token carries it. The server [checks the committer](../using-the-api/resources.md#contribution) where it can: one that names another login of the caller's token issuer or of the server, or a `PARTY_SELF` from anyone but the person, is refused with **403**. Shipped, [#4520](https://github.com/FerroHEALTH/FerroEHR/issues/4520) | Have your clinical applications name the professional as committer with the login the token carries, since a name only or another authority's identifier cannot be compared with the login and is stored as sent; register the priority categories (Art. 13(1)) under the person's identification data in the Member State of affiliation (Art. 13(3)) | The duty to register, and the data quality requirements Art. 13(4) leaves to implementing acts, rest on the healthcare provider and the Commission | +| **EHDS [Art. 7](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, transmission to another provider "without hindrance from the healthcare provider or from the manufacturers", across borders in the exchange format, and one-way to a social security recipient | The REST API, AQL and the EXTRACT export, whose routes are [not admin-gated](../storage-admin-apis.md#ehr-extract-export-and-import), so any authorized caller can take the whole record or a part of it | Transmit the data to the recipient the person names, one-way for a social security recipient (Art. 7(3)), through the exchange format where Art. 7(2) asks for it | Cross-border transmission runs through the infrastructure of Art. 23 (MyHealth@EU and the national contact points), which no CDR is part of; the exchange format is FerroBRIDGE's, as in the Art. 3(2) row | +| **EHDS [Art. 8](https://eur-lex.europa.eu/eli/reg/2025/327/oj)** with **[Art. 11(5)](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, restricting professionals' access, invisible to providers, with access "where necessary in order to protect the vital interests of the data subject", logged | The [restriction of access](../access-control.md#restriction-of-access-by-health-professionals-ehds-art-8) a `restriction` directive of the EHR's own `EHR_ACCESS`, for a whole EHR or named versioned objects, committed and lifted on the person's instruction with `POST /ferroehr/rest/extensions/v1/admin/ehr-access`: restricted data reads as absent on every professional route, and no status, header or count says a restriction exists. An emergency [justification](../access-control.md#justified-access-outside-the-care-relationships) of the access policy, invoked with the clinician's reason, overrides it, and the access record names the emergency with the reason ([justified and emergency access](../ehds-logging.md#justified-and-emergency-access)) | Record the restriction on the person's instruction, tell the person that it may affect their care (Art. 8, second paragraph), write the emergency justification in your access policy, and apply your Member State's rules and safeguards | The grain stops at the versioned object, as the [restriction section](../access-control.md#restriction-of-access-by-health-professionals-ehds-art-8) explains; the rules and safeguards of the mechanism are the Member State's (Art. 8, fourth paragraph) | +| **EHDS [Art. 9](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, information on every access, including through automatic notifications, available "for at least three years from each date of access" | An [access record](../audit.md) of every read, write and refusal with the elements Art. 9(2)(a) to (c) name; a [subject-scoped ITI-81 read](../audit-integrity.md#retrieving-audit-records-iti-81) for one patient under a `read_subject_audit` grant in the CDR, which a patient portal can hold without an admin credential; the emergency mark of Art. 11(5); and a [retention floor](../ehds-logging.md#retention-and-who-chooses-it) of three years that refuses an access policy write keeping the log shorter for a controller that declares itself in the Union | Present the trail to the person in the access service, send the automatic notifications, keep the retention at three years or more, and apply any exception your Member State makes under Art. 9(3) | Notifying the person is the access service's (Art. 9(2)); the repository has no channel to the person. A portal built on the subject-scoped read gets the Art. 3(3) filter, while one built on the feeds does not | +| **EHDS [Art. 10](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, a reversible opt-out from access through the access services of Arts. 4 and 12, where a Member State's law provides one, with access to protect vital interests | The [opt-out mark](../access-control.md#opt-out-from-the-access-services-ehds-art-10) on a whole EHR, an `opt_out` directive of the EHR's own `EHR_ACCESS` committed and reversed with `POST /ferroehr/rest/extensions/v1/admin/ehr-access`, kept with its history as `EHR_ACCESS` versions: a caller holding an `access_service` grant in the CDR reads the EHR as absent at every route, query and export, and every other caller, your own care included, reads it as before. An access-service caller an emergency justification of the access policy names, stating a reason and not acting for the person, overrides it, recorded with the reason. Recording, reversing and the override are access records. Off by default. Shipped, [#4516](https://github.com/FerroHEALTH/FerroEHR/issues/4516) | Allow `access_service` in `[authz.grants] allowed` and grant it to your access services, record and reverse the opt-out on the person's instruction, write the emergency justification, and apply your Member State's law and its safeguards (Art. 10(2)); where the Member State enforces the opt-out in its own services, leave the mark unused | Whether the right exists at all, and its rules and safeguards, are the Member State's (Art. 10(1) and (2)) | +| **EHDS [Art. 11(1) and (3)](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, professionals' access to the data of persons under their treatment, under the Member State's rules on the categories each category of professional may reach | Per-EHR [`EHR_ACCESS`](../access-control.md#per-ehr-access-control-ehr_access) and its [access directives](../access-control.md#access-directives), which the access evaluator decides over the controller's rules by role and kind of data, the caller's care relationships and purpose and the data's category and origin | Write the access policy and its rules that carry your Member State's rules, provision the `ROLE`s your professionals perform, and record the care relationships they turn on | The rules themselves are the Member State's (Art. 11(3)); cross-border access (Art. 11(2) and (4)) runs through the Art. 23 infrastructure | +| **EHDS [Art. 12](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, health professional access services open only to professionals holding recognised electronic identification means | [`[authz.assurance]`](../security.md#assurance-level-and-the-natural-person-on-patient-data) refuses patient data below a minimum eIDAS level | Run the identity provider that issues the recognised means, map its levels, and set the minimum | The professional access service and its "user-friendly" presentation are the Member State's and the clinical application's | +| **EHDS [Art. 13(4)](https://eur-lex.europa.eu/eli/reg/2025/327/oj)**, second subparagraph: a registration or update identifies the professional, the provider and the time | Every version carries the server's `time_committed`, the `system_id`, and the committer the caller names; the access record of the write names the authenticated person, the professional behind a client, and the organisation where the token carries it. The server [checks the committer](../using-the-api/resources.md#contribution) where it can: one that names another login of the caller's token issuer or of the server, or a `PARTY_SELF` from anyone but the person, is refused with **403**. Shipped, [#4520](https://github.com/FerroHEALTH/FerroEHR/issues/4520) | Have your clinical applications name the professional as committer with the login the token carries, since a name only or another authority's identifier cannot be compared with the login and is stored as sent; register the priority categories (Art. 13(1)) under the person's identification data in the Member State of affiliation (Art. 13(3)) | The duty to register, and the data quality requirements Art. 13(4) leaves to implementing acts, rest on the healthcare provider and the Commission | ## Where FerroEHR documents its side @@ -90,4 +90,4 @@ ends every hold, and the access record of each. The rule is yours to carry: whether your Member State provides for the delay at all, which categories of data it covers, how long a hold may last, and which professional releases a result and when. FerroEHR ships the delay off; see [delayed access by the -person](../security.md#delayed-access-by-the-person-ehds-art-33). +person](../access-control.md#delayed-access-by-the-person-ehds-art-33). diff --git a/website/book/src/concepts/architecture.md b/website/book/src/concepts/architecture.md index e37b7475fd..9469f3f17d 100644 --- a/website/book/src/concepts/architecture.md +++ b/website/book/src/concepts/architecture.md @@ -57,7 +57,7 @@ so a build without them contains none of their code; see part of FerroEHR: it is [FerroBRIDGE](https://github.com/FerroHEALTH/FerroBRIDGE), a separate server that reaches FerroEHR over ITS-REST. The Helm chart deploys it in the same release with `bridge.enabled=true`; see -[Kubernetes & Helm](../installation/kubernetes.md#ferrobridge-the-fhir-bridge-off-by-default). +[Kubernetes & Helm](../installation/kubernetes-integrations.md#ferrobridge-the-fhir-bridge-off-by-default). What you actually deploy is small: **one self-contained server binary** plus PostgreSQL. No JVM, no language runtime, and a pure-Rust TLS stack. The @@ -147,7 +147,7 @@ authenticate as the first, which keeps the schema separation and drops the credential separation. Preparing the schema spans every schema at once, so it runs on `[database] migrate_url` rather than on any of them. The local Audit Record Repository is written on the clinical pool, into its own `audit` schema. See -[Operations](../operations.md#database-roles-and-least-privilege) for the +[Operations](../database-operations.md#database-roles-and-least-privilege) for the roles and [the threat model](../threat-model.md#what-each-database-credential-can-reach) for what each credential can reach. diff --git a/website/book/src/concepts/index.md b/website/book/src/concepts/index.md index 73a07c8d1e..e7e8ba2e13 100644 --- a/website/book/src/concepts/index.md +++ b/website/book/src/concepts/index.md @@ -1,6 +1,6 @@ # Concepts -This part explains the ideas you need to use FerroEHR effectively. Four +These chapters explain the ideas you need to use FerroEHR effectively. Four chapters; the first two read in either order, the last two go deeper: - **[openEHR primer](openehr-primer.md):** the standard itself: the Reference diff --git a/website/book/src/concepts/storage.md b/website/book/src/concepts/storage.md index d345581fbe..fb0855249b 100644 --- a/website/book/src/concepts/storage.md +++ b/website/book/src/concepts/storage.md @@ -71,17 +71,17 @@ Parties (PERSON, ORGANISATION, GROUP, AGENT, ROLE, PARTY_RELATIONSHIP) live in directions: each domain's `version` relation carries a `CHECK` admitting only its own kinds. The clinical record and the identity of its subject are therefore never in the same schema, the same -archival tier, or the reach of the same runtime role — GDPR Art. 4(5) and +archival tier, or the reach of the same runtime role: GDPR Art. 4(5) and Art. 32(1)(a), . Which role reads which domain, and how a deployment turns the schema split into a credential -split, is [Operations → Database roles](../operations.md#database-roles-and-least-privilege). +split, is [Operations → Database roles](../database-operations.md#database-roles-and-least-privilege). The mechanism inside the server is deliberately small: the two domains' change control and node relations are **rendered from one DDL template**, so they carry the same names, the same column shape, the same indexes and the same foreign keys and cannot drift; and the pool serving each domain sets its own -`search_path`. One set of storage code — the nested-set node codec, the -versioning engine, the AQL path machinery — therefore serves both domains +`search_path`. One set of storage code (the nested-set node codec, the +versioning engine, the AQL path machinery) therefore serves both domains unchanged, and no SQL in the server names a domain schema. A test renders both files and refuses any difference beyond the kind `CHECK` and the foreign keys into the `ehr` relation, which the party domain has none of. @@ -95,7 +95,7 @@ cross-reference table; v6 creates none of it. The wire is unaffected. The ITS-REST Demographic API, the RM change-control semantics and every version identifier are exactly what they were; only where -the rows physically sit has changed. No openEHR spec governs storage layout — +the rows physically sit has changed. No openEHR spec governs storage layout: this is FerroEHR's own design. ## Core tables and how they relate @@ -206,7 +206,7 @@ FerroEHR does not, and it does not carry a validity interval either. its predecessor's rows, and a `LATEST_VERSION` query joins the node rows on this column, so a tree a long chain of identical versions shares is read once. None of the columns a commit changes appears in an index, - which is the condition PostgreSQL 18 §"Heap-Only Tuples (HOT)" states for a + which is the condition PostgreSQL 19 §"Heap-Only Tuples (HOT)" states for a heap-only update. - `ALL_VERSIONS` is the unfiltered table; `LATEST_VERSION` is the head row's answer. @@ -369,7 +369,7 @@ Details that matter: - There is no close-out statement: the head row advancing past the previous version is what supersedes it, and that update is heap-only because none of the columns it changes is indexed. -- The whole chain above is ONE statement — a data-modifying CTE — so the audit, +- The whole chain above is ONE statement (a data-modifying CTE) so the audit, the contribution, the version row, the head row and every node row commit or roll back together and cost one round trip. - The body bytes in `version.body` are materialized from the accepted, @@ -406,7 +406,7 @@ on the same one table. `version`, `node` and `vo_attestation` are each `PARTITION BY LIST (tier)` with a `hot` and a `cold` partition and no default partition. Archiving an EHR is one -statement — `UPDATE version SET tier = 'cold' WHERE ehr_id = $1` — and +statement (`UPDATE version SET tier = 'cold' WHERE ehr_id = $1`) and PostgreSQL moves the rows between partitions; the `node` and `vo_attestation` foreign keys carry their rows across with `ON UPDATE CASCADE`. Restore is the reverse statement. Archiving never merges the two pseudonymisation domains: each @@ -462,7 +462,7 @@ The shape follows documented PostgreSQL behaviour rather than habit: - An append-only version table replaces current/history pairs, with `ALL_VERSIONS` a plain scan of one relation. The reason it is append-only is PostgreSQL's own rule for a heap-only update: it applies when "the update does - not modify any columns referenced by the table's indexes" (PostgreSQL 18, + not modify any columns referenced by the table's indexes" (PostgreSQL 19, "Heap-Only Tuples (HOT)"). A validity interval cannot satisfy that, because the currency predicates index it; a separate head row whose updated columns are in no index can, and does. diff --git a/website/book/src/contributing.md b/website/book/src/contributing.md index 4595c27e47..9294956bcc 100644 --- a/website/book/src/contributing.md +++ b/website/book/src/contributing.md @@ -25,12 +25,12 @@ measurement from your own hardware all count. The three governing documents are kept in the repository root: -- [CONTRIBUTING](https://github.com/FerroHEALTH/FerroEHR/blob/main/CONTRIBUTING.md) - — the practical rules for setup, the required checks, and pull requests. -- [Code of conduct](https://github.com/FerroHEALTH/FerroEHR/blob/main/CODE_OF_CONDUCT.md) - — the Contributor Covenant (v2.1) the community follows. -- [Security policy](https://github.com/FerroHEALTH/FerroEHR/blob/main/SECURITY.md) - — how to report a vulnerability privately. +- [CONTRIBUTING](https://github.com/FerroHEALTH/FerroEHR/blob/main/CONTRIBUTING.md): + the practical rules for setup, the required checks, and pull requests. +- [Code of conduct](https://github.com/FerroHEALTH/FerroEHR/blob/main/CODE_OF_CONDUCT.md): + the Contributor Covenant (v2.1) the community follows. +- [Security policy](https://github.com/FerroHEALTH/FerroEHR/blob/main/SECURITY.md): + how to report a vulnerability privately. ## Setting up diff --git a/website/book/src/database-operations.md b/website/book/src/database-operations.md new file mode 100644 index 0000000000..7b41fb6d14 --- /dev/null +++ b/website/book/src/database-operations.md @@ -0,0 +1,504 @@ +# Database roles, migrations and backup + +The PostgreSQL side of running FerroEHR: the least-privileged roles, applying the +migrations, and backing up and restoring each domain. + + + +## Database roles and least privilege + +FerroEHR connects to an **external** PostgreSQL 19: a managed service or an +operator-run cluster, never a chart-side sidecar, because a database holding +PHI must be independently backed up and recoverable. The server carries only a +connection string, ideally sourced from a secret. + +The database never runs as a superuser at runtime. Two roles cover +provisioning and migration: + +| Role | Purpose | Used by | +|---|---|---| +| owner | owns the database | provisioning only | +| `ferroehr_migrator` | runs the schema migrations; owns the helper functions | the migration step | + +and four cover serving, split by **pseudonymisation domain**, the clinical +record and the identity of its subject: + +| Role | Reads and writes | Barred from | +|---|---|---| +| `ferroehr_clinical` | `clinical`, archival tier included | `party` | +| `ferroehr_party` | `party`, archival tier included | `clinical` | +| `ferroehr_clinical_reader` | read-only over `clinical` | `party` | +| `ferroehr_party_reader` | read-only over `party` | `clinical` | + +The migrations create these roles idempotently, apply the per-schema grants, +**and revoke every other domain explicitly in both directions**, and revoke the +ability to create objects in the public schema. All four are `NOINHERIT` and +none is a member of another, so a boundary cannot be crossed by picking up a +membership. GDPR Art. 4(5) defines pseudonymisation as processing where +attribution to a person needs additional information "kept separately and +subject to technical and organisational measures", and Art. 32(1)(a) names it a +security measure for health data +(); EDPB Guidelines 01/2025 +require that separation to hold against internal actors, operators with +database access included. + +Each serving role holds `SELECT`/`INSERT`/`UPDATE`/`DELETE` on its own domain's +tables, `EXECUTE` on the `ext` helper functions, and `MAINTAIN` on its store's +partitioned tables (and `ehr`, for `ferroehr_clinical`), and nothing else: it is not +a superuser, does not bypass row-level security, and cannot create, alter or +drop a table, index, schema or role. On the audit trail it is narrower still: +it may record an event and stamp it forwarded, and it holds no privilege that +can rewrite or remove one (see [Audit](audit.md)). + +`MAINTAIN` is there so the server can keep those tables' planner statistics +(see [Planner statistics of the partitioned tables](#planner-statistics-of-the-partitioned-tables)). +It also allows `VACUUM`, `CLUSTER`, `REINDEX` and `LOCK TABLE` on exactly +those tables. The role can already write every row of them, so what it adds +is the locks and index rebuilds those commands take. The reader roles do not +hold it. + +### Turning the schema split into a role split + +The **schema** separation is unconditional: the server always reads and writes +parties in `party`, whatever it authenticates as, and each of the three pools +carries only its own schema on its `search_path`. The **role** separation is a +deployment choice, and it is one configuration table per domain: + +```toml +[database.party] +url = "postgres://ferroehr_party:***@pg:5432/ferroehr" +``` + +(or `url_file`, for a mounted secret). With a domain's `url` set the server +opens that pool on that credential, and a flaw that reaches one of them reaches +one domain. Left unset, the domain uses `[database].url` and the separation is +schema-only. Set both domains and no credential the server uses can join a +party to its EHR in SQL; the crossing happens in the application, over +two connections, and is recorded as an access event (see [Security → Resolving +across the boundary](pseudonymisation.md#resolving-across-the-boundary)). + +A DSN that names another host moves the domain to a **database or cluster of its +own**, which is the separation a schema cannot make: a base backup, WAL +archiving and physical replication carry every schema of a database together +([PostgreSQL 19, Backup and +Restore](https://www.postgresql.org/docs/19/backup-dump.html)). + +Two boot checks make the posture honest. Two domains configured on **different** +DSNs that authenticate as the **same** database role are refused: a separation +that exists only in the configuration reads as one that holds, which is worse +than none. And a domain role that does not exist is a warning under +`deployment.profile = "sandbox"` and a refusal under `production`: absent roles +mean absent grants, and the boundary check would otherwise pass by having +nothing to measure. + +### Which credential prepares the schema + +**None of the domain credentials.** Preparing a database spans every schema in +it at once: the DDL of each resident migration set under `[database] migrations = "apply"`, +and their `_sqlx_migrations` bookkeeping tables under `"verify"`: a read, but a +read across the whole database. Each runtime role holds exactly one domain, so +none can do it, and `verify` is not the exception: a role that is a member of +`ferroehr_clinical` and nothing else is refused on the very first set: it +cannot read the `ext`, `party` or `audit` bookkeeping. + +So the credential that prepares the schema is named separately, and the server +uses it for that one boot step: + +```toml +[database] +url = "postgres://ferroehr_clinical:***@pg:5432/ferroehr" +migrate_url = "postgres://ferroehr_migrator:***@pg:5432/ferroehr" + +[database.party] +url = "postgres://ferroehr_party:***@pg:5432/ferroehr" +``` + +`migrate_url` prepares every domain that reaches the same DATABASE it does, +which is all of them in the posture above: three credentials, one database. A +domain whose DSN reaches a DIFFERENT database is prepared there on that +database's own migrator, `[database.]` migrate_url`, because +`migrate_url` names one database and a relocated domain is not in it; unset, it +falls back to the domain's own DSN, which a DML-only role cannot use. Which case a domain is in is read from the server itself +(`pg_control_system()` and `current_database()`), never from the DSN text: two +DSNs that differ only in their credential reach the same database. + +(or `migrate_url_file`, for a mounted secret). The connection is opened for +preparation and closed again: no pool is held on it, and no request is ever +served through it. Left unset it falls back to `url`, which is exactly what a +single-credential deployment has always run; its behaviour is unchanged by +this key existing. + +A credential that cannot read a set is told which schema and which role, so +the fix is visible from the message: + +```text +database role `app_ehr` cannot read the migration state of schema +`ext`: … point `[database] migrate_url` (or `migrate_url_file`) at the credential +that prepares the schema — unset, it falls back to `[database] url` — and, for a +domain in a database of its own, `[database.]` migrate_url` at that +database's migration credential +``` + +Either way the server **refuses to boot** when the grants themselves are wrong: +a self-check enumerates every table, view, sequence and function in each +domain and fails, naming the role and the object, if either runtime role can +read across the boundary. `ferroehr db verify` runs the same check. When the +four roles do not exist at all (the development, compose and test-harness case, +where the migrator holds no `CREATEROLE`) the check warns rather than inventing +a failure: under `deployment.profile = "production"` it refuses, because absent +roles mean absent grants and there is then nothing to measure. + +On Kubernetes the same choice is chart values, mounted as files the same way +the clinical DSN is, so no credential enters the pod's environment: + +```yaml +database: + existingSecret: ferroehr-db # postgres://ferroehr_clinical:… + party: + existingSecret: ferroehr-db-party # postgres://ferroehr_party:… + audit: + existingSecret: ferroehr-db-audit # the audit repository's own DSN + migrateExistingSecret: ferroehr-db-migrator # postgres://ferroehr_migrator:… +``` + +Leave a domain's block unset and that pool uses the shared DSN, which is the +schema-only posture. + +Provisioning the four roles is yours in both cases. The migrations create them +only when the migrator holds `CREATEROLE` and skip them with a `NOTICE` +otherwise, so on a managed database (where the migrator usually does not) +create them before the first deploy: + +```sql +CREATE ROLE ferroehr_clinical NOLOGIN NOINHERIT; +CREATE ROLE ferroehr_party NOLOGIN NOINHERIT; +CREATE ROLE ferroehr_clinical_reader NOLOGIN NOINHERIT; +CREATE ROLE ferroehr_party_reader NOLOGIN NOINHERIT; +``` + +then give each login role membership of exactly one of them. +`ferroehr db verify` tells you whether the boundary holds afterwards. + +The local Audit Record Repository is written on its own pool +(`[database.audit]`), and the `audit` schema is granted to `ferroehr_clinical` +(record an event, stamp it forwarded, run the retention reaper, verify the +chain) and to `ferroehr_clinical_reader` (read it and verify the chain). A +clinical login role that is a member of `ferroehr_clinical` alone writes its own +access log; no extra membership is needed. The audit trail is not a +pseudonymisation domain, so this grant adds no reach into `party`. + +The compose stacks create the four domain roles and grant the clinical and party domains to +the single dev login role, which owns the database. That +demonstrates the schema separation and exercises the boot self-check; it is +deliberately **not** the credential separation, because one container with one +DSN cannot show that half honestly. + +### Which of these postures is exercised, and which is not + +A recommendation nothing runs is a guess. This is what the suites cover. + +Exercised against a real PostgreSQL 19: + +- Two runtime credentials serving both domains through the assembled router, + each of the server's own pools refused every relation of the other domain + (`app/ferroehr-rest/tests/it/credential_separation.rs`), and the single-DSN + fallback still serving both. +- All four domain roles refused every relation in the domain they do not own, + enumerated from `information_schema` rather than from a written list + (`app/ferroehr/tests/it/pseudonymisation_boundary.rs`). +- The boot sequence on separated credentials with `[database] migrate_url`, under + both `verify` and `apply`, and the single-DSN fallback under both + (`app/ferroehr/tests/it/schema_preparation_credential.rs`). +- The party domain relocated to a second database, prepared and verified + there on `[database.party]`, and the + refusal when the domain's two DSNs reach different databases + (`app/ferroehr/tests/it/relocated_domain_preparation.rs`). +- The chart's production overlay on three PostgreSQL clusters, one per domain, + prepared by the migration Job and booting under `production` + (`scripts/deploy-probe-k8s.sh --production-only`, probes P-K8S-PROD-BOOT and + P-K8S-PROD-SHARED). +- The compose stack's grant boundary read back from the running database by + `scripts/deploy-probe.sh`, which also records that the stack is + single-credential by design. + +Not exercised by anything, and stated rather than left to inference: + +- **A real deployment on separated DSNs**: a container booting with the DSN + files mounted, and the chart wiring them through + `database.party.existingSecret` and `database.migrateExistingSecret`. What is covered is the in-process half. +- **Role provisioning on a managed database** where the migrator holds no + `CREATEROLE` and the roles are created by the manual step above. + +Which posture you actually get depends on `[database] migrations`, because the server's +embedded migrations are DDL: a self-migrating deployment necessarily runs as a +role that can execute DDL. The single-container quickstart takes that path: its +DSN authenticates as a non-superuser role that owns the database and is a member +of `ferroehr_migrator`, `ferroehr_clinical` and `ferroehr_party`. + +## Applying migrations + +`[database] migrations` decides who runs the schema: + +- **`apply`** (the default): the server applies its embedded migrations at + boot. This is what makes a fresh checkout and an empty database work with no + configuration at all, and it is the right choice for development and for + small single-tenant deployments. The runtime DSN must be a member of + `ferroehr_migrator`, so the serving process holds DDL rights for its whole + life. Least isolation. +- **`verify`:** the server issues **no DDL at all**. At boot it checks that the + database carries exactly this build's migrations and refuses to start + otherwise, naming the schema and what is wrong with it. The pools can then + hold no schema rights at all, which is the least-privilege production + posture: an application-level SQL flaw can reach rows, never the schema. The + check itself still reads every schema's bookkeeping, so it runs on + `[database] migrate_url`; see [which credential prepares the + schema](#which-credential-prepares-the-schema), and set that key whenever + `database.url` is a role that holds one domain. + +Migrations are **append-only** within a major release line: a released +migration is never edited, because sqlx records a checksum of each applied file +and refuses a database whose recorded checksum no longer matches, so a +corrected schema arrives as a new migration rather than as a change to an old +one. A CI guard fails any pull request that modifies, renames or deletes a +migration a release carries. v6.0.0 starts the line again from one baseline per +schema, so a v5 database is not upgraded in place; see +[Upgrading from v5 to v6](upgrades.md#upgrading-from-v5-to-v6). + +With `verify`, something else has to run the migrations first. Use the binary's +own subcommand under the migrator DSN: a CI/CD stage, a one-shot job, or the +Helm chart's `migrations.job.enabled` pre-install/pre-upgrade hook Job, which +Helm waits on so a failed migration fails the release (it takes its own +`migrations.job.existingSecret` holding the migrator DSN, deliberately a +different credential from the runtime one, and rendering fails without it): + +```shell +FERROEHR__DATABASE__URL='postgres://ferroehr_migrator:***@pg:5432/ferroehr' \ + ferroehr db migrate # applies; exits when done +FERROEHR__DATABASE__URL='postgres://ferroehr_clinical:***@pg:5432/ferroehr' \ +FERROEHR__DATABASE__MIGRATE_URL='postgres://ferroehr_migrator:***@pg:5432/ferroehr' \ + ferroehr db verify # read-only check; exit 0 iff the schema is current +``` + +`db verify` splits the same way the boot sequence does, and for the same +reason: the schema state is read on `migrate_url`, while the pseudonymisation +boundary is measured on the runtime DSNs; asking the migrator credential +whether it can reach every domain would answer yes by design and tell you +nothing about the roles that serve requests. + +Gate the rollout on the migration step so two server versions never race the +schema. Note the difference in failure shape: a `verify` server refuses to boot +against an unmigrated database (loud, immediate), while an `apply` server that +loses its schema later stays up and reports readiness `DOWN`, the warning +below. + +> [!WARNING] +> **Migration is a boot step, and nothing re-runs it.** A running instance whose +> database is replaced, wiped, or reachable-but-empty does not migrate. It reports +> +> ```json +> {"state":"down","phase":"serving","indicators":[{"name":"db","state":"up"}, +> {"name":"migrations","state":"down"}]} +> ``` +> +> on `/health/readiness` (`503`), with the detail `core schema tables missing +> (migrations not applied)` on `/management/health`, leaves the load balancer's rotation, and keeps +> passing liveness (correctly, since the process is healthy) so nothing restarts +> it. Under Kubernetes that is a Deployment sitting at `0/N` ready with no error +> after the first one. +> +> The readiness check re-tests the schema on **every probe**, so recovery does not +> require a restart *of that instance*: it goes back to `UP` within one probe +> interval of the schema existing, whoever created it. What needs a restart is the +> case where the only thing that would migrate is the instance itself: then +> `kubectl rollout restart deploy/ferroehr` (or a migration job) is the remedy. +> +> For the out-of-band flow this means: the migration step must **complete before** +> the first instance starts, or that instance sits unready until the schema +> appears, harmless but confusing, and it delays the rollout rather than failing +> it. Gate the rollout on the migration job. + +### Planner statistics of the partitioned tables + +`node`, `version` and `vo_attestation` are partitioned by storage tier in both +stores, and PostgreSQL estimates a join over them from the statistics of the +partitioned table itself. Autovacuum analyzes the partitions and never the +partitioned table (PostgreSQL 19, Updating Planner Statistics), so +FerroEHR runs `ANALYZE ONLY` on the partitioned tables itself, and on `ehr` +while autovacuum has never analyzed it: + +- after it applies the migrations, as the migration credential; +- after `load_ehrs` loads an archive; +- at boot and then every hour, as each store's serving role. + +Without these statistics an AQL `CONTAINS` can read every COMPOSITION's +nodes. `ANALYZE` needs the `MAINTAIN` privilege on the table, and the +migrations grant it to `ferroehr_clinical` on `clinical.node`, +`clinical.version`, `clinical.vo_attestation` and `clinical.ehr`, and to +`ferroehr_party` on the three partitioned tables of `party`. When a serving +role still lacks it, for example because the roles were absent when the +migrations ran, the hourly refresh logs a warning naming the tables it could +not analyze. Grant the role `MAINTAIN` on those tables, or run the same +`ANALYZE ONLY` from a scheduled job as the migration role. + +### Recovering a partially wiped database + +A wipe that removes *some* of the server's schemas is not a fresh start, and the +server cannot tell it from one. + +The server owns four schemas: `ext`, `clinical`, `party` and `audit`. +A fresh start drops all four. Each domain's cold archival tier is a **partition** +of the relation it archives, inside that domain's own schema, so a +`DROP SCHEMA clinical CASCADE` takes the archived rows with the live ones. There +is no separate mirror schema left to survive a wipe of the tier it mirrors. + +Dropping some of the schemas is not a supported reset, because they are not +independent. `ext` holds the helper functions the `clinical` and `party` +relations depend on, so `DROP SCHEMA ext CASCADE` drops them with it, and those +sets, still recorded as applied, never recreate them. The next boot rebuilds +the dropped schemas, and its +migration check reads each set's bookkeeping only, so it passes over a database +that has lost those guarantees. + +A database written by a release before the storage rewrite is refused outright: + +```text +this database predates the storage rewrite: schema `ehr` carries its own +migration bookkeeping, which only a release before the rewrite wrote. +``` + +The new migration sets replace the old ones rather than upgrading them, so there +is no in-place path. Dump anything worth keeping, recreate the database, and +start the server against it. + +> [!TIP] +> When you wipe a FerroEHR database deliberately, drop the **database**, not a +> schema. `DROP DATABASE` cannot leave half a repository behind, and it is the +> only wipe with no partial-state failure mode. `ferroehr db erase` drops all +> four schemas of a database in one transaction, for taking an instance out of +> service ([Decommissioning](operations-decommissioning.md)). + +## Backup and point-in-time recovery + +Enable WAL archiving and point-in-time recovery from day one (pgBackRest or a +managed PITR), because a CDR's data is not reconstructible. Clinical and audit +tables are never `UNLOGGED`. Test your restore, not just your backup. + +### Dump each domain separately + +A logical backup is where the two pseudonymisation domains are easiest to +re-join by accident. One `pg_dump` of the whole database produces a single file +holding the pseudonymised clinical record beside the identities of its +subjects, and whoever can read that file can re-identify every record in it, +which is the separation the schema split and the database roles exist to +maintain. **Two domains, two dumps**, into targets with different access +control. + +**How many dumps, by DSN layout.** The number of dumps follows the domains, not +the databases: co-located, the three domains share one database and are dumped +`--schema` by `--schema` as below; relocated, each database is dumped for the +domains that live in it. What never changes is that the clinical record and the +identities land in two different artefacts with two different audiences. `ferroehr config check` prints the resolved layout, which is the +list a backup runbook is written from. The audit repository travels with the +clinical dump while it shares that database (`--schema=audit` below) and needs a +dump of its own once `[database.audit]` names another one. On Kubernetes that +third dump is not yours to schedule: the chart renders a `backup.audit` +CronJob as soon as `database.audit` carries a Secret of its own, and drops +`--schema=audit` from the clinical job in the same render. + +```bash +# The clinical domain +pg_dump --dbname="$CLINICAL_DSN" --format=custom --no-owner \ + --schema=clinical --schema=ext --schema=audit \ + --file=/backups/clinical/clinical-$(date -u +%Y%m%dT%H%M%SZ).dump + +# The identities, into a different directory, owned by a different group +pg_dump --dbname="$PARTY_DSN" --format=custom --no-owner \ + --schema=party \ + --file=/backups/party/party-$(date -u +%Y%m%dT%H%M%SZ).dump + +# The audit trail, ONLY when [database.audit] names a database of its own — +# co-located it is in the clinical dump above, and dumping it twice is a second +# copy of who read what +pg_dump --dbname="$AUDIT_DSN" --format=custom --no-owner \ + --schema=audit \ + --file=/backups/audit/audit-$(date -u +%Y%m%dT%H%M%SZ).dump +``` + +Which EHR belongs to which subject is the EHR's own `EHR_STATUS.subject`, so +it travels in the clinical dump. + +The clinical and party examples ship. In Compose they are the opt-in `backup` +profile: + +```bash +docker compose --profile backup run --rm ferroehr-backup-clinical +docker compose --profile backup run --rm ferroehr-backup-party +``` + +Set `FERROEHR_BACKUP_CLINICAL_DIR` and `FERROEHR_BACKUP_PARTY_DIR` to the two +targets; they default to `./backups/clinical` and `./backups/party`. +Run it as yourself (`FERROEHR_BACKUP_USER="$(id -u):$(id -g)"`) and the dump +lands owned by you. Left unset, the job runs as root inside the container and +keeps one capability, `DAC_OVERRIDE`, because that is what writing a directory +it does not own actually requires: the container drops every other capability, +and without this one uid 0 is just another user against your directory's +permission bits. Everything else stays off: no privilege escalation, read-only +root filesystem. +Under Kubernetes the chart renders one `CronJob` per domain; see the chart's +`backup` values. + +> [!WARNING] +> **A backup credential is not the application role.** Each domain's runtime +> role is revoked from the other domains, which is the pseudonymisation +> boundary doing its job, so a dump taken through one of them is silently +> partial rather than refused. Give each backup job its own role, read-only on +> its own domain and nothing else. + +Two further properties are yours to arrange, because no configuration file can +enforce them: the two targets carry **different** access control, and the +credential each job uses reaches **one** domain. Give the demographic job the demographic +DSN once you run two ([Deploying](installation/kubernetes.md)); with a single +credential you have separated the artefacts but not the authority to produce +them. + +> [!NOTE] +> Point-in-time recovery stays instance-wide. All the domains live in one +> cluster, so a WAL archive covers them together and a recovery target restores +> them together. The separation this section is about is the logical dump. + +### Restoring + +A restore is not finished when `pg_restore` exits. The grants are the +boundary: a database whose roles came back wrong is a database where the +clinical role can read the identities, so re-apply the role grants before the +server starts, then let the server check them: + +```bash +createdb ferroehr_restored +pg_restore --dbname=ferroehr_restored --no-owner clinical-….dump +pg_restore --dbname=ferroehr_restored --no-owner demographic-….dump +# then, before anything serves traffic: +ferroehr db verify +``` + +Restore the clinical dump first. It is the one carrying the `ext` schema, whose +helper functions the other domains' relations depend on. + +`ferroehr db verify` issues no DDL. It checks that the database carries exactly +this build's migrations, **all four sets**, so a restore that skipped a domain +is refused by name, and that no runtime role can read across the domain +boundary, exiting non-zero when either is untrue. It is the same check the +server runs at boot, which is why a server pointed at a badly restored database +refuses to start rather than serving from it. + +What it does **not** read is a constraint. `pg_restore` ignores a failed +statement unless you pass `--exit-on-error`, so a table can come back with its +rows and without a key while every check above stays green. Read the restore's +own output. + +Restoring only one domain is a supported outcome, not a mistake: a demographic +dump restored on its own gives a database with identities and no clinical +record, which is what a rehearsal of the identity domain's recovery looks like. +Such a database is not one the server will serve from: `ferroehr db verify` +refuses it for the domains that are missing, which is the correct answer for a +rehearsal target. diff --git a/website/book/src/ehds-logging.md b/website/book/src/ehds-logging.md new file mode 100644 index 0000000000..05b7a4e121 --- /dev/null +++ b/website/book/src/ehds-logging.md @@ -0,0 +1,502 @@ +# The EHDS logging elements + +How each element EHDS Annex II 3.2 asks a log to record maps onto FerroEHR's records. + + + +## The EHDS logging elements, mapped + +Annex II 3.2 of [Regulation (EU) 2025/327](https://eur-lex.europa.eu/eli/reg/2025/327/oj) +lists five things the European logging software component must record "on every +access event or group of events". This is where each one lands, or does not. +The elements were read from the published text on 2026-09-10; the regulation is +the authority and the wording below is a paraphrase. + +| Annex II 3.2 | Access-event field | DICOM PS3.15 | FHIR `AuditEvent` | State | +|---|---|---|---|---| +| (a) the healthcare provider or other individuals having accessed | `provider` of the binding (the provider of the caller's party binding, read from the CDR), or the `organisation` record of a verified external organisation | — (no such attribute) | the `acts-for` detail of the `ehds-accessor` entity | Recorded | +| (b) the specific natural person or persons having accessed | `principal` (+ `token_id`, `client_ip`), and `professional_id` + `acting_mode` for a caller its issuer classifies as a person or a delegate | `ActiveParticipant/@UserID` (the professional; a client application acting for one is a second, non-requesting participant; the token subject is `@AlternativeUserID` when it differs) | the `agent:user` slice, `who` the token's issuer and subject, the professional's identifier as its `ihe-otherId`, and the client application as an agent of its own (BALP 1.1.4 §3:5.7.5.4) | Recorded | +| (c) the categories of data accessed | `categories` + `category_basis` + `category_evidence` + `category_map_digest`, classified by `ehds-logging` through the audit category register (beside `resource_class`, `domain` and `result_count`) | none (no such element) | the `entity` named `ehds-categories`, with one `ehds-category` detail per category and its basis, each id the classification read and the map digest; each category is also a `meta.security` label | Recorded | +| (d) the time and date of access | `recorded_at` | `EventIdentification/@EventDateTime` | `recorded` | Recorded | +| (e) the origin or origins of data | `origins` + `origin_count` (the `FEEDER_AUDIT` originating systems of the served version bodies, or the server that created them, derived at commit onto `version.origins`) | — (no such element) | one `entity` named `origin` per origin, its `system-id` detail the originating system | Recorded | + +Read (a) beside (b): they are both about the accessing side, and the pair +distinguishes the **organisation** on whose behalf the access happened from the +**natural person** who made it. The principal answers (b); the provider of the +caller's party binding answers (a). It is read from the CDR, never from a token +claim, so the provider a record names is the one the deployment bound the +caller to. A caller with no binding, such as a Basic user with no `PERSON`, +leaves it empty rather than guessed. + +Element (b) asks for a **natural person**, and a bearer token can name a client +application instead. Each issuer's [`kind` and profile](security.md#assurance-level-and-the-natural-person-on-patient-data) +classify the caller, so every record says which it was and who stood behind it: + +| Field | Meaning | DICOM PS3.15 | FHIR `AuditEvent` | +|---|---|---|---| +| `acting_mode` | `person` when the token names a natural person, `client` when it names a client application | the participant split below | the agent split below | +| `professional_id` | the natural person: the person's own claim, or the professional a client token acts for | `ActiveParticipant/@UserID` of the requesting participant | the `ihe-otherId` extension of the `agent:user`, typed `NPI` | +| `principal` | the token subject, as before: the client application in `client` mode | a second `ActiveParticipant` with `UserIsRequestor="false"` and the network address; `@AlternativeUserID` in `person` mode when it differs from the professional | `agent:user` `who.identifier`, with the issuer as its system; the acting mode is its first `role` | +| `assurance_level` | the eIDAS level (`low`, `substantial`, `high`) the token's assurance claim maps to under `[authz.assurance]` | none (no such attribute) | the `ihe-assuranceLevel` extension of the `agent:user` | +| `assurance_value` | the raw claim value the level was read from, usually `acr` | none | none | + +[PS3.15 §A.5](https://dicom.nema.org/medical/dicom/current/output/chtml/part15/sect_A.5.html) +gives `ActiveParticipant` no assurance attribute, so the DICOM message and the +syslog feed carry no level. The FHIR export carries the level as the BALP +`ihe-assuranceLevel` extension (BALP 1.1.4 §3:5.7.5.4) and never the raw claim +value, which lives in the local store's column only. The tamper-evidence digest covers both columns, like every other column of +the record (see [Tamper evidence](audit-integrity.md#tamper-evidence) for records written before +the digest was versioned). + +For a system caller the mode and the professional stay empty and (b) is +answered by `principal`, which names the client application. Without `[authz.assurance] levels` the level stays empty; +the raw value is still recorded when the token carries the claim. A Basic +credential records none of the four. + +Element (c) asks for the **priority category** of the data, in the sense of +Art. 14(1): patient summaries, electronic prescriptions, electronic +dispensations, medical imaging, medical test results and discharge reports, +plus any category a Member State adds in national law. AQL selects archetypes +and templates, never categories, and no openEHR specification maps the one +onto the other, so the deployment declares the mapping in +[the audit category register](installation/config-audit.md#the-audit-category-register), an +[admin register](access-policy.md#the-admin-registers): a +template id, or failing that the root archetype id, maps to a set of categories +(a priority category by its code in HL7 Europe's +`EEHRxFDocumentPriorityCategoryCS`, such as `Patient-Summaries` or +`Laboratory-Reports`, a national category as its `|`), or to +`none` for content that holds no data of any category. While you declare no +template and no archetype, the map FerroEHR ships applies: the published CKM +templates and COMPOSITION archetypes whose data sit in one priority category +([the shipped map](installation/config-audit.md#the-audit-category-register)). Your own +map replaces it, and `ehds-logging` classifies each access through the map in +force. + +Each record is classified when the access happens, from what it served or +wrote, and never at commit, because the map is your reading of your templates +and can change: + +- a composition read or write is classified by the version's template id, then + by its root archetype id; +- an AQL execution is classified by the template and root archetype ids of the + versions its result page came from; where the answer carries no version (a + `DISTINCT` or aggregate projection, or zero rows) by the query's positive + archetype and template constraints, so an operand under `NOT CONTAINS` or a + predicate under `NOT` never counts. Every id the query constrains to must be + mapped, and every content operand bound to an id, or the record is + `unclassified` beside what did map. Each per-EHR record of a query carries + the categories that EHR disclosed; +- a logical delete writes no content, so it is classified by the version it + deleted; a `VERSIONED_COMPOSITION` read by the composition it holds; +- a `CONTRIBUTION` read, with or without `Prefer: resolve_refs`, is classified + by the versions the contribution committed, a deleted version again by the + version it deleted; +- an EHR Extract export is classified by every version it carried, and an + Extract import by the newest content of every versioned object it landed; +- `EHR`, `EHR_STATUS`, `EHR_ACCESS`, the directory, item tags and revision + histories are recorded as `none`, by resource kind. + +An access the map cannot classify is recorded `unclassified`, with the +template and archetype ids as evidence, and is never refused; the FHIR record +says why (`unmapped`, `unbound`, `named-nothing`). A stored category is its +`|` token. `category_basis` says what the classification was read +from (`returned`, `written`, `queried` or `resource-kind`; records written +before 5.3.2 carry `template`, `archetype` or `query` and the earlier +spellings), and `category_map_digest` names the map that produced it, so a +later map never rereads an old record. The map's +digest is also on the boot line and on `GET /management/info` under +`audit.category_map`. The classification stays in the access log: it is never +written to the request log, a span or a metric label. The DICOM rendering has +no element for it (PS3.15 §A.5), so it travels in the local store and the FHIR +export only. + +Records in the demographic domain carry no classification, because no +priority category lives there. + +Element (e) asks where the DATA came from, which is not where the request came +from. openEHR models that provenance as `FEEDER_AUDIT` on the content itself, +so every committed version records the distinct set of +`FEEDER_AUDIT.originating_system_audit.system_id` values found in its body, or +this server's own system id when it carries none. A composition, status or +folder read then records the origins of the version it served, and an AQL +execution the union over the version rows its result page came from. The record +carries the true distinct count beside a set capped at 32, so a page drawing on +more origins than that says how many rather than looking complete. A version +committed before the column existed is assessed when it is read. + +One further element, adjacent to the five: **the declared purpose of use +reaches one export of the two**, and only one of them could carry it. It is +stored on the record, served by ITI-81, and rendered as +[`agent.purposeOfUse`](https://hl7.org/fhir/R4/auditevent.html) on the +requesting person's agent in the FHIR export. A declared code carries no +system: the vocabulary is the one you agree with your callers in `[audit] +purpose_codes`, which has no published code system URI, and attributing the +code to a system it does not come from would misdescribe it. A purpose the +access token states keeps the system the token gives it. +The +[DICOM Audit Message schema](https://dicom.nema.org/medical/dicom/current/output/chtml/part15/sect_A.5.html) +of PS3.15 §A.5 defines no purpose element at all (`EventIdentification`, +`ActiveParticipant`, `AuditSourceIdentification` and +`ParticipantObjectIdentification`, and none of them carries one), so on that +side it is a limit of the format, not something this code withholds. + +### Where the purpose of use comes from + +The purpose of use reaches the record from two places: + +- **The access token.** An issuer with an `[auth.issuer..attributes]` table + (`mapping = "iua"`) states its professionals' attributes in the token: the + IHE IUA `purpose_of_use` and `subject_role` claims under + `extensions.ihe_iua` (IHE ITI TF-2 §3.71.4.2.2.1.1), and with + `authorization_details_purposes` the `purpose_of_use` of each RFC 9396 + `authorization_details` entry. The record stores them in + `token_attributes`, and both renderings write them with their code systems: + the purposes at the requesting agent's `purposeOfUse`, the roles at its + `role`, beside the roles the caller held. +- **The `[audit] purpose_header`** (`x-purpose-of-use`), which the caller + sets. It works alone for an issuer without an `[auth.issuer..attributes]` table, + as before. + +The token is the authorization server's statement, so it decides. A request +whose header names a purpose the token, which states purposes, does not +state is refused with `403`, and the refusal is recorded as a failed +authentication naming the caller and the token's purposes. A header naming +one of the token's purposes is admitted and recorded with both. Which source +wins is FerroEHR's own design; no openEHR specification governs the purpose +of use. + +> [!NOTE] +> Every row of this table is asserted by a test +> (`app/ferroehr/tests/it/audit_ehds_mapping.rs`), **including the gaps**: the +> tests that record an absence fail the day the field arrives, so the table and +> the code cannot drift apart in either direction. + +The common specifications the regulation's Article 36 provides for have not +been adopted. When they are, this mapping is re-verified against them rather +than assumed to still hold; see the +[EHDS readiness page](https://ferrohealth.eu/docs/ehds/readiness.html). + +### The binding outcome + +Every record of an authenticated request carries `binding`: how the caller +was bound to a demographic party, or why the binding refused it. The +committer the same request writes into a version is on +[Who is the committer](security/committer.md). It answers +Annex II 3.2(a) and (b) where the token's subject alone does not. The columns +beside it hold what each outcome needs: + +| `binding` | The caller | Recorded beside it | +|---|---|---| +| `bound` | a person bound to a `complete` `PERSON` | `party`, `party_groups`, `provider`, `representation` for a representative, `actor_chain` for a delegated token | +| `provisional` | a person bound to an `incomplete` `PERSON` | `party`, `party_groups`, `provider` | +| `external` | a verified external person of a `federation` issuer | `external_fields`, `agreement`, `provider` | +| `organisation` | an organisation under an agreement with `accessor = "organisation"` | `external_fields`, `agreement` (with its legal ground and access class, and for a `chained` request `correlation_id` and `correlation_source`), `provider` | +| `system` | a client acting for nobody | `party`, the client's `ACTOR` in the policy parties; `provider`, the identifier of the `ORGANISATION` its acts-for relationship targets; `facilities` of the compositions it committed | +| `self` | the record's person, whose login the party binding binds to the `PERSON` an EHR's subject names | the principal; `party`, that `PERSON` | +| `refused-*` | a refusal of the binding or of a caller kind: `unbound`, `ambiguous`, `inactive`, `abandoned`, `deprovisioned`, `wrong-marker`, `representation-unrecorded`, `key-claim-missing`, `groups-unavailable`, `external-incomplete`, `trc-patient-mismatch`, `trc-missing`; and of a caller kind, `system-personal-scope` (a system caller holding a `user/` or `patient/` scope), `no-agreement` (no federation agreement admits the accessor) and `scope-beyond-agreement` (an external caller holding a scope its agreement does not read) and `correlation-missing` (a `chained` organisation request without an attested correlation id) | `party` for a party refused for its state or marker, `binding_detail` for what else the refusal names (`represented`, the subject a representative asserted; `claim`, the name of the key claim a token lacked, never its value) | + +`acting_mode` is `person`, `delegated` for a person through a declared client +or actor, `external` for a verified external accessor and `system` for a client +acting for nobody (`client` remains on records written before). The FHIR +`AuditEvent` writes each mode as the person's `agent.role`. A record of a +request with no authenticated caller carries no binding. The columns are in the +chain digest: version 2 hashes them, version 3 adds `token_attributes`, a new +record is version 3, and a record written before keeps verifying under its own +version. + +#### The binding fields in the renderings + +Neither BALP 1.1.4 §3:5.7.5.4 nor DICOM PS3.15 §A.5 has an element for the +binding fields beyond the bound person, so `ehds-logging` writes them as +details of two entities it adds, and FerroEHR hands it every field. The FHIR +`AuditEvent` carries each entity as an `entity` with its `name` and one +`detail` per value. The DICOM message carries each as a +`ParticipantObjectIdentification` of type `4` (Other) with the entity name as +its `ParticipantObjectName` and one `ParticipantObjectDetail` per value +(RESTful ATNA Rev. 3.6 Table 3.20.4.2.2.1-1), and the ITI-20 syslog feed +sends that message. Both renderings take the detail list from +`ehds-logging`, so they never disagree. + +| Recorded field | Rendered as | +|---|---| +| `binding` | `ehds-accessor`: `binding`, with `security-event` for `refused-trc-patient-mismatch` and `refused-trc-missing` | +| `party` | `ehds-accessor`: `party` as `\|\|`; in the FHIR `AuditEvent` also the person's `otherId` typed `PRN` | +| `party_groups` | `ehds-accessor`: one `group` per group, in the party's namespace with type `GROUP` | +| `provider` | `ehds-accessor`: `acts-for` as `\|` | +| `facilities` | `ehds-accessor`: one `facility` per facility, as `\|` | +| `representation` | `ehds-accessor`: `represents`, `represents-ground` and `represents-relationship`; a refusal's `represented` as `represents` alone | +| `actor_chain` | `ehds-accessor`: one `actor` per actor, `\|`, outermost first | +| `binding_detail` | `ehds-accessor`: `binding-claim` for `refused-key-claim-missing` | +| `external_fields` | `ehds-relayed`, marked `asserted` and naming the issuer by `relayed-issuer`: each 2026/2099 Annex field and eHDSI SAML attribute at its own detail (`hp-family-name`, `hp-identifier`, `provider-identifier` and the others), `consent.reference` as `agreement-consent`, and every other field as `asserted-field` `=` | +| `agreement` | `ehds-relayed`: `agreement-name`, `agreement-version`, `agreement-legal-ground` and `agreement-access-class` | +| `correlation_id`, `correlation_source` | the FHIR `AuditEvent`: `correlation-id` and `correlation-source` of the request id's entity; the DICOM message: the same two details of `ehds-relayed`, since it carries no request entity | +| `acting_mode` | the FHIR `AuditEvent`: the person's `agent.role`; DICOM: none | + +Every value goes through the renderers' escape: a control character, a +bidirectional control or a line separator is written as its code point, and +no value is cut. A DICOM detail value is base64-encoded as given (PS3.15 +§A.5.1.1). A binding record that lacks a field its code needs fails the +rendering, and the sender reports the failure, never a record without the +binding. + +### Refusal records and their budgets + +Every refused request is recorded as a failed user authentication, through the +same path as an operation record: a refusal whose record cannot be written is +answered `503`. A refusal of +the login binding or of a caller kind carries its `refused-*` code. Refusals +are charged to one of two budgets, which never draw on each other, so a flood +of invalid tokens cannot hide a verified caller's probing: + +| Budget | Charged to | Per caller in a window | Per window | +|---|---|---|---| +| Failed verification | the source network: the `/24` of an IPv4 address, the `/64` of an IPv6 one | 10 | 1000 | +| Verified caller | the token's `iss` and `sub` | 10 | 1000 | + +A window lasts 60 seconds. Past a caller's 10 records the rest of its +refusals in that window become one summary record, written when the window +closes: it names the caller and carries `summary`, the count and the EHR ids +the refused requests named (at most 64, while the count stays exact). Past a +budget's 1000 records, the refusals of every caller not yet recorded in that +window become one summary record per issuer and outcome, naming no caller. A +security event (`refused-trc-patient-mismatch`, `refused-trc-missing`) is +recorded once for every answered request and never summarised. A federation +caller above its agreement's `caller_rate`, a contact point's included, is +answered `429` before any patient lookup, and every such refusal goes into +that caller's summary record from the first, with `binding_detail` naming +`caller-rate`, so the count of security events stays bounded. A refusal +record the system log cannot take is counted in +`atna_audit_refusals_unwritten` and logged at `error`. + +> [!NOTE] +> The limits, the windows and the budgets are kept **per replica**. Behind a +> load balancer with three replicas, one caller can have up to 30 refusals +> recorded one by one in a window before the summaries begin, and each replica +> writes its own summary records. + +### Access through FerroBRIDGE's FHIR facade + +The openEHR REST API carries no end-user identity on a read, so when +FerroBRIDGE's FHIR facade reads or writes through FerroEHR, FerroEHR's record +names the bridge's credential under (b) and cannot name the natural person +behind the FHIR request. From FerroBRIDGE 0.0.16 the bridge records each +facade access itself when its `[audit]` section is on: it writes the Annex II +3.2 record with the person, the categories, the time and the origin through +the same `ehds-logging` crate, and sends it as an IHE BALP `AuditEvent` +through `ihe-atna` over the ITI-20 FHIR feed to the Audit Record Repository +you configure there. The bridge refuses a facade access whose record it +cannot take. Read the two records together: FerroEHR's says which data left +the CDR and to which client, and FerroBRIDGE's says which person asked for +it. FerroBRIDGE's +[access record](https://ferrobridge.eu/docs/operate/access-record.html) page +describes its record and its configuration. + +### Justified and emergency access + +A clinician opens a record outside their care relationships on a +[justification](access-control.md#justified-access-outside-the-care-relationships) +of your access policy, with a reason in `x-access-reason`; an emergency is a +justification that also lifts what EHDS Art. 11(5) lets an emergency lift. +Art. 11(5) requires such cases to be "logged in a clear and understandable +format" and "easily accessible for the data subject", and Art. 9(1) and +Annex II 3.2 count every access among the ones the person is told about. +FerroEHR records what the access decision rested on, never what the request +merely declared: + +- **The stored record:** the `justification` column holds the kind + (`justification` or `emergency`) and the reason as the clinician wrote it. + It is `NULL` for an access that rested on a care relationship or anything + else, and for a refused justified access, which names its refusal + instead; an emergency is recorded even when the access was refused. +- **The access-log entry:** the `justification` or `emergency` authorisation + under `ACCESS_POLICY` and its version, with the `reason`. +- **The FHIR `AuditEvent`:** the reason is the `text` of the + `CodeableConcept` beside the declared code on `purposeOfEvent` and on the + requestor's `agent.purposeOfUse` (FHIR R4 `AuditEvent`, IHE BALP). An + emergency also carries the `entity` named `ehds-emergency-access` that + `ehds-logging` writes, whose `description` states the mark in plain words + ("Emergency access: the accessor declared that the access was necessary + to protect the vital interests of the data subject (Regulation (EU) + 2025/327 Art 11(5)).") and whose `ehds-emergency-purpose` detail names the + purpose that invoked it. An app keys on the entity and shows its + description, and shows the reason for every justified access. +- **The DICOM syslog feed:** neither the reason nor the mark; the message + FerroEHR writes there carries no purpose of use. + +```mermaid +sequenceDiagram + participant C as Clinician + participant F as FerroEHR + participant S as Audit store + participant P as Patient (ITI-81) + C->>F: read, purpose ETREAT, reason "Unresponsive on arrival" + F->>F: emergency justification invoked, restriction lifted + F->>S: access record, justification {emergency, reason} + F-->>C: 200 + P->>F: GET AuditEvent?patient=... + F->>S: subject-scoped search + F-->>P: purposeOfEvent ETREAT with the reason, ehds-emergency-access entity +``` + +The person reads their own log, every justified access included, through the +[subject-scoped ITI-81 retrieval](audit-integrity.md#retrieving-audit-records-iti-81), and the +access-log resource filters on `justification=justification` or +`justification=emergency`. + +A justification lifts no restriction of the patient. A composition or EHR +restricted under GDPR Art. 18 stays refused with any justification, an +emergency included, because Art. 18(2) admits processing only with consent, +for legal claims, for the rights of another person or for an important +public interest, and the person's own vital interests are not on that list. +An EHDS Art. 8 restriction of access by health professionals yields only to +an emergency justification, where the directive's `emergency_override` +holds +([restriction of access](access-control.md#restriction-of-access-by-health-professionals-ehds-art-8)). + +### Retention, and who chooses it + +The controller decides how long the log keeps a record, in its access policy +(`ACCESS_POLICY.log_retention`, written through +[`/admin/access_policy`](operational-policy.md)). FerroEHR provides the +mechanism and names no national law of its own. `log_retention` holds: + +- `in_union`: whether Regulation (EU) 2025/327 binds the controller. When it + does, Art. 9(2) keeps the access information "available for at least three + years from each date of access to the data", and FerroEHR refuses a shorter + period. +- `period`: how long each record is kept from the date of access, in whole + years (`P5Y`) or whole days (`P1826D`). Absent keeps every record without + end. +- `floors` and `ceilings`: the minimum and maximum periods the controller's + law sets, each with the provision that sets it, coded in the terminology the + jurisdiction names (an `ACCESS_RETENTION_BOUND`). + +A policy whose period breaks a floor or ceiling it declares is refused when it +is written, with `400`, and the version in force stays. So is a ceiling below +a floor, a ceiling with no period (a record kept without end outlasts every +ceiling), a controller outside the Union with no floor, and a period in any +unit other than years or days. Years are counted on the calendar: three years +admit `P1096D` as a floor but not as a ceiling, since 1 096 days can outlast +three calendar years. A new version applies to every record written after it, +on every replica, with no restart. + +**With no `log_retention`, every record is kept without end.** That meets +every floor, so the log never forgets evidence a data subject's right of access +is served from. It is also undecided: GDPR Art. 5(1)(e) makes the period the +controller's to set. The `log_retention` readiness indicator reads `degraded` +until the access policy states it, and the instance stays in rotation. `ferroehr +config check` reads only the configuration file, so it cannot see the policy; +check the indicator on `GET /management/health` after the first policy write. + +A stored policy version whose `log_retention` does not read (a damaged store; +the write check refuses one) is named and held loud. Each replica keeps the +last retention that read and records every access under it, so the access log +never stops, while the reaper purges nothing and the `log_retention` +indicator reads `down`, naming the version, until a version that reads is +committed. + +Every record stores the first date it may be deleted on, and the reaper +deletes each record hourly on or after that date and never before it. A +record outside the access log ends the day after its date of access plus the +period in force when it was written. + +**An openEHR access-log entry states its own retention.** Each +`ACCESS_LOG_ENTRY` carries an `ACCESS_RETENTION` when it is written: +`retain_until`, the last day it is kept; `grounds`, the provisions that set +the period; and `policy`, the version of the access policy it was taken from. +An entry kept without end states no `retain_until`. The grounds are Art. 9(2) +for a controller in the Union, coded by the regulation's European Legislation +Identifier with the subdivision as the code +(`http://data.europa.eu/eli/reg/2025/327/oj`, `art_9.par_2`), then each +declared floor and ceiling as the controller coded it. The ELI coding is our +own design (Council conclusions 2012/C 325/02 define the identifier). The +same hourly worker replaces every entry whose `retain_until` has passed by an +`ACCESS_LOG_TOMBSTONE` in place, in any order of expiry. The tombstone keeps the +entry's uid, `system_id` and `time_recorded`, names the grounds of the period +that ended, and holds nothing else of the entry; its row keeps the entry's +content digest, so its window's seal verifies after the content is gone +([Tamper evidence](audit-integrity.md#tamper-evidence)). A +tombstone is never replaced again, and the database refuses any other change +to it. An erasure a law orders before the period ends takes the same path +through `POST {ext}/admin/access-log/erase`, with the law's provisions as the +tombstone's grounds; the erasure is an access record of its own +(`access-log-erasure:`) naming the administrator +([Admin APIs](operations-admin-apis.md)). + +**A tombstone is kept as long again, then its window folds.** A tombstone +holds no EHR, no accessor and no purpose, but its content digest is a hash +of the entry it replaced, and a copy of that entry elsewhere (a forwarded +BALP `AuditEvent`, an export, a backup) can be matched against it. It is +kept only while its window needs it to verify (GDPR Art. 5(1)(e)): for one +more retention horizon, its entry's own, so a tombstone stays as long after +its removal as its entry was kept before it. Once every record of a sealed +window is a tombstone past its end, the same hourly run removes the +window's entries and records the window as folded +(`audit.access_log_seal_fold`), with every ground its tombstones named and +when it was folded. The window's seal stays, so the seals still follow one +another, and a record that leaves the log any other way is reported as +tampering. A window folds whole: an entry kept longer keeps its window's +tombstones until it has folded too. An erasure a law orders is a tombstone +like any other and folds the same way. Several replicas fold on a +PostgreSQL advisory lock, so no window is folded twice. The metrics are +`access_log_folded_total` and `access_log_gaps_total` +([Access path](operations-access-path.md)). No configuration key sets the +second horizon. No openEHR specification governs audit retention: our own +design. + +**An imported entry ends at its own `retain_until` too.** An entry imported +with an EHR from another system +([Seals, checkpoints and the transfer of a log](audit-integrity.md#seals-checkpoints-and-the-transfer-of-a-log)) +keeps the `retain_until` its recording system stated, and the same hourly +run replaces it by its tombstone once that day has passed, on the entry's +own grounds. Its tombstone is kept as long again, as a local one is, and +then folds, leaving its uid, its bundle and its content digest +(`audit.access_log_imported_folded`), so its bundle still verifies. The +metrics count both logs, with `chain` = `local` or `imported`. No openEHR +specification governs this: our own design. + +Choosing the period is a legal question for the controller. NEN 7513 is the +Dutch reference for this log and the Besluit vaststelling bewaartermijn +logging sets its five years; SGB V § 309 Abs. 1 caps the German +telematics-infrastructure log at three years; DSV Art. 4 Abs. 5 keeps a Swiss +log at least one year. A controller bound by one of them declares it as a +floor or ceiling with its provision. Art. 9 applies from 26 March 2029 for +patient summaries, prescriptions and dispensations and from 26 March 2031 for +the other priority categories (Art. 105). FerroEHR holds the Art. 9(2) floor, +so a log kept today already meets it when Art. 9 applies. One instance serves one access policy, so two controllers needing +different periods run two instances. +The retention in force is the access policy's (`GET {ext}/admin/access_policy`). +A record takes about 1.2 KB on disk, so the period decides how far the log +grows ([Storage sizing](storage-sizing.md#audit-retention)). + +### The access log at steady state + +With entries written at a rate of `r` a day and kept for `P` days, the log +levels off once the first tombstones fold, after `2P`: + +- the entries of the last `P` days: `r × P ×` the bytes per entry; +- their tombstones, kept another `P` days: `r × P ×` the bytes per tombstone; +- the seals: one row a minute, and one folded-window row for each window the + fold removed, kept without end. + +The performance gate's run summary states the bytes per entry and per +tombstone of the release it measures. `VACUUM` reuses the space a fold frees +for later rows (PostgreSQL 19 docs, Routine Vacuuming, Recovering Disk Space). + +### Getting the log out + +Three routes, and they answer different questions. + +- **The access log over ITS-REST:** the [access-log + resources](access-log.md#reading-the-access-log-over-its-rest) serve the openEHR + access-log entries: one EHR's log to the person it is about and their + representative, and the full log to a reviewer. This is the person's own + route (EHDS Art. 9(2)). +- **ITI-81 retrieval:** the [audit search](audit-integrity.md#retrieving-audit-records-iti-81) + serves the records back as FHIR `AuditEvent` resources, filtered by patient, + agent, date and outcome. This is the operator's route and the one an IHE + Audit Consumer uses: everything Annex II 3.2 records is reachable through + it, including the purpose and the organisation, which the syslog feed's + DICOM form cannot carry. +- **The BALP feed:** records fan out to syslog and to a FHIR feed as they are + written, for a SIEM or a central Audit Record Repository. diff --git a/website/book/src/explanation/access-model.md b/website/book/src/explanation/access-model.md index b7af343f81..e7c13a0f39 100644 --- a/website/book/src/explanation/access-model.md +++ b/website/book/src/explanation/access-model.md @@ -276,7 +276,7 @@ concept, and each is set and lifted through the admin API by the controller. The details are in [Retention, restriction and objection](../compliance/retention.md) and -[Security](../security.md#delayed-access-by-the-person-ehds-art-33). +[Security](../access-control.md#delayed-access-by-the-person-ehds-art-33). ## How one request is decided diff --git a/website/book/src/getting-started.md b/website/book/src/getting-started.md index 95b08fb5ce..b806e52f3e 100644 --- a/website/book/src/getting-started.md +++ b/website/book/src/getting-started.md @@ -210,7 +210,7 @@ curl -u ferroehr:ferroehr -H 'Content-Type: application/json' -d '{ }' http://localhost:8080/ferroehr/rest/openehr/v1/query/aql ``` -[Querying with AQL](querying-aql.md) is the full language guide — parameters, +[Querying with AQL](querying-aql.md) is the full language guide: parameters, stored queries, version scope, terminology, pagination, and the supported feature set. @@ -228,18 +228,21 @@ drift from the routes it actually serves. When authentication is enabled the "Authorize" dialog shows the one scheme the server is configured for (HTTP Bearer/JWT when OIDC is set up, otherwise HTTP Basic). The hosted sandbox runs the same UI at if you -want to try it before running anything locally — and +want to try it before running anything locally, and itself opens the [viewer](viewer/index.md) on that server, with the demo credentials `ferroehr` / `ferroehr`. ## Next steps -- [Installation](installation/index.md) — running it for real (Compose, +- [Your first integration](tutorials/first-integration.md): the requests an + application sends, from a template to an AQL query, with versioning and + errors. +- [Installation](installation/index.md): running it for real (Compose, Kubernetes, or from source) and the [configuration reference](installation/configuration.md). -- [Using the API](using-the-api/index.md) — the per-resource reference with +- [Using the API](using-the-api/index.md): the per-resource reference with headers, status codes, and versioning. -- [Operations](operations.md) — migrations, probes, observability and upgrades, +- [Operations](operations.md): migrations, probes, observability and upgrades, plus the [admin & messaging APIs](operations-admin-apis.md). -- [Concepts](concepts/index.md) — the openEHR model and how FerroEHR is built, +- [Concepts](concepts/index.md): the openEHR model and how FerroEHR is built, if the terms above were unfamiliar. diff --git a/website/book/src/identity-providers.md b/website/book/src/identity-providers.md index 44e80a68b3..8958e54e73 100644 --- a/website/book/src/identity-providers.md +++ b/website/book/src/identity-providers.md @@ -115,14 +115,11 @@ What changes against a provider FerroEHR trusts directly, such as the table. Moving people to another provider changes every key, and a deployment re-provisions their logins. - **Roles.** FerroSMART writes the person's roles, as it mapped them from the - provider, into the access token's `roles` claim (RFC 9068 §2.2.3.1) from - FerroSMART 0.2.0, the release the quickstart pins - (FerroHEALTH/FerroSMART#649). Name FerroSMART's table in `[authz.rbac] + provider, into the access token's `roles` claim (RFC 9068 §2.2.3.1). Name FerroSMART's table in `[authz.rbac] role_issuers` for them to grant `admin_role`. Emergency access is a justification of the access policy, never a role. - **The product scope.** A person reaches the ADMIN API only with the - product scope, which FerroSMART grants through a role that maps to it from - FerroSMART 0.2.0 (FerroHEALTH/FerroSMART#647). + product scope, which FerroSMART grants through a role that maps to it. - **Clients** register at FerroSMART, whose registry is the one list of clients. A system client registers for Backend Services, with a JWK Set, and FerroEHR grants each its operations in the CDR as for any system @@ -162,7 +159,7 @@ RFC 9068 §2.2; RFC 8693 §4.1), and the server acts on the kind: - **A representative** is a user whose `fhirUser` is a `RelatedPerson`, or whose `PERSON` is a representative's alone, admitted for a subject the CDR stores a live representation of - ([Representatives](operational-policy.md#representatives)). + ([Representatives](caller-facts.md#representatives)). - **A delegated user** is a token whose RFC 8693 `act` names an actor, such as a service that exchanged the user's token or an administrator who impersonates them. The token's subject is the user, so the request is bound @@ -213,7 +210,7 @@ RFC 9068 §2.2; RFC 8693 §4.1), and the server acts on the kind: `professional.hp_professional_role` and `provider.facility_type`, are read as the caller's roles and its organisation's types, each a code of the system the value names. The controller's rules name callers by them - ([Controller rules](operational-policy.md#controller-rules)), so a + ([Controller rules](access-policy.md#controller-rules)), so a national rule such as one that keeps insurers or occupational physicians out of an exchange is a rule you commit, refused with `403` as `refused-policy-denied`. A value that names no system matches no rule; @@ -358,7 +355,7 @@ its own. Configure three things: 3. **The SCIM client.** Your authorization server issues the provisioning client an access token by the client credentials grant (RFC 6749 §4.4), or in exchange for a client assertion (RFC 7523 §2.2). Grant the client - [`scim_provision`](installation/config-auth.md#authscim) in the CDR with + [`scim_provision`](installation/config-scim.md#authscim) in the CDR with the `binding_issuer` of step 2. The SCIM client sends the key as `urn:ietf:params:scim:schemas:extension:ferrohealth:2.0:User:loginIdentifier` (RFC 7644). @@ -464,11 +461,11 @@ Never bind on `email`, `phone_number`, `preferred_username`, `name`, `upn` or An issuer can let a professional with no party work at their first login: FerroEHR then creates a provisional `PERSON` from the access token and binds the login to it, as -[the configuration reference](installation/config-auth.md#just-in-time-creation) +[the configuration reference](installation/config-authz.md#just-in-time-creation) describes. It is off until an administrator writes a `create_at_login` grant for the issuer in the CDR, whose admission conditions read the claims below -([Operational policy](operational-policy.md#just-in-time-admission)). What +([Operational policy](policy-examples.md#just-in-time-admission)). What each identity provider must do for it: - **Put the name claims in the access token.** FerroEHR reads the person's diff --git a/website/book/src/installation/codespaces.md b/website/book/src/installation/codespaces.md index 8076d657c6..1c960cd952 100644 --- a/website/book/src/installation/codespaces.md +++ b/website/book/src/installation/codespaces.md @@ -38,7 +38,7 @@ checkout you opened it on: the `COMPOSE_FILE` environment variable inside the container pins every `docker compose` command to that file, so the repository's development override (which switches to from-source builds) does not apply. To develop FerroEHR itself, use a local checkout as described -under [Repository development](compose.md#repository-development). +under [Repository development](compose-overlays.md#repository-development). The Codespace runs on your own GitHub account. The smallest machine type (2 cores, 8 GB) is enough, and GitHub's free monthly Codespaces allowance @@ -56,7 +56,7 @@ what it runs on and what to expect from it: | | | |---|---| | Compute | one dedicated Hetzner Cloud CX33 (4 shared vCPU, 8 GB RAM, 80 GB NVMe SSD; Nuremberg, `eu-central`; €8.49/month net), running the published container images behind a Caddy proxy that terminates TLS | -| Database | a second, dedicated CX33 running the published `ferroehr-postgres` image (PostgreSQL 19), reachable only over a Hetzner private network — no public database port | +| Database | a second, dedicated CX33 running the published `ferroehr-postgres` image (PostgreSQL 19), reachable only over a Hetzner private network, with no public database port | | Data durability | none by design: **every night around midnight UTC the whole store is wiped and fresh demo data is seeded** | The server does not scale to zero, so there is no cold start; it is still a diff --git a/website/book/src/installation/compose-overlays.md b/website/book/src/installation/compose-overlays.md new file mode 100644 index 0000000000..45d52f935f --- /dev/null +++ b/website/book/src/installation/compose-overlays.md @@ -0,0 +1,380 @@ +# Docker Compose: overlays and profiles + +The overlays that change the quickstart's configuration (Keycloak, FerroTERM, observability), +the optional services behind Compose profiles, and the repository's development override. +The quickstart itself is on [Docker Compose](compose.md). + + + +## The OIDC variant (Keycloak overlay) + +A second standalone file adds a ready-made identity provider, so you can +exercise bearer-token authentication without registering a client anywhere. +Download `docker-compose.keycloak.yml` from the same release, beside the base +file, and stack the two: + +```shell +docker compose -f docker-compose.yml -f docker-compose.keycloak.yml up +``` + +That starts **Keycloak** with a small demo realm (`ferroehr`) defined inline and +points the server's bearer validation at it. Basic auth from the base file keeps +working, so the server then advertises `Basic, Bearer`. + +The overlay adds the realm's `[auth.issuer..party]` table, which changes the party +mapping. On a volume the base quickstart already started, the server refuses +to boot on the changed mapping until the binding side table is refilled, so +add or remove the overlay with the server stopped and refill first: + +```shell +docker compose -f docker-compose.yml -f docker-compose.keycloak.yml up -d keycloak +docker compose -f docker-compose.yml -f docker-compose.keycloak.yml stop ferroehr +docker compose -f docker-compose.yml -f docker-compose.keycloak.yml run --rm --no-deps ferroehr party-binding refill +``` + +The server accepts a token issuer only over HTTPS, or plain HTTP on a loopback +host, so Keycloak serves the issuer over TLS at +`https://keycloak.localhost:8443/auth/realms/ferroehr`. The containers resolve +`keycloak.localhost` through a network alias on the compose network, and a +browser resolves every `*.localhost` name to the loopback address, where the +published port lands, so both sides use one issuer URL with no hosts entry. On +the first `up`, a one-shot `keycloak-tls` service generates a development CA +and a certificate for that name into the `keycloak-tls` volume and discards +the CA's private key; the server (`[auth.tls] trust_roots_file`) and the viewer +(`[oidc.tls] trust_roots_file`) trust that CA beside the public ones. +`docker compose down --volumes` deletes the volume, and the next `up` +generates a new CA. Keycloak also answers plain HTTP on port 8081 for the token +call below, and the tokens it mints there name the HTTPS issuer. Keycloak's +access tokens carry `typ: JWT`, so the overlay adds the realm as the +`[auth.issuer.keycloak]` table accepting that type +(`FERROEHR__AUTH__ISSUER__KEYCLOAK__PROFILE__TOKEN_TYPES=JWT`), and the realm +puts `client_id` in every token with a hardcoded claim mapper, beside the +quickstart's `basic_users` issuer, which its Basic user binds under, and its +`quickstart` issuer, which signs its SCIM client's tokens. + +Start the viewer too and sign in at as any user below: + +```shell +docker compose -f docker-compose.yml -f docker-compose.keycloak.yml --profile viewer up +``` + +The viewer takes the authorization-code flow with PKCE through the +`ferroehr-viewer` client and calls the server with the user's token. Your +browser does not trust the development CA, so it warns once on the Keycloak +page: accept the warning, or trust the CA, which +`docker compose cp keycloak:/opt/keycloak/conf/tls/ca/ca.crt .` copies out. A +browser that does not resolve `*.localhost` needs `127.0.0.1 keycloak.localhost` +in its hosts file. + +Every route checks SMART on openEHR scopes, so the realm puts them in every +token: `user/composition-*.cruds`, `user/template-*.cruds` and +`user/aql-*.cruds` grant a user every resource family, the service client gets +their `system/` twins, and `__ferroehr.platform` is the product scope the ADMIN +and DEMOGRAPHIC APIs need. The roles below then decide. + +The overlay also **turns RBAC on**, deliberately: an identity provider whose +roles decide nothing is a login screen, not authorization. So the realm ships +four users whose roles are load-bearing: + +| User | Password | Realm roles | What it demonstrates | +|---|---|---|---| +| `ferroehr` | `ferroehr` | `ADMIN`, `USER` | the full surface, admin API included | +| `clinician` | `clinician` | `USER` | the clinical API without the admin routes | +| `auditor` | `auditor` | `USER`, `READONLY` | reads succeed, every write is refused `403` | +| `nobody` | `nobody` | none | an authenticated caller with no grant | + +The server refuses a person whose login no demographic party carries, so the +overlay binds each of the four before you sign in. The realm import gives +every user a fixed `id`, which Keycloak puts in `sub`, and the one-shot +`ferroehr-provision-keycloak` creates a SCIM User for each with that id as its +login key, as a second client of the development issuer, which the one-shot +`ferroehr-grant-keycloak` first grants `scim_provision` in the CDR with the +realm's identifier issuer, `urn:example:keycloak-quickstart-login`, as its +`binding_issuer`. The service +account acts for nobody, so it binds to no party. + +Two confidential clients are defined, and both put `ferroehr`, the audience the +server checks, in every access token: + +| Client | Secret | Grants | +|---|---|---| +| `ferroehr-viewer` | `ferroehr-viewer-quickstart-secret` | the authorization-code flow with PKCE (`S256`), redirecting only to the viewer's origin on port 3000, and the password grant so a token can be fetched by curl | +| `ferroehr-service` | `ferroehr-service-quickstart-secret` | the client-credentials grant only | + +Fetch a user's token and call the API with it: + +```shell +TOKEN=$(curl -s -d client_id=ferroehr-viewer -d client_secret=ferroehr-viewer-quickstart-secret \ + -d username=ferroehr -d password=ferroehr -d grant_type=password \ + http://localhost:8081/auth/realms/ferroehr/protocol/openid-connect/token \ + | jq -r .access_token) + +curl -H "Authorization: Bearer $TOKEN" -X POST -i \ + http://localhost:8080/ferroehr/rest/openehr/v1/ehr +``` + +A service with no user behind it takes the client-credentials grant with +`ferroehr-service`. Its service account holds `USER`, so the token reaches the +clinical API and the admin routes refuse it with `403`. Its `system/aql-*` +grant counts because the CDR grants the client `query_system_wide`, and it +creates EHRs because the CDR grants it `commit_composition`, the only way a +caller acting for no person commits: the `ferroehr-provision-keycloak` +one-shot writes its `AGENT` and a `ROLE` coding both operations through the +Demographic API, and the overlay admits them in `[authz.grants] allowed` +(`FERROEHR__AUTHZ__GRANTS__ALLOWED`) +([Operational policy](../operational-policy.md#what-a-system-client-may-do)). +The `commit_composition` grant names no template, so it commits no +COMPOSITION: + +```shell +TOKEN=$(curl -s -d client_id=ferroehr-service -d client_secret=ferroehr-service-quickstart-secret \ + -d grant_type=client_credentials \ + http://localhost:8081/auth/realms/ferroehr/protocol/openid-connect/token \ + | jq -r .access_token) +``` + +> [!WARNING] +> The realm, the client secret, the user passwords and the CA are demo values, +> served by a Keycloak in `start-dev` mode. For a real deployment, drop this +> overlay and point an `[auth.issuer.]` table (or +> `FERROEHR__AUTH__ISSUER____ISSUER` and its siblings, `` the +> table's name) at your own issuer over HTTPS. + +## The terminology overlay (FerroTERM) + +[FerroTERM](https://github.com/FerroHEALTH/FerroTERM) is the Ferro family's +FHIR terminology server: R4, R4B and R5 endpoints over a precomputed index, no +JVM, no database, one distroless image. The overlay +`docker-compose.terminology.yml` starts it beside the CDR and switches the CDR's +terminology server on, so archetype value-set bindings resolve at commit and +AQL `TERMINOLOGY()` expands through it. It also switches on the read-only +`/terminology/*` extension API (`FERROEHR__API__TERMINOLOGY`, off by +default): a term, subsumption or value-set call there for a terminology the +bundled openEHR terminology does not carry is answered by FerroTERM, while +listing and describing terminologies stays with the bundle: + +```shell +docker compose -f docker-compose.yml -f docker-compose.terminology.yml up +curl 'http://localhost:8090/r4b/metadata?mode=terminology' +``` + +It is an overlay rather than a profile for the same reason as the Keycloak and +observability ones: enabling it has to change the CDR's environment, which a +profile cannot do. FerroTERM's image carries its own health probe (the binary's +`healthcheck` subcommand, since the distroless image has no shell), and the CDR +is declared to start only once that probe reports healthy, so `docker compose up +--wait` returns with both serving. + +Out of the box FerroTERM serves the licence-free shaped seed this repository +ships (two code systems and two value sets under the reserved `example.test` +domain, the content the conformance lane binds to), mounted read-only straight +out of the `ferroehr` image. No licensed terminology is distributed with +FerroEHR or FerroTERM. To serve a release you hold a licence for, build its +index once into the named volume and tell the server to open it: + +```shell +FERROTERM_RF2=/path/to/SnomedCT_Release.zip \ + docker compose -f docker-compose.yml -f docker-compose.terminology.yml \ + --profile terminology-build run --rm ferroterm-build +FERROTERM_INDEX=/data/index \ + docker compose -f docker-compose.yml -f docker-compose.terminology.yml up +``` + +The archive is mounted read-only and unpacked to a tmpfs that dies with the +build container. FerroTERM's [loading page](https://ferroterm.eu/docs/operate/loading-snomed.html) +covers the other code systems and their build flags. + +Three things the operator owns: + +- **The code-system licence.** SNOMED CT needs an Affiliate Licence (free in + Member countries, see [snomed.org/get-snomed](https://www.snomed.org/get-snomed)); + LOINC, ICD and RxNorm have their own terms. Every surface that shows SNOMED CT + content carries the notice its licence prescribes (clause 8.3.1) and the + release version and date. +- **Who can reach the server.** The overlay publishes FerroTERM on the loopback + interface at port 8090 (`FERROEHR_TERMINOLOGY_PORT`) so you can query it while + developing. FerroTERM has no authentication and no rate limit of its own; a + deployment that serves other machines puts a reverse proxy with both in front, + or removes the `ports:` block and lets the CDR be the only caller, which is + what the [hosted sandbox](https://sandbox.ferroehr.eu) does. +- **FerroTERM's licence.** BUSL-1.1 from the same Licensor as FerroEHR: + non-commercial production use is free, any other production use needs a + commercial licence. Its README says which is which. + +The CDR keeps its shipped fail-open posture: a binding the server cannot resolve +is accepted. `FERROEHR__TERMINOLOGY__ON_ERROR=true` turns an +unreachable server into a `422` refusal instead; the +[terminology page](../beyond-core/terminology.md#when-the-terminology-server-cannot-answer) +explains both. A code the server resolves as outside its value set is refused +with `422` under either posture. + +## Optional services (Compose profiles) + +The core services are profile-less and start on every `up`. Further services +sit behind a [Compose +profile](https://docs.docker.com/compose/how-tos/profiles/) and stay down until +you ask for them: + +- **`ferroehr-viewer`** (`--profile viewer`): the + [viewer](../viewer/index.md) on port 3000, pointed at the server + inside the Compose network. Start the stack with it: + + ```shell + docker compose --profile viewer up + # → http://localhost:3000 (log in with ferroehr / ferroehr) + ``` + +- **`seaweedfs`** and **`seaweedfs-init`** (`--profile s3`): an S3 gateway for + large `DV_MULTIMEDIA` externalization (development and test only). Point the + server at it and bring the profile up: + + ```shell + export FERROEHR__RECORD__MULTIMEDIA__ENABLED=true + export FERROEHR__RECORD__MULTIMEDIA__S3__URL=http://seaweedfs:8333 # dev only; production S3 is HTTPS + export FERROEHR__RECORD__MULTIMEDIA__S3__BUCKET=openehr-multimedia + + docker compose --profile s3 up -d --wait ferroehr seaweedfs + ``` + + The compose file passes the whole `FERROEHR__RECORD__MULTIMEDIA__*` set through from + your shell, so there is no file to edit, and `seaweedfs-init` creates the + bucket by issuing an idempotent `CreateBucket` against the gateway, which + ships with none, and answers an S3 write into a missing bucket with + `403 AccessDenied`, a reply that reads as a credentials problem and is not + one. It reads the same bucket variable the server does, so the two cannot + drift. + + To turn it off again, `unset` those variables (or set + `FERROEHR__RECORD__MULTIMEDIA__ENABLED=false`) and re-up: an unset variable is + *removed* from the container's environment rather than passed as empty, so + the server falls back to its own default of `enabled = false`. + + Confirm the server took them with + `curl -s -u ferroehr:ferroehr http://localhost:8080/management/env | jq .multimedia` + (`"enabled": true` and a non-empty `endpoint` mean the wiring is right). In + production, point the multimedia settings at a real, credentialed, HTTPS S3 + endpoint instead; see [S3 multimedia](../beyond-core/s3-multimedia.md). + +- **`ferroehr-backup-clinical` and `ferroehr-backup-party`** + (`--profile backup`): one `pg_dump` job per + pseudonymisation domain, run on demand rather than started with the stack: + + ```shell + docker compose --profile backup run --rm ferroehr-backup-clinical + docker compose --profile backup run --rm ferroehr-backup-party + ``` + + Each writes a timestamped custom-format dump into its own host directory + (`FERROEHR_BACKUP_CLINICAL_DIR` and `FERROEHR_BACKUP_PARTY_DIR`, defaulting + to `./backups/clinical` and `./backups/party`). Set + `FERROEHR_BACKUP_USER="$(id -u):$(id -g)"` and the files land owned by you; + unset, the job runs as root inside the container with one capability, + `DAC_OVERRIDE`, which is what writing a directory it does not own actually + requires. + + Three dumps rather than one is the point: a single whole-database dump holds + the clinical record, the identities of its subjects and the map between them, + and whoever reads that file re-identifies every record in it. This stack runs + one login credential, so it separates the artefacts and not the authority to + produce them; [Operations → Dump each domain + separately](../database-operations.md#dump-each-domain-separately) is the production + procedure, including why a backup credential needs `BYPASSRLS`. + +Two additions change the server's configuration, which a profile cannot do, so +each is a separate overlay file: + +- **OIDC / Keycloak** is the `docker-compose.keycloak.yml` overlay above (and, + in a repository checkout, a `keycloak` profile of the development override + described below). +- **A terminology server** is the `docker-compose.terminology.yml` overlay + [above](#the-terminology-overlay-ferroterm), FerroTERM beside the CDR; the + repository's conformance stack additionally runs its own seeded server for + the acceptance lane, see [Terminology servers](../beyond-core/terminology.md). + +## Repository development + +A bare `docker compose up` in a checkout runs the same published-images +quickstart as the downloaded file. Building from the current sources is an +explicit opt-in: the `docker-compose.dev.yml` overlay, passed as a +[second file](https://docs.docker.com/compose/how-tos/multiple-compose-files/), +switches the stack to the from-source developer posture: + +```shell +docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build +``` + +That builds the server, database and viewer images from the current sources +(the `:local` tags) instead of pulling published ones, and replaces the inline +quickstart configuration with `docker/ferroehr.dev.toml`: three Basic users +(`ferroehr`, `ferroehr-admin`, `ferroehr-readonly`, all with password +`ferroehr`), **RBAC enabled** so the role separation is exercised, and trust for +the development Keycloak realm. The override also defines a `keycloak` profile +that imports the full development realm +(`docker compose --profile keycloak up`). + +Downloaders of the standalone quickstart file never see any of this; it is +purely a convenience for working on FerroEHR itself, and it only ever +applies when its `-f` is passed; nothing merges it in silently. + +> [!TIP] +> A cold from-source build compiles at two parallel rustc jobs by default, +> and a release-optimization compile can hold several gigabytes per job. If +> the build gets OOM-killed on a memory-constrained host (observed on a +> 24 GB machine that was also running another stack), rerun it serially, +> which is slower but completes: +> +> ```shell +> CARGO_BUILD_JOBS=1 docker compose -f docker-compose.yml -f docker-compose.dev.yml build +> ``` + +## Build provenance + +Images built by CI (and any `docker compose build` you drive from a checkout) +embed a build SHA reported at `/management/info` and on the +`ferroehr_build_info` metric. The build does not read `.git`; instead the SHA is +passed as the standard `REVISION` build argument, the same value that fills the +`org.opencontainers.image.revision` image label (CI uses the commit SHA; the +project's own scripts export `git rev-parse --short=12 HEAD`). The argument is +declared by the files that carry `build:` blocks (the development override and +the conformance stack) not by the pull-only quickstart file. When no value is +supplied the identity falls back to the workspace version with an `unknown` +SHA; the build never fails for lack of it. + +## Observability overlay + +A further standalone file adds a full local telemetry stack: an OTLP +collector, Prometheus, Tempo, Loki and Grafana with a provisioned +service-overview dashboard. Like the Keycloak overlay it travels inline, so +downloading it beside `docker-compose.yml` is enough: + +```shell +docker compose -f docker-compose.yml -f docker-compose.observability.yml up +# Grafana → http://localhost:3000 +``` + +The overlay reconfigures the server for that stack: it exports **traces and +metrics** over OTLP/gRPC (`FERROEHR__TELEMETRY__OTLP__ENDPOINT` with +`FERROEHR__TELEMETRY__OTLP__METRICS=true`), switches stdout to JSON lines +(`FERROEHR__TELEMETRY__FORMAT=json`), and enables the management surface on its own +internal port 9464 with `info`, `metrics` and `prometheus` reachable there. That +port is only published on the Compose network; Grafana's 3000 is the sole +published port. + +Metrics are **pushed, not scraped**, and that is a property of the bundled +image rather than a preference: `grafana/otel-lgtm` runs Prometheus with a +config file carrying no `scrape_configs` at all, and receives metrics over OTLP +from its own collector. A scrape job dropped into that image is read by nothing, +which is what an earlier version of this overlay did: every metric panel was +empty with no error anywhere. Since one meter provider feeds both readers, the +push carries every metric family the scrape endpoint would, and +`/management/prometheus` stays reachable on the Compose network for anyone who +wants to compare the two. + +Grafana's port 3000 is the same one the viewer would use, but the two +never collide by accident: the viewer only starts when you ask for the +`viewer` profile. If you want both at once, move one of them +(`FERROEHR_VIEWER_PORT=3001` or `GRAFANA_PORT=3001`). + +This is the easiest way to see the server's metrics and traces without wiring +up a collector by hand. See [Operations](../operations.md) for what the server +exports and how to consume it in production. diff --git a/website/book/src/installation/compose.md b/website/book/src/installation/compose.md index 6f9140475c..6562a25f24 100644 --- a/website/book/src/installation/compose.md +++ b/website/book/src/installation/compose.md @@ -6,16 +6,17 @@ quickstart is **one file and zero configuration**: download `docker-compose.yml`, run `docker compose up`, and the published images are pulled and started: no repository checkout, no bind mounts, no environment variables. This chapter describes the three published images, the services, the -authentication posture the quickstart ships with, the optional profiles and -overlays, and the variables that tune them. For a step-by-step first run, see +authentication posture the quickstart ships with, and the variables that tune +them. The overlays and optional profiles are on [Overlays and +profiles](compose-overlays.md). For a step-by-step first run, see [Getting started](../getting-started.md). > [!NOTE] > This chapter applies equally to the **standalone** `docker-compose.yml` > downloaded into an empty directory and to a bare `docker compose up` in a -> repository checkout — both run the published images. Building from source -> is an explicit opt-in (`-f docker-compose.yml -f docker-compose.dev.yml`) — -> see [Repository development](#repository-development) below. +> repository checkout; both run the published images. Building from source +> is an explicit opt-in (`-f docker-compose.yml -f docker-compose.dev.yml`), +> see [Repository development](compose-overlays.md#repository-development). @@ -65,8 +66,8 @@ the schema, in `[database] migrate_url`: preparation reads all four least-privilege role can do, `ferroehr_clinical` included. Unset, `migrate_url` falls back to `[database] url`, which is what the quickstart runs. See [Operations → Which credential prepares the -schema](../operations.md#which-credential-prepares-the-schema) and -[Applying migrations](../operations.md#applying-migrations). +schema](../database-operations.md#which-credential-prepares-the-schema) and +[Applying migrations](../database-operations.md#applying-migrations). The PostgreSQL image is **init-scripts only**: it creates roles and schemas, and bakes in no migration state. The schema needs no extension, so a plain @@ -81,7 +82,7 @@ self-provisions and a restart is a no-op. > running a plain `postgres` image): either recreate the volume > (`docker compose down -v`, which **destroys data**) or create the group roles > once by hand as a superuser -> ([Operations](../operations.md#turning-the-schema-split-into-a-role-split) +> ([Operations](../database-operations.md#turning-the-schema-split-into-a-role-split) > has the statements). The server runs fine either way: the > grants are a defense-in-depth layer, not a functional requirement. @@ -105,7 +106,7 @@ and the server below, and the patient identity source described in - **`ferroehr-postgres`:** the database image, with a named data volume, a `pg_isready` healthcheck, `pg_stat_statements` preloaded, and a modest tuning floor (shared buffers, WAL size, work memory, lz4-compressed WAL full-page - images — which cut per-commit WAL volume roughly in half — and a larger + images (which cut per-commit WAL volume roughly in half) and a larger `/dev/shm` than Docker's default, which otherwise starves parallel workers). - **`ferroehr`:** the server, which waits for the database to report healthy (`depends_on: condition: service_healthy`), then boots, migrates, and serves @@ -123,7 +124,7 @@ for the API credential; `api.openapi_ui` chooses who may read it). > the host firewall's own chains, so a `ufw deny 8080` does not stop a port > published on `0.0.0.0`. To reach the stack from another machine, name the > interface explicitly (`FERROEHR_BIND_HOST=0.0.0.0 docker compose up`, or a -> single address). The database publishes no host port at all — see +> single address). The database publishes no host port at all; see > [Connecting to the database](#connecting-to-the-database). > [!NOTE] @@ -155,7 +156,7 @@ Podman-specific notes: - `podman compose` delegates to an external Compose provider. With Docker's own Compose CLI installed (the common case on a machine that has ever run Docker Desktop) you get identical Compose behaviour; with the Python - `podman-compose` package, flag coverage differs — prefer the Docker Compose + `podman-compose` package, flag coverage differs; prefer the Docker Compose provider. - The default `podman machine` on macOS ships with 2048 MiB of memory. That is enough for the quickstart and both overlays, but not for building the @@ -364,292 +365,6 @@ provider over https on their own names. The hospital scenario of the deployment probe runs on these files once per upstream (`deploy-probe-hospital` in CI). -## The OIDC variant (Keycloak overlay) - -A second standalone file adds a ready-made identity provider, so you can -exercise bearer-token authentication without registering a client anywhere. -Download `docker-compose.keycloak.yml` from the same release, beside the base -file, and stack the two: - -```shell -docker compose -f docker-compose.yml -f docker-compose.keycloak.yml up -``` - -That starts **Keycloak** with a small demo realm (`ferroehr`) defined inline and -points the server's bearer validation at it. Basic auth from the base file keeps -working, so the server then advertises `Basic, Bearer`. - -The overlay adds the realm's `[auth.issuer..party]` table, which changes the party -mapping. On a volume the base quickstart already started, the server refuses -to boot on the changed mapping until the binding side table is refilled, so -add or remove the overlay with the server stopped and refill first: - -```shell -docker compose -f docker-compose.yml -f docker-compose.keycloak.yml up -d keycloak -docker compose -f docker-compose.yml -f docker-compose.keycloak.yml stop ferroehr -docker compose -f docker-compose.yml -f docker-compose.keycloak.yml run --rm --no-deps ferroehr party-binding refill -``` - -The server accepts a token issuer only over HTTPS, or plain HTTP on a loopback -host, so Keycloak serves the issuer over TLS at -`https://keycloak.localhost:8443/auth/realms/ferroehr`. The containers resolve -`keycloak.localhost` through a network alias on the compose network, and a -browser resolves every `*.localhost` name to the loopback address, where the -published port lands, so both sides use one issuer URL with no hosts entry. On -the first `up`, a one-shot `keycloak-tls` service generates a development CA -and a certificate for that name into the `keycloak-tls` volume and discards -the CA's private key; the server (`[auth.tls] trust_roots_file`) and the viewer -(`[oidc.tls] trust_roots_file`) trust that CA beside the public ones. -`docker compose down --volumes` deletes the volume, and the next `up` -generates a new CA. Keycloak also answers plain HTTP on port 8081 for the token -call below, and the tokens it mints there name the HTTPS issuer. Keycloak's -access tokens carry `typ: JWT`, so the overlay adds the realm as the -`[auth.issuer.keycloak]` table accepting that type -(`FERROEHR__AUTH__ISSUER__KEYCLOAK__PROFILE__TOKEN_TYPES=JWT`), and the realm -puts `client_id` in every token with a hardcoded claim mapper, beside the -quickstart's `basic_users` issuer, which its Basic user binds under, and its -`quickstart` issuer, which signs its SCIM client's tokens. - -Start the viewer too and sign in at as any user below: - -```shell -docker compose -f docker-compose.yml -f docker-compose.keycloak.yml --profile viewer up -``` - -The viewer takes the authorization-code flow with PKCE through the -`ferroehr-viewer` client and calls the server with the user's token. Your -browser does not trust the development CA, so it warns once on the Keycloak -page: accept the warning, or trust the CA, which -`docker compose cp keycloak:/opt/keycloak/conf/tls/ca/ca.crt .` copies out. A -browser that does not resolve `*.localhost` needs `127.0.0.1 keycloak.localhost` -in its hosts file. - -Every route checks SMART on openEHR scopes, so the realm puts them in every -token: `user/composition-*.cruds`, `user/template-*.cruds` and -`user/aql-*.cruds` grant a user every resource family, the service client gets -their `system/` twins, and `__ferroehr.platform` is the product scope the ADMIN -and DEMOGRAPHIC APIs need. The roles below then decide. - -The overlay also **turns RBAC on**, deliberately: an identity provider whose -roles decide nothing is a login screen, not authorization. So the realm ships -four users whose roles are load-bearing: - -| User | Password | Realm roles | What it demonstrates | -|---|---|---|---| -| `ferroehr` | `ferroehr` | `ADMIN`, `USER` | the full surface, admin API included | -| `clinician` | `clinician` | `USER` | the clinical API without the admin routes | -| `auditor` | `auditor` | `USER`, `READONLY` | reads succeed, every write is refused `403` | -| `nobody` | `nobody` | none | an authenticated caller with no grant | - -The server refuses a person whose login no demographic party carries, so the -overlay binds each of the four before you sign in. The realm import gives -every user a fixed `id`, which Keycloak puts in `sub`, and the one-shot -`ferroehr-provision-keycloak` creates a SCIM User for each with that id as its -login key, as a second client of the development issuer, which the one-shot -`ferroehr-grant-keycloak` first grants `scim_provision` in the CDR with the -realm's identifier issuer, `urn:example:keycloak-quickstart-login`, as its -`binding_issuer`. The service -account acts for nobody, so it binds to no party. - -Two confidential clients are defined, and both put `ferroehr`, the audience the -server checks, in every access token: - -| Client | Secret | Grants | -|---|---|---| -| `ferroehr-viewer` | `ferroehr-viewer-quickstart-secret` | the authorization-code flow with PKCE (`S256`), redirecting only to the viewer's origin on port 3000, and the password grant so a token can be fetched by curl | -| `ferroehr-service` | `ferroehr-service-quickstart-secret` | the client-credentials grant only | - -Fetch a user's token and call the API with it: - -```shell -TOKEN=$(curl -s -d client_id=ferroehr-viewer -d client_secret=ferroehr-viewer-quickstart-secret \ - -d username=ferroehr -d password=ferroehr -d grant_type=password \ - http://localhost:8081/auth/realms/ferroehr/protocol/openid-connect/token \ - | jq -r .access_token) - -curl -H "Authorization: Bearer $TOKEN" -X POST -i \ - http://localhost:8080/ferroehr/rest/openehr/v1/ehr -``` - -A service with no user behind it takes the client-credentials grant with -`ferroehr-service`. Its service account holds `USER`, so the token reaches the -clinical API and the admin routes refuse it with `403`. Its `system/aql-*` -grant counts because the CDR grants the client `query_system_wide`, and it -creates EHRs because the CDR grants it `commit_composition`, the only way a -caller acting for no person commits: the `ferroehr-provision-keycloak` -one-shot writes its `AGENT` and a `ROLE` coding both operations through the -Demographic API, and the overlay admits them in `[authz.grants] allowed` -(`FERROEHR__AUTHZ__GRANTS__ALLOWED`) -([Operational policy](../operational-policy.md#what-a-system-client-may-do)). -The `commit_composition` grant names no template, so it commits no -COMPOSITION: - -```shell -TOKEN=$(curl -s -d client_id=ferroehr-service -d client_secret=ferroehr-service-quickstart-secret \ - -d grant_type=client_credentials \ - http://localhost:8081/auth/realms/ferroehr/protocol/openid-connect/token \ - | jq -r .access_token) -``` - -> [!WARNING] -> The realm, the client secret, the user passwords and the CA are demo values, -> served by a Keycloak in `start-dev` mode. For a real deployment, drop this -> overlay and point an `[auth.issuer.]` table (or -> `FERROEHR__AUTH__ISSUER____ISSUER` and its siblings, `` the -> table's name) at your own issuer over HTTPS. - -## The terminology overlay (FerroTERM) - -[FerroTERM](https://github.com/FerroHEALTH/FerroTERM) is the Ferro family's -FHIR terminology server: R4, R4B and R5 endpoints over a precomputed index, no -JVM, no database, one distroless image. The overlay -`docker-compose.terminology.yml` starts it beside the CDR and switches the CDR's -terminology server on, so archetype value-set bindings resolve at commit and -AQL `TERMINOLOGY()` expands through it. It also switches on the read-only -`/terminology/*` extension API (`FERROEHR__API__TERMINOLOGY`, off by -default): a term, subsumption or value-set call there for a terminology the -bundled openEHR terminology does not carry is answered by FerroTERM, while -listing and describing terminologies stays with the bundle: - -```shell -docker compose -f docker-compose.yml -f docker-compose.terminology.yml up -curl 'http://localhost:8090/r4b/metadata?mode=terminology' -``` - -It is an overlay rather than a profile for the same reason as the Keycloak and -observability ones: enabling it has to change the CDR's environment, which a -profile cannot do. FerroTERM's image carries its own health probe (the binary's -`healthcheck` subcommand, since the distroless image has no shell), and the CDR -is declared to start only once that probe reports healthy, so `docker compose up ---wait` returns with both serving. - -Out of the box FerroTERM serves the licence-free shaped seed this repository -ships (two code systems and two value sets under the reserved `example.test` -domain, the content the conformance lane binds to), mounted read-only straight -out of the `ferroehr` image. No licensed terminology is distributed with -FerroEHR or FerroTERM. To serve a release you hold a licence for, build its -index once into the named volume and tell the server to open it: - -```shell -FERROTERM_RF2=/path/to/SnomedCT_Release.zip \ - docker compose -f docker-compose.yml -f docker-compose.terminology.yml \ - --profile terminology-build run --rm ferroterm-build -FERROTERM_INDEX=/data/index \ - docker compose -f docker-compose.yml -f docker-compose.terminology.yml up -``` - -The archive is mounted read-only and unpacked to a tmpfs that dies with the -build container. FerroTERM's [loading page](https://ferroterm.eu/docs/operate/loading-snomed.html) -covers the other code systems and their build flags. - -Three things the operator owns: - -- **The code-system licence.** SNOMED CT needs an Affiliate Licence (free in - Member countries, see [snomed.org/get-snomed](https://www.snomed.org/get-snomed)); - LOINC, ICD and RxNorm have their own terms. Every surface that shows SNOMED CT - content carries the notice its licence prescribes (clause 8.3.1) and the - release version and date. -- **Who can reach the server.** The overlay publishes FerroTERM on the loopback - interface at port 8090 (`FERROEHR_TERMINOLOGY_PORT`) so you can query it while - developing. FerroTERM has no authentication and no rate limit of its own; a - deployment that serves other machines puts a reverse proxy with both in front, - or removes the `ports:` block and lets the CDR be the only caller, which is - what the [hosted sandbox](https://sandbox.ferroehr.eu) does. -- **FerroTERM's licence.** BUSL-1.1 from the same Licensor as FerroEHR: - non-commercial production use is free, any other production use needs a - commercial licence. Its README says which is which. - -The CDR keeps its shipped fail-open posture: a binding the server cannot resolve -is accepted. `FERROEHR__TERMINOLOGY__ON_ERROR=true` turns an -unreachable server into a `422` refusal instead; the -[terminology page](../beyond-core/terminology.md#when-the-terminology-server-cannot-answer) -explains both. A code the server resolves as outside its value set is refused -with `422` under either posture. - -## Optional services (Compose profiles) - -The core services are profile-less and start on every `up`. Further services -sit behind a [Compose -profile](https://docs.docker.com/compose/how-tos/profiles/) and stay down until -you ask for them: - -- **`ferroehr-viewer`** (`--profile viewer`): the - [viewer](../viewer/index.md) on port 3000, pointed at the server - inside the Compose network. Start the stack with it: - - ```shell - docker compose --profile viewer up - # → http://localhost:3000 (log in with ferroehr / ferroehr) - ``` - -- **`seaweedfs`** and **`seaweedfs-init`** (`--profile s3`): an S3 gateway for - large `DV_MULTIMEDIA` externalization (development and test only). Point the - server at it and bring the profile up: - - ```shell - export FERROEHR__RECORD__MULTIMEDIA__ENABLED=true - export FERROEHR__RECORD__MULTIMEDIA__S3__URL=http://seaweedfs:8333 # dev only; production S3 is HTTPS - export FERROEHR__RECORD__MULTIMEDIA__S3__BUCKET=openehr-multimedia - - docker compose --profile s3 up -d --wait ferroehr seaweedfs - ``` - - The compose file passes the whole `FERROEHR__RECORD__MULTIMEDIA__*` set through from - your shell, so there is no file to edit, and `seaweedfs-init` creates the - bucket by issuing an idempotent `CreateBucket` against the gateway, which - ships with none, and answers an S3 write into a missing bucket with - `403 AccessDenied`, a reply that reads as a credentials problem and is not - one. It reads the same bucket variable the server does, so the two cannot - drift. - - To turn it off again, `unset` those variables (or set - `FERROEHR__RECORD__MULTIMEDIA__ENABLED=false`) and re-up: an unset variable is - *removed* from the container's environment rather than passed as empty, so - the server falls back to its own default of `enabled = false`. - - Confirm the server took them with - `curl -s -u ferroehr:ferroehr http://localhost:8080/management/env | jq .multimedia` - (`"enabled": true` and a non-empty `endpoint` mean the wiring is right). In - production, point the multimedia settings at a real, credentialed, HTTPS S3 - endpoint instead; see [S3 multimedia](../beyond-core/s3-multimedia.md). - -- **`ferroehr-backup-clinical` and `ferroehr-backup-party`** - (`--profile backup`): one `pg_dump` job per - pseudonymisation domain, run on demand rather than started with the stack: - - ```shell - docker compose --profile backup run --rm ferroehr-backup-clinical - docker compose --profile backup run --rm ferroehr-backup-party - ``` - - Each writes a timestamped custom-format dump into its own host directory - (`FERROEHR_BACKUP_CLINICAL_DIR` and `FERROEHR_BACKUP_PARTY_DIR`, defaulting - to `./backups/clinical` and `./backups/party`). Set - `FERROEHR_BACKUP_USER="$(id -u):$(id -g)"` and the files land owned by you; - unset, the job runs as root inside the container with one capability, - `DAC_OVERRIDE`, which is what writing a directory it does not own actually - requires. - - Three dumps rather than one is the point: a single whole-database dump holds - the clinical record, the identities of its subjects and the map between them, - and whoever reads that file re-identifies every record in it. This stack runs - one login credential, so it separates the artefacts and not the authority to - produce them; [Operations → Dump each domain - separately](../operations.md#dump-each-domain-separately) is the production - procedure, including why a backup credential needs `BYPASSRLS`. - -Two things that used to be profiles of this file are not any more. Both have to -*change* the server's configuration to be useful, which a profile cannot do, so -each is a separate file instead: - -- **OIDC / Keycloak** is the `docker-compose.keycloak.yml` overlay above (and, - in a repository checkout, a `keycloak` profile of the development override - described below). -- **A terminology server** is the `docker-compose.terminology.yml` overlay - [above](#the-terminology-overlay-ferroterm), FerroTERM beside the CDR; the - repository's conformance stack additionally runs its own seeded server for - the acceptance lane, see [Terminology servers](../beyond-core/terminology.md). - ## Port already in use? Every published port is a variable, so a conflict never requires editing any @@ -661,12 +376,12 @@ FERROEHR_PORT=8081 docker compose up ``` The same works for the other ports (`FERROEHR_VIEWER_PORT`, -`FERROEHR_PIX_PORT`, `FERROEHR_ISSUER_PORT`, `FERROEHR_S3_PORT`; PostgreSQL publishes no host port — see +`FERROEHR_PIX_PORT`, `FERROEHR_ISSUER_PORT`, `FERROEHR_S3_PORT`; PostgreSQL publishes no host port; see [Connecting to the database](#connecting-to-the-database)). The defaults stay fixed on purpose: every URL in this book assumes `localhost:8080`, and Docker's automatic ephemeral-port allocation exists only when a mapping -[omits the host port entirely](https://docs.docker.com/engine/network/port-publishing/) -— a server that silently moved ports would break every printed URL, so here +[omits the host port entirely](https://docs.docker.com/engine/network/port-publishing/). +A server that silently moved ports would break every printed URL, so here you always choose the port and always know it. > [!NOTE] @@ -676,9 +391,9 @@ you always choose the port and always know it. > `… An attempt was made to access a socket in a way forbidden by its access > permissions` when the port sits in a Windows reserved range. The remedy is > the same variable; to see the reserved ranges, run -> `netsh interface ipv4 show excludedportrange protocol=tcp`. (The classic -> Windows collision — a natively installed PostgreSQL service holding 5432 — -> no longer affects the quickstart, which publishes no database port.) +> `netsh interface ipv4 show excludedportrange protocol=tcp`. The quickstart +> publishes no database port, so a natively installed PostgreSQL on 5432 does +> not collide with it. ## Connecting to the database @@ -700,7 +415,7 @@ docker compose -f docker-compose.yml -f docker-compose.db-publish.yml up ``` It publishes `127.0.0.1:5432` (retune with `FERROEHR_DB_PORT`, widen with -`FERROEHR_BIND_HOST` — the warning above applies). +`FERROEHR_BIND_HOST`; the warning above applies). ## Variables the compose files read @@ -753,97 +468,9 @@ over the file. Every variable uses the same `FERROEHR__…` grammar as the rest that reference; a single-underscore spelling is rejected at startup, not ignored. -## Repository development - -A bare `docker compose up` in a checkout runs the same published-images -quickstart as the downloaded file. Building from the current sources is an -explicit opt-in: the `docker-compose.dev.yml` overlay, passed as a -[second file](https://docs.docker.com/compose/how-tos/multiple-compose-files/), -switches the stack to the from-source developer posture: - -```shell -docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build -``` - -That builds the server, database and viewer images from the current sources -(the `:local` tags) instead of pulling published ones, and replaces the inline -quickstart configuration with `docker/ferroehr.dev.toml`: three Basic users -(`ferroehr`, `ferroehr-admin`, `ferroehr-readonly`, all with password -`ferroehr`), **RBAC enabled** so the role separation is exercised, and trust for -the development Keycloak realm. The override also defines a `keycloak` profile -that imports the full development realm -(`docker compose --profile keycloak up`). - -Downloaders of the standalone quickstart file never see any of this; it is -purely a convenience for working on FerroEHR itself, and it only ever -applies when its `-f` is passed — nothing merges it in silently. - -> [!TIP] -> A cold from-source build compiles at two parallel rustc jobs by default, -> and a release-optimization compile can hold several gigabytes per job. If -> the build gets OOM-killed on a memory-constrained host (observed on a -> 24 GB machine that was also running another stack), rerun it serially — -> slower, but it completes: -> -> ```shell -> CARGO_BUILD_JOBS=1 docker compose -f docker-compose.yml -f docker-compose.dev.yml build -> ``` - -## Build provenance - -Images built by CI (and any `docker compose build` you drive from a checkout) -embed a build SHA reported at `/management/info` and on the -`ferroehr_build_info` metric. The build does not read `.git`; instead the SHA is -passed as the standard `REVISION` build argument, the same value that fills the -`org.opencontainers.image.revision` image label (CI uses the commit SHA; the -project's own scripts export `git rev-parse --short=12 HEAD`). The argument is -declared by the files that carry `build:` blocks (the development override and -the conformance stack) not by the pull-only quickstart file. When no value is -supplied the identity falls back to the workspace version with an `unknown` -SHA; the build never fails for lack of it. - -## Observability overlay - -A further standalone file adds a full local telemetry stack: an OTLP -collector, Prometheus, Tempo, Loki and Grafana with a provisioned -service-overview dashboard. Like the Keycloak overlay it travels inline, so -downloading it beside `docker-compose.yml` is enough: - -```shell -docker compose -f docker-compose.yml -f docker-compose.observability.yml up -# Grafana → http://localhost:3000 -``` - -The overlay reconfigures the server for that stack: it exports **traces and -metrics** over OTLP/gRPC (`FERROEHR__TELEMETRY__OTLP__ENDPOINT` with -`FERROEHR__TELEMETRY__OTLP__METRICS=true`), switches stdout to JSON lines -(`FERROEHR__TELEMETRY__FORMAT=json`), and enables the management surface on its own -internal port 9464 with `info`, `metrics` and `prometheus` reachable there. That -port is only published on the Compose network; Grafana's 3000 is the sole -published port. - -Metrics are **pushed, not scraped**, and that is a property of the bundled -image rather than a preference: `grafana/otel-lgtm` runs Prometheus with a -config file carrying no `scrape_configs` at all, and receives metrics over OTLP -from its own collector. A scrape job dropped into that image is read by nothing, -which is what an earlier version of this overlay did: every metric panel was -empty with no error anywhere. Since one meter provider feeds both readers, the -push carries every metric family the scrape endpoint would, and -`/management/prometheus` stays reachable on the Compose network for anyone who -wants to compare the two. - -Grafana's port 3000 is the same one the viewer would use, but the two -never collide by accident: the viewer only starts when you ask for the -`viewer` profile. If you want both at once, move one of them -(`FERROEHR_VIEWER_PORT=3001` or `GRAFANA_PORT=3001`). - -This is the easiest way to see the server's metrics and traces without wiring -up a collector by hand. See [Operations](../operations.md) for what the server -exports and how to consume it in production. - ## Next -- [Configuration reference](configuration.md) — every setting you can pass. -- [Kubernetes & Helm](kubernetes.md) — the production deployment. +- [Configuration reference](configuration.md): every setting you can pass. +- [Kubernetes & Helm](kubernetes.md): the production deployment. - [Returning to the original state](../operations-reset.md): resetting the stack to the configuration and empty database it shipped with. diff --git a/website/book/src/installation/config-audit.md b/website/book/src/installation/config-audit.md index 0ed47a67de..f37991a269 100644 --- a/website/book/src/installation/config-audit.md +++ b/website/book/src/installation/config-audit.md @@ -38,9 +38,9 @@ purpose_system = "http://terminology.hl7.org/CodeSystem/v3-ActReason" | `suppress_login_events` | bool | `true` | Skip successful-login records. Rejected accesses (`401`/`403`) are always recorded. | | `resolve_subject` | bool | `true` | Enrich the patient participant with an indexed lookup of the EHR's subject, remembered per EHR for an hour, so a request seldom asks. The IHE BALP patient patterns and the patient-centric audit search need the subject. | | `server_host` | string | unset ⇒ the `value_if_missing` fill | This node's advertised network address, reported as the destination `NetworkAccessPointID`. | -| `purpose_header` | string | `x-purpose-of-use` | The request header a caller declares its purpose of use in, recorded on every access record. NEN 7513 asks on whose authority a record was read and EHDS Art. 9 asks why; neither is derivable from the request, so the caller declares it. IHE carries the equivalent in a SAML attribute rather than a header, so the header is FerroEHR's own. An issuer with an `[auth.issuer..attributes]` table states the purposes in its token, and a header naming another purpose is refused ([where the purpose comes from](../audit.md#where-the-purpose-of-use-comes-from)). | +| `purpose_header` | string | `x-purpose-of-use` | The request header a caller declares its purpose of use in, recorded on every access record. NEN 7513 asks on whose authority a record was read and EHDS Art. 9 asks why; neither is derivable from the request, so the caller declares it. IHE carries the equivalent in a SAML attribute rather than a header, so the header is FerroEHR's own. An issuer with an `[auth.issuer..attributes]` table states the purposes in its token, and a header naming another purpose is refused ([where the purpose comes from](../ehds-logging.md#where-the-purpose-of-use-comes-from)). | | `permit_header` | string | `x-data-permit` | The request header a secondary-use caller declares the data permit it acts under in (EHDS Art. 68), recorded on every access record as `permit`. The value is the permit's identifier, 1 to 128 characters of letters, digits and `.` `_` `:` `/` `#` `-`; any other value is recorded as absent. No specification names a header for it, so the header is FerroEHR's own. See [Secondary use](../compliance/secondary-use.md#the-access-record). | -| `reason_header` | string | `x-access-reason` | The request header a caller states the reason for a [justified access](../security.md#justified-access-outside-the-care-relationships) in: the clinician's own words, percent-encoded UTF-8, 1 to 1000 characters after decoding, with no control character; any other value is a `400`. The access record keeps the reason, and the FHIR `AuditEvent` carries it as the text of the purpose of use ([justified and emergency access](../audit.md#justified-and-emergency-access)). No specification names a header for it, so the header and its bound are FerroEHR's own. | +| `reason_header` | string | `x-access-reason` | The request header a caller states the reason for a [justified access](../access-control.md#justified-access-outside-the-care-relationships) in: the clinician's own words, percent-encoded UTF-8, 1 to 1000 characters after decoding, with no control character; any other value is a `400`. The access record keeps the reason, and the FHIR `AuditEvent` carries it as the text of the purpose of use ([justified and emergency access](../ehds-logging.md#justified-and-emergency-access)). No specification names a header for it, so the header and its bound are FerroEHR's own. | | `purpose_codes` | list of string | `[]` | The purpose codes this deployment accepts. Empty records whatever the caller declares. A non-empty list records a declared code only when it is on the list, so an unagreed string does not sit in the trail reading like an established purpose. | | `purpose_system` | string | `http://terminology.hl7.org/CodeSystem/v3-ActReason` | The canonical URL of the FHIR `CodeSystem` the `purpose_codes` belong to, HL7's `ActReason` by default. `GET {extensions}/access/purposes` answers the header, this system and each accepted code with the display text the [terminology server](config-integrations.md#terminology)'s `CodeSystem/$lookup` gives it, so a client such as the viewer offers the codes by name. Any authenticated caller reads that list, one with no role included: it names no personal data. No specification names the system of a purpose header, so the key is FerroEHR's own. | | `legal_basis` | string | unset | The legal basis this deployment processes under, recorded on every access record. A deployment-level fact: the controller establishes the GDPR Art. 6/9 condition once. Unset records nothing rather than a guess. | @@ -66,27 +66,26 @@ and `Retry-After`. There is no fail mode and no queue: `fail_mode` and | Key | Type | Default | Description | |---|---|---|---| -| `verify_interval` | duration | `"1h"` | The time between two scheduled verifications of the sealed windows of the system records and the access log; `"0s"` turns the schedule off. Each run verifies the windows sealed since the newest window an earlier run found intact. A finding is logged at `ERROR`, counted in `atna_audit_chain_findings` and reported by the `audit_chain` indicator on `GET /health/readiness`. See [Tamper evidence](../audit.md#tamper-evidence). | +| `verify_interval` | duration | `"1h"` | The time between two scheduled verifications of the sealed windows of the system records and the access log; `"0s"` turns the schedule off. Each run verifies the windows sealed since the newest window an earlier run found intact. A finding is logged at `ERROR`, counted in `atna_audit_chain_findings` and reported by the `audit_chain` indicator on `GET /health/readiness`. See [Tamper evidence](../audit-integrity.md#tamper-evidence). | | `full_verify_interval` | duration | `"7d"` | The time between two scheduled full passes over every sealed window of both logs; `"0s"` leaves the full pass to `ferroehr audit-chain verify` on demand. A run that found damage is always followed by a full pass. | | `max_verify_lag` | duration | `"4h"` | How long a record may wait past its chain's verification cursor before the `audit_chain` indicator reads `DEGRADED`; `"0s"` reports the lag only as the `audit_chain_verification_lag` and `audit_chain_unverified_age_seconds` metrics. Set it above `verify_interval`. | The local store is always on while auditing is: every record is written to it before its access is reported, and syslog and the FHIR feed deliver from -it, so a down repository loses nothing. `enabled` is an unknown key, refused -at load. +it, so a down repository loses nothing. How long the store and the access log keep a record is the controller's access policy (`ACCESS_POLICY.log_retention`), not a configuration key: the period, whether EHDS binds the controller, and the floors and ceilings its law sets, each with its provision. `retention` and `sgb_v_309_controller` are unknown keys and refused at load. See -[Audit trail](../audit.md#retention-and-who-chooses-it). +[Audit trail](../ehds-logging.md#retention-and-who-chooses-it). ### The audit category register The map every access record is classified through by EHDS category (Annex II -3.2(c); see [the EHDS logging elements](../audit.md#the-ehds-logging-elements-mapped)) -is an [admin register](../operational-policy.md#the-admin-registers), not a +3.2(c); see [the EHDS logging elements](../ehds-logging.md#the-ehds-logging-elements-mapped)) +is an [admin register](../access-policy.md#the-admin-registers), not a configuration key: you read and replace it through `{ext}/admin/registers/audit-categories`, every version is kept with its committer, and a change applies on the next request without a restart. The @@ -170,7 +169,7 @@ free text, so the origins your deployment recognises are policy in the CDR, not configuration: each is the `origin` element of a `data_origin` grant in force, which a [retention period](../compliance/retention.md#keying-a-period-on-an-origin) -and an [access directive's data scope](../security.md#access-directives) may then +and an [access directive's data scope](../access-control.md#access-directives) may then name ([Operational policy](../operational-policy.md#what-the-grants-decide)). A body that carries no `FEEDER_AUDIT`, committed by the holder of such a grant, is stamped with its origin; a direct commit by any other caller keeps @@ -257,4 +256,4 @@ can remove the newest windows together with the checkpoints that seal them, and only a checkpoint published where that person cannot write shows it. Mount the directory from write-once storage, or from storage another system collects from, and give every instance the same one. See the -[audit page](../audit.md#seals-checkpoints-and-the-transfer-of-a-log). +[audit page](../audit-integrity.md#seals-checkpoints-and-the-transfer-of-a-log). diff --git a/website/book/src/installation/config-auth.md b/website/book/src/installation/config-auth.md index bf9139d554..acc0eb129c 100644 --- a/website/book/src/installation/config-auth.md +++ b/website/book/src/installation/config-auth.md @@ -1,8 +1,10 @@ # Authentication & access Who may call the server, what they may do once identified, and the surfaces -that are gated rather than always-on: `[auth]`, `[authz]`, `[api] admin`, -`[auth.smart]`, `[management]`, and `[record.signing]`. Precedence, the +that are gated rather than always-on: `[auth]`, `[api] admin`, the +access-delay register, `[auth.smart]`, `[management]`, `[deployment]`, +`[record.signing]` and `[record.versioning]`. `[authz]` is on [Authorization +keys](config-authz.md) and `[auth.scim]` on [SCIM provisioning](config-scim.md). Precedence, the environment-name grammar, and file discovery are on the [Configuration reference](configuration.md) index. @@ -14,7 +16,7 @@ Authentication: bearer tokens of one or more trusted issuers, Basic credentials, or both. `[auth]` is the section every FerroHEALTH product shares, checked by the `ferrohealth-smart` crate (0.32). FerroEHR is a resource server: it checks tokens and never issues them. Every person a request comes from is -bound to a demographic `PERSON` (see [`[authz.party_binding]`](#authzparty_binding)). +bound to a demographic `PERSON` (see [`[authz.party_binding]`](config-authz.md#authzparty_binding)). Each issuer is a table named by you, `[auth.issuer.]`, and every other key that refers to an issuer names that table: `[auth] described_issuer`, @@ -120,9 +122,9 @@ boot cannot see. | `jwks_file` | path | `""` | A JWK Set of public keys handed over out of band, read at start instead of the issuer's metadata. A symmetric key (`kty: "oct"`) or a private-key member (`d`, `p`, `q`, `dp`, `dq`, `qi`, `oth`, `k`) is a boot error. An issuer read from a file has no metadata, so it serves the SMART discovery document only with [`[auth.smart] issuer_metadata_file`](#authsmart) set. | | `timeout` | duration | `"10s"` | One call to the authorization server. | | `mode` | `jwt` or `introspection` | `jwt` | How the issuer's tokens are checked: as JWTs against its key set, or posted to its RFC 7662 endpoint (see [Opaque tokens](#opaque-tokens-by-introspection)). | -| `role_claims` | list of string | `["roles","groups","entitlements"]` | Token claim paths the caller's roles are read from; dotted paths walk nested claims, and a role is matched without regard to case. **`scope` is not a role source**. A `federation` issuer reads no role. Whether a role grants `admin_role` is [`[authz.rbac] role_issuers`](#authzrbac). | +| `role_claims` | list of string | `["roles","groups","entitlements"]` | Token claim paths the caller's roles are read from; dotted paths walk nested claims, and a role is matched without regard to case. **`scope` is not a role source**. A `federation` issuer reads no role. Whether a role grants `admin_role` is [`[authz.rbac] role_issuers`](config-authz.md#authzrbac). | | `sender_constraint` | `none` or `required` | `none` | `required` admits only a token bound to a DPoP key (RFC 9449) or to the client certificate of a mutual-TLS connection (RFC 8705 §3). A token carrying `cnf` is held to it under either value. | -| `assurance` | table | unset | The assurance level the issuer's tokens carry, in the shape of [`[authz.assurance]`](#authzassurance-the-assurance-level-patient-data-requires). | +| `assurance` | table | unset | The assurance level the issuer's tokens carry, in the shape of [`[authz.assurance]`](config-authz.md#authzassurance-the-assurance-level-patient-data-requires). | ### `[auth.issuer..profile]`: the token shape @@ -161,9 +163,9 @@ that `baseUrl`, so a deployment writes its public URL once. Without | Table | Description | |---|---| -| `[auth.issuer..party]` | One per issuer whose users sign in to FerroEHR: where their logins are looked up. `identifier_issuer` (the issuer's own identifier when empty) and `identifier_type` (`pairwise`, FerroSMART's pairwise `sub`, when empty; `guid` and `uuid` compare in lower case) name the identifiers each token's `sub` is matched against (OpenID Connect Core 1.0 §5.7); `group_claim` with `group_identifier_issuer` reads the groups a token asserts. A user token of an issuer without one is refused `403` `refused-unbound`, so an issuer without a table admits its clients' own tokens alone. Boot refuses a table under a `federation` issuer, two tables sharing an `identifier_issuer`, and a table whose `identifier_type` is the `type` of no [`[[authz.party_binding.person.template]]`](#authzparty_binding) `key`: SCIM and just-in-time creation write the key under that type and the lookup compares the type exactly, so no login of the issuer would bind. | +| `[auth.issuer..party]` | One per issuer whose users sign in to FerroEHR: where their logins are looked up. `identifier_issuer` (the issuer's own identifier when empty) and `identifier_type` (`pairwise`, FerroSMART's pairwise `sub`, when empty; `guid` and `uuid` compare in lower case) name the identifiers each token's `sub` is matched against (OpenID Connect Core 1.0 §5.7); `group_claim` with `group_identifier_issuer` reads the groups a token asserts. A user token of an issuer without one is refused `403` `refused-unbound`, so an issuer without a table admits its clients' own tokens alone. Boot refuses a table under a `federation` issuer, two tables sharing an `identifier_issuer`, and a table whose `identifier_type` is the `type` of no [`[[authz.party_binding.person.template]]`](config-authz.md#authzparty_binding) `key`: SCIM and just-in-time creation write the key under that type and the lookup compares the type exactly, so no login of the issuer would bind. | | `[auth.issuer..federation]` | Required on a `federation` issuer and refused on any other: how its tokens' claims map to the fields of another party's professional or organisation (`mapping = "iua"`, `"ehdsi"` or per field), the countries, issuing authorities and provider prefixes that bound them, and `contact_point` for a MyHealth@EU contact point. `fields` maps a field to its claim (`{ claim = "..." }`), its `authorization_details` member, or a coded constant with its code system (`{ constant = "…", system = "…" }`), among them `consent.reference`, the consent decision reference of a consent-conditioned read, `correlation_id`, the requester's id a `chained` organisation request carries, and `trc.care_role`, the care role a treatment relationship attests (see [the attested care path](../operational-policy.md)). | -| `[auth.issuer..attributes]` | At most one per issuer with a party table: where its tokens state the professional's attributes (`mapping = "iua"`, the IHE IUA claims under `extensions.ihe_iua`, or per field in `fields`), and `authorization_details_purposes`, whether the `purpose_of_use` of each RFC 9396 `authorization_details` entry is a purpose of use too. Its purposes of use and roles go into each [access record](../audit.md#where-the-purpose-of-use-comes-from), and a `[audit] purpose_header` naming a purpose the token does not state refuses the request with `403`. | +| `[auth.issuer..attributes]` | At most one per issuer with a party table: where its tokens state the professional's attributes (`mapping = "iua"`, the IHE IUA claims under `extensions.ihe_iua`, or per field in `fields`), and `authorization_details_purposes`, whether the `purpose_of_use` of each RFC 9396 `authorization_details` entry is a purpose of use too. Its purposes of use and roles go into each [access record](../ehds-logging.md#where-the-purpose-of-use-comes-from), and a `[audit] purpose_header` naming a purpose the token does not state refuses the request with `403`. | | `[auth.dpop]` | The DPoP proof check of a sender-constrained issuer: `max_age` (`"60s"`), `clock_skew` (`"10s"`) and `algorithms`. Each accepted proof is recorded in the database every replica shares until its window ends, so a proof is accepted once across all of them (RFC 9449 §11.1), and a database that cannot record it refuses the request with `503`. A proof's `htu` must name [`server.public_base_url`](config-server.md#public_base_url-the-one-public-url), `server.base_path` and the request path, so the table needs that key. | > [!WARNING] @@ -230,7 +232,7 @@ client_secret_file = "/run/secrets/introspection-client" `[[auth.basic.users]]` is an array of tables. A Basic user is always a person: it maps to the `PERSON` carrying its binding key through -[`[[authz.party_binding.basic_user]]`](#authzparty_binding), and a Basic user +[`[[authz.party_binding.basic_user]]`](config-authz.md#authzparty_binding), and a Basic user with no mapping refuses the start, naming the user. A machine authenticates with the client credentials grant (RFC 6749 §4.4), and a `system/` scope on a Basic user refuses the start. @@ -241,7 +243,7 @@ Basic user refuses the start. | `password_hash` | secret | required | Argon2**id** PHC hash (`$argon2id$v=19$…`), never a plaintext password. Boot-validated against the OWASP floor; see below. | | `password_hash_file` | path | unset | Read the hash from a file instead, for a mounted secret. A hash is an offline cracking target, so prefer this wherever the configuration file itself is not treated as sensitive. Exactly one of the pair is required. | | `scopes` | list of string | `[]` | The SMART on openEHR scopes the user holds, checked on every route exactly like a token's `scope` claim. A user bound to a `PERSON` also holds the scopes of its `hold_scopes` grants ([What the grants decide](../operational-policy.md#what-the-grants-decide)). A user with none is refused everywhere a requirement applies. | -| `roles` | list of string | `[]` | The user's RBAC roles, upper-cased on authentication. A user bound to a `PERSON` also holds the roles of its `hold_roles` grants, never a privileged one. A user with none holds no role and is refused wherever [`[authz.rbac]`](#authzrbac) asks for one. | +| `roles` | list of string | `[]` | The user's RBAC roles, upper-cased on authentication. A user bound to a `PERSON` also holds the roles of its `hold_roles` grants, never a privileged one. A user with none holds no role and is refused wherever [`[authz.rbac]`](config-authz.md#authzrbac) asks for one. | `[auth.basic]` itself takes one key beside the users: @@ -263,472 +265,6 @@ Basic user refuses the start. An unknown user-id is checked against a decoy hash of the same cost, so the time a refusal takes does not say whether the user exists. -## `[authz]` - -Role-based (RBAC) authorization, the party binding, the grant ceiling and the -patient-data assurance gate. Which caller may read which data is the access -evaluator's, over each EHR's `access_directives` and the controller's access -policy, and takes no key here. How the parts fit together and the order a -request is decided in are on [How FerroEHR decides -access](../explanation/access-model.md). - -### `[authz.assurance]`: the assurance level patient data requires - -Off by default. What it refuses and the `401` challenge it sends are described -in [Security](../security.md#assurance-level-and-the-natural-person-on-patient-data). - -| Key | Type | Default | Description | -|---|---|---|---| -| `claim` | string | `acr` | The token claim carrying the authentication context class; a dotted path reaches into a JSON object. | -| `levels` | table of string → `low` \| `substantial` \| `high` | empty | Maps each value your identity provider puts in `claim` to an eIDAS level of assurance. A value the table does not name carries no level. File-only: the keys are usually URIs. | -| `minimum` | `low` \| `substantial` \| `high` | unset | The level a patient-data request must carry. Unset refuses nothing. | - -```toml -[authz.assurance] -minimum = "substantial" - -[authz.assurance.levels] -"http://eidas.europa.eu/LoA/low" = "low" -"http://eidas.europa.eu/LoA/substantial" = "substantial" -"http://eidas.europa.eu/LoA/high" = "high" -``` - -These are the values FerroSMART writes into `acr`. Behind FerroSMART, set -the floor to substantial at least: the xShare Yellow Button that FerroBRIDGE -serves reads the patient's record with their own exchanged token, which -this gate holds to the floor -([Behind FerroSMART](../behind-ferrosmart.md#the-patients-own-token-through-ferrobridge)). - -Boot refuses a `minimum` with an empty `levels` table or with no value mapped at -or above it (every patient-data request would be refused), a blank `claim` -beside a declared table, and a `levels` value that is blank or carries -whitespace, a quote or a backslash, because the refusal names the accepted -values in one quoted, space-separated `acr_values` parameter (RFC 9470 §3). - -A Basic credential carries no level, so with `minimum` set every Basic user, -mapped to a person or not, is refused on patient data. While `minimum` is unset -and a Basic user is mapped in `[[authz.party_binding.basic_user]]`, boot logs a -`warn` naming those users. - -The access record carries the acting mode and the professional the caller -classification names; see [Audit trail](../audit.md#the-ehds-logging-elements-mapped). -`[authz.professional]` is refused at boot: the token's `fhirUser` classifies -the caller, and its RFC 8693 `act` names who acts for them. - -### `[authz.party_binding]` - -How a person is attributed. There is no switch: binding is how FerroEHR -attributes a person, and `enabled` is refused at boot. - -| Key | Type | Default | Description | -|---|---|---|---| -| `provider` | `{ issuer, id }` | **required** once `[auth]` admits a credential | The healthcare provider this deployment acts for, as an identifier issuer and id (in the Netherlands the URA). Every access record of a bound or provisional person and every version a person commits name it (EHDS Art. 13(4), Annex II 3.2(a)). | -| `namespace` | string | `demographic` | The `PARTY_REF.namespace` a bound party is written under, the value of the ITS-REST overview example (`committer.external_ref.namespace="demographic"`), held to the `OBJECT_REF.namespace` pattern `[a-zA-Z][a-zA-Z0-9_.:/&?=+-]*`. | -| `basic_user` | `[[authz.party_binding.basic_user]]` tables | `[]` | One per Basic user: `user`, `key_issuer` (the `identifier_issuer` of an `[auth.issuer..party]` table) and `key`, the binding key the user's `PERSON` carries. A Basic user with no table, a table naming no Basic user and a `key_issuer` no table names refuse the start. | -| `issuer` | `[[authz.party_binding.issuer]]` tables | `[]` | How the tokens of one issuer are read when a first login creates a provisional `PERSON`; see [Just-in-time creation](#just-in-time-creation). | -| `provisional_report_after` | duration | `"30d"` | The age past which `ferroehr party-binding check` reports a provisional `PERSON`. | - -```toml -[authz.party_binding] -provider = { issuer = "urn:oid:2.16.528.1.1007.3.3", id = "12345678" } - -[[authz.party_binding.basic_user]] -user = "clinician" -key_issuer = "urn:example:staff-login" -key = "3f2b0c1e-0000-4000-8000-000000000001" -``` - -#### The party mapping - -SCIM provisioning, just-in-time creation and the login binding read and -write the same demographic parties under one mapping. It names the -templates each party is valid against, the identifier selectors of the -binding key, `userName` and `externalId`, and where each SCIM attribute and -OpenID Connect claim goes. Names go in `PARTY.identities` and identifiers -in `PARTY.details` (RM demographic §Names and Addresses, §Party -Identification), and boot refuses a name mapped into `details` or an -identifier mapped into `identities`. No openEHR specification governs this -mapping: it is FerroEHR's own design, and its targets are RM demographic -paths. - -| Section | Keys | Description | -|---|---|---| -| `[[authz.party_binding.person.template]]` | `template_id`, `key`, `user_name`, `external_id`, `default` | One per template a professional's `PERSON` may use, so a migrated template can stay beside a new one. `key`, `user_name` and `external_id` are selectors, each `{ path, type }`: the path of the `ELEMENT` holding the `DV_IDENTIFIER` and its `type`. Every identifier can sit at one path (the repeated element of an identifier cluster), so two selectors at one path are told apart by `type`, and the key by its issuer, the `identifier_issuer` of an `[auth.issuer..party]` table. Exactly one table sets `default = true`: SCIM and just-in-time creation create new persons with it. | -| `[[authz.party_binding.person.attribute]]` | `scim`, `oidc`, `jit`, `name`, `path` | One per mapped value: a SCIM attribute path (the RFC 7644 `valuePath` form, `emails[type eq "work"].value`, and the FerroEHR extension `urn:ietf:params:scim:schemas:extension:ferrohealth:2.0:User:loginIdentifier` that feeds the binding key), an OpenID Connect claim, whether just-in-time creation writes it (`jit`, default `false`), whether it is the name the committer reads (`name`, at most one), and `path`, one path per template id. `id`, `schemas`, `meta`, `active`, `userName` and `externalId` are SCIM's own and are never mapped. | -| `[authz.party_binding.professional_role]` | `template_id` | The template of the professional `ROLE`, rooted at `ROLE`. A `PERSON` is a professional while it lists a `ROLE` of this template that names it as `performer`, is `complete` or `incomplete`, and whose `time_validity` holds today. | -| `[authz.party_binding.group]` | `template_id`, `external_id`, `display_name` | The template of a SCIM Group's `GROUP`, its `externalId` selector and the path of its `displayName`. | -| `[authz.party_binding.membership]` | `archetype_id` | The `PARTY_RELATIONSHIP` archetype of a group membership, as each membership's `archetype_node_id` carries it (the interface form of an ADL 2 id, `openEHR-DEMOGRAPHIC-PARTY_RELATIONSHIP.membership.v1`). SCIM serves `/Groups` when the group table names a `display_name` and this table is set. | -| `[authz.party_binding.patient]` | `template_id`, `identifier`, `name` | The template of a patient's `PERSON`, the subject of an EHR and the target of a representation: the path of the `ELEMENT` holding its identifiers (each a `DV_IDENTIFIER` of any type and issuer) and the path of its name. A `PERSON` written under this template is validated against it. | - -With no mapping key set, every section maps FerroEHR's [default -demographic definitions](default-demographic-definitions.md), which the -server stores as it boots when the definition store holds no definition of -their id. An empty configuration has this mapping: - -```toml -[[authz.party_binding.person.template]] -template_id = "openEHR-DEMOGRAPHIC-PERSON.healthcare_professional.v1.0.0" -default = true -key = { path = "/details[id2]/items[id3]", type = "login" } -user_name = { path = "/details[id2]/items[id3]", type = "scim_user_name" } -external_id = { path = "/details[id2]/items[id3]", type = "scim_external_id" } - -[[authz.party_binding.person.template]] -template_id = "openEHR-DEMOGRAPHIC-PERSON.patient.v3.0.0" -key = { path = "/details[id2]/items[id3]", type = "login" } -user_name = { path = "/details[id2]/items[id3]", type = "scim_user_name" } -external_id = { path = "/details[id2]/items[id3]", type = "scim_external_id" } - -[[authz.party_binding.person.attribute]] -scim = "name.formatted" -name = true -path = { "openEHR-DEMOGRAPHIC-PERSON.healthcare_professional.v1.0.0" = "/identities[id4]/details[id5]/items[id6]", "openEHR-DEMOGRAPHIC-PERSON.patient.v3.0.0" = "/identities[id6]/details[id7]/items[id8]" } - -[[authz.party_binding.person.attribute]] -scim = "name.givenName" -path = { "openEHR-DEMOGRAPHIC-PERSON.healthcare_professional.v1.0.0" = "/identities[id4]/details[id5]/items[id7]", "openEHR-DEMOGRAPHIC-PERSON.patient.v3.0.0" = "/identities[id6]/details[id7]/items[id9]" } - -[[authz.party_binding.person.attribute]] -scim = "name.familyName" -path = { "openEHR-DEMOGRAPHIC-PERSON.healthcare_professional.v1.0.0" = "/identities[id4]/details[id5]/items[id8]", "openEHR-DEMOGRAPHIC-PERSON.patient.v3.0.0" = "/identities[id6]/details[id7]/items[id10]" } - -[[authz.party_binding.person.attribute]] -scim = 'emails[type eq "work"].value' -path = { "openEHR-DEMOGRAPHIC-PERSON.healthcare_professional.v1.0.0" = "/contacts[id9]/addresses[id10]/details[id11]/items[id12]" } - -[authz.party_binding.professional_role] -template_id = "openEHR-DEMOGRAPHIC-ROLE.healthcare_professional.v1.0.0" - -[authz.party_binding.group] -template_id = "openEHR-DEMOGRAPHIC-GROUP.care_team.v1.0.0" -external_id = { path = "/details[id2]/items[id3]", type = "scim_external_id" } -display_name = "/identities[id4]/details[id5]/items[id6]" - -[authz.party_binding.membership] -archetype_id = "openEHR-DEMOGRAPHIC-PARTY_RELATIONSHIP.membership.v1" - -[authz.party_binding.patient] -template_id = "openEHR-DEMOGRAPHIC-PERSON.patient.v3.0.0" -identifier = "/details[id2]/items[id3]" -name = "/identities[id6]/details[id7]/items[id8]" -``` - -The template ids are the ADL 2 ids of the stored archetypes, and the -membership archetype is named in the interface form each membership's -`archetype_node_id` carries. The patient template is a person template too, -never the default: a patient's login binds their `PERSON` in it. A -representation needs no section: FerroEHR recognises it by its coded name, in -any archetype (see -[Representatives](../operational-policy.md#representatives)). The default -key is of the type `login`, so an `[auth.issuer..party]` table whose -`identifier_type` is `login` needs no mapping key. - -A section you set replaces that section's default whole: a deployment that -sets `[[authz.party_binding.person.template]]` maps its own attributes too. -A deployment with templates of its own sets the sections that name them and -stores its templates before boot (`ferroehr definitions load`); the server -stores nothing under its ids, and still stores the default definitions, -which no section of its mapping then names. - -A worked example over the default definitions, with the Microsoft Entra -object id as the binding key. It sets the person section, and every other -section keeps its default: - -```toml -[[authz.party_binding.person.template]] -template_id = "openEHR-DEMOGRAPHIC-PERSON.healthcare_professional.v1.0.0" -default = true -key = { path = "/details[id2]/items[id3]", type = "guid" } -user_name = { path = "/details[id2]/items[id3]", type = "scim_user_name" } -external_id = { path = "/details[id2]/items[id3]", type = "scim_external_id" } - -[[authz.party_binding.person.attribute]] -scim = "name.formatted" -oidc = "name" -jit = true -name = true -path = { "openEHR-DEMOGRAPHIC-PERSON.healthcare_professional.v1.0.0" = "/identities[id4]/details[id5]/items[id6]" } -``` - -With Microsoft Entra ID, map the object id to `externalId` (Entra's -matching) and to the binding-key attribute (the binding): two attributes, -two selectors. The key's party table's `identifier_type` is `guid`, so a -key differing only in case binds one login. - -Boot refuses, naming the key: no or two `default` tables; a selector path -that does not compile; two equal selectors; any selector under the Dutch -BSN namespace (OID `2.16.840.1.113883.2.4.6.3`); a key fed by an email -address, a phone number, `preferred_username`, `name`, `upn` or -`unique_name`; a template that is absent, rooted at another class or lacks -a mapped path; and a path whose type cannot carry its source. Deleting a template -the mapping names is refused with `409`. - -The parties the binding relies on are protected: a `PERSON` of a mapped -template carrying a selector identifier, its professional `ROLE`, a -representation (a `PARTY_RELATIONSHIP` of its own named -`openehr_access::represents`), and a `GROUP` of the group template. Only an -administrator (`authz.rbac.admin_role`) writes one through the demographic -API, including the creation of a party that carries a selector identifier; -a `write_representation` holder writes a representation for the providers -its grant names, and the patient a representation targets writes one on the -basis `HL7_RoleCode::DELEGATEE`. -The policy parties (a party holding a capability coded in -`openehr_access`, an acts-for relationship or an `openehr_access::client_id` client identifier) -are recognised by what they hold and take no key of this mapping; they are an administrator's to write and to read, -never a SCIM client's: see [Operational policy](../operational-policy.md#who-writes-and-reads-a-policy-party). -An administrator's version that leaves a protected identifier out is refused -with `422`. A present binding key is immutable (RFC 7643 §2.2): a version -that changes it is refused with `403`, and -[`POST /admin/party/binding-key`](../operations-admin-apis.md) is the one -change. Each selector value binds one live party: a commit that gives a -binding key, a `userName` (compared after RFC 8265 width mapping, lower case -and NFC), an `externalId` or a group `displayName` a second party is refused -with `409`. A deleted `PERSON` leaves its key as a tombstone that refuses -the login until an administrator binds the key again. - -#### Changing the mapping - -The side table is filled from the configured mapping and the party -versions. The first boot fills it and stores the mapping's digest, which -covers the templates, the selectors, the role, the group and the membership. -It leaves out the key issuers: the `identifier_issuer` of each -`[auth.issuer..party]` table. Each running replica holds -a lease it renews every 20 seconds, and the lease lists the key issuers the -replica derives keys for. - -**Adding or removing a key issuer needs no stop and no refill.** Each key -issuer is a key space with a state: - -| State | Its keys bind a login | What happens next | -|---|---|---| -| `pending` | No: the login is answered `503` with a `Retry-After` | Once every live replica names the issuer, a replica fills its keys from the party versions | -| `filling` | No: `503` with a `Retry-After` | The fill runs online in pages and the issuer turns `active` | -| `active` | Yes | A replica that starts without the issuer turns it `retiring` | -| `retiring` | No: the login is refused with `403 refused-unbound` | Once no live replica names it, its keys are deleted; once every live replica names it again, it is filled anew | - -So a rolling upgrade that adds an issuer serves every other issuer -throughout, and the new issuer's logins bind on every replica once the last -replica without it is replaced. A replica restarted without an issuer stops -that issuer's logins binding on every replica at once, so revoking an issuer -needs no downtime. A fill that finds two parties carrying one -key under the new issuer keeps it `pending`, logs both parties, and looks -again after five minutes; the other issuers keep binding. - -**A change to the templates, selectors, role, group or membership is a -stop-the-world step.** A replica whose mapping digest differs from the stored -one refuses to start, naming both digests: - -1. Stop every replica. With Helm, scale the deployment to zero first: a - rolling upgrade would start new replicas beside old ones. -2. Run `ferroehr party-binding refill` with the new configuration. It - refuses while a replica's lease was renewed within the last minute, and - refuses a store in which two parties carry one selector value, naming - both. -3. Start the replicas with the new mapping. A replica still holding the old - mapping refuses to start. - -#### How a login is looked up - -Every request of a person is looked up in the binding side table of the -party store, on the party database role, with no cache, so a change to a -party takes effect on the next request on every instance. The table holds -the binding key of each `PERSON` of a mapped template that performs a -professional `ROLE` (a `ROLE` of the mapped role template that its `roles` -list, that names it as `performer`, whose state is `complete` or -`incomplete` and whose `time_validity` holds today's date in UTC) or that -is the source of a representation. A key of type `guid` or -`uuid` is compared in lower case. The table is written in each party -commit's transaction and can be rebuilt from the party versions alone. - -The request is refused with `403` and the binding code in the problem body -when the login matches two parties (`refused-ambiguous`), when its party is -`inactive` (`refused-inactive`) or `abandoned` (`refused-abandoned`), when -its key belongs to a deleted party (`refused-deprovisioned`), when the token -carries no `sub` (`refused-key-claim-missing`), when the party lacks the -marker the caller's kind needs (`refused-wrong-marker`), when the groups a -token asserts cannot be read (`refused-groups-unavailable`), and when a -representative reaches a subject its party has no live -representation of, stored in the CDR for the provider the deployment acts -for and not written by the representative itself -(`refused-representation-unrecorded`). A party -store that cannot answer is answered `503`. - -A person whose login matches no party is refused with `403` and -`refused-unbound` on every request, reads and writes alike; only the public -endpoints outside the auth layer answer. The problem names the identifier -issuer to provision the person under, and the refusal of a token without -`sub` names that claim instead. No setting serves an unbound person -under a login-only committer, so provision every professional (through -[SCIM](#authscim) or the demographic API) before you add an issuer, or -let the issuer create a provisional `PERSON` at the first login -([just-in-time creation](#just-in-time-creation)). Each -refusal writes one `warn` line naming the issuer and the outcome, never the -claim value, and counts into the `binding_refusals` metric by `issuer` and -`outcome`. - -A representative reaches only the EHRs of a subject their `PERSON` holds a -live representation of, stored in the CDR for the provider -`[authz.party_binding.provider]` names and read from the store, never from -the token (EHDS Art. 4(2)). The access evaluator holds every request that -names an EHR to those EHRs, whatever the token's scopes cover, and refuses -any other with `403` `refused-not-represented`; a query must name one with -`ehr_id`, and an operation that names no EHR is refused the same way. -Templates stay readable. A professional's token whose only clinical scopes -are `patient/` is confined to its launch EHR, and its commits record the -professional, never `PARTY_SELF`. See -[Representatives](../operational-policy.md#representatives). - -#### Just-in-time creation - -Just-in-time creation lets a professional with no party work under their own -account at their first login, before SCIM or an administrator completes the -record. When a professional's login matches no party, and a -`create_at_login` grant in the CDR admits it, FerroEHR commits one `PERSON` -of the default template with lifecycle state `553|incomplete|`, which RM -common §Incomplete Content allows for "incomplete demographic details", and -its professional `ROLE` in the same demographic contribution, then serves the -request bound to it. The next request binds to that `PERSON` and creates -nothing. When a login creates a party is FerroEHR's own design: no openEHR -specification governs it. - -Which logins are created is operational policy, so it is CDR data and no -configuration key: an administrator writes a `ROLE` whose capability grants -`openehr_access::create_at_login`, naming the issuer and the admission -conditions, through the Demographic API. The grant is read on each first -login, so a change applies to the next one without a restart. The -[Operational policy](../operational-policy.md#just-in-time-admission) page -documents the grant and has a worked example. `[authz.grants] allowed` -must list `create_at_login`, which the default does not, or no such grant -can be written or honoured. - -The `[[authz.party_binding.issuer]]` table only says how an issuer's tokens -are read, and an issuer without one reads the defaults: - -| Key | Type | Default | Description | -|---|---|---|---| -| `issuer` | string | required | An issuer an `[auth.issuer..party]` table binds. | -| `user_name_claim` | string | `sub` | The claim the `userName` is read from. It must be one the issuer controls: an email address, a phone number, `preferred_username`, `name`, `upn` and `unique_name` refuse the start. | -| `idp_claim` | string | `idp` | The dotted claim path an `admit_idp` condition reads the identity provider from (the Microsoft Entra `idp` claim). | - -Creation also needs a default person template with a `user_name` selector, -`[authz.party_binding.professional_role]`, and an attribute that maps an -OpenID Connect name claim (`name`, `given_name`, `family_name`, -`middle_name` or `nickname`) to the default template. The default mapping -has them. When a grant admits a login and the mapping lacks one, the login -is not created and the server logs what is missing. - -```toml -[[authz.party_binding.issuer]] -issuer = "https://login.microsoftonline.com//v2.0" -user_name_claim = "oid" -``` - -What it writes is the attribution minimum: the binding key, the `userName` -and the name claims the token carries. Any other mapped attribute is written -only where its `[[authz.party_binding.person.attribute]]` sets `jit = true` -(GDPR Art. 25(2), data protection by default), and `externalId` is never -written, since RFC 7643 §3.1 leaves it to the provisioning client. The -version is committed with change type `249|creation|`, a description naming -just-in-time creation and the issuer, and the person's own committer: the -name, the login identifier and an `external_ref` naming the new `PERSON`. -FerroEHR reads every value from the access token only (RFC 9068 §2.2.2), so -the issuer must put the name claims in the access token. - -It runs only for a person or a delegated caller of the issuer, never for a -representative, a patient, a system or a `federation` caller, and never for a -login whose outcome is anything other than unbound: an ambiguous, inactive, -abandoned or deprovisioned party, a token without the key claim and a party -with the wrong marker are refused as before. A `PERSON` a SCIM client deleted -is never created again by a later login, whatever the identity provider still -issues. A login that no grant in force admits, or whose token carries no -mapped name claim, is refused with `403` and `refused-unbound`. - -Concurrent first requests of one login commit one `PERSON`: the binding key's -unique index refuses the second commit, and that request binds to the first -one's `PERSON`. A login whose `userName` another party already holds is -refused with `403` and binds nothing. Just-in-time creation only creates: it -never updates, deactivates or deletes a `PERSON`, so a later login with -changed claims changes nothing. - -A `PERSON` whose latest version is `incomplete` is provisional. The access -record of each of its requests carries `binding = provisional`, a demographic -read and an AQL query over `VERSION/lifecycle_state` show it, and -`ferroehr party-binding check` reports the provisional persons older than -`provisional_report_after` under `side_table.provisional`. What a provisional person may do is decided by -their SMART scopes and roles, as for anyone. A SCIM client whose -`binding_issuer` is the issuer's `identifier_issuer` completes the `PERSON`: -it finds it by `userName`, with a binding key equal to its own, writes the -`externalId` with a `PATCH`, and a complete `PUT` completes it. SCIM -`active = false` abandons it. - -The lawful basis for the attribution minimum (key, `userName`, name) is GDPR -Art. 6(1)(c): EHDS Art. 13(4) and the logging duties need the professional -identified. An operator who opts a contact attribute in with `jit = true` -names its own basis, Art. 6(1)(b) or (f). Because the data come from the -identity provider and not from the person, tell the professionals what Art. 14 -asks: what is copied, from which source, and why. On a realm or tenant that -creates persons, make the name attributes administrator-controlled, as the key -is; [Enterprise identity providers](../identity-providers.md#just-in-time-creation) -shows the settings per identity provider. - -### Imports and system clients - -The systems whose wrapped committers an import may carry are no key: a -`creating_system` element of the importer's import grant names each one -([What the grants decide](../operational-policy.md#what-the-grants-decide)). - -The system clients are not configuration. An OAuth client-credentials client -is granted what it may commit, import or export in the CDR, as an `ACTOR` -carrying its `client_id` that acts for a provider and performs a `ROLE` whose -capabilities grant the operations; see -[What a system client may do](../operational-policy.md#what-a-system-client-may-do). -The former `[[authz.system_client]]` table is an unknown key and refuses the -start. - -### Federation agreements - -A federation agreement is CDR data, not a configuration key: a grant of -`federated_person_access` or `federated_organisation_access` on the partner's -party, read on every request and judged when it is written. The configuration -keeps what the agreements are judged against: the `federation` issuers, their -`[auth.issuer..federation]` tables, `[authz.grants] allowed` (which must name both -codes before an agreement can be written). The period a `chained` agreement -is held to is the access log retention of the controller's access policy -(`ACCESS_POLICY.log_retention`). The model, the codes and the rules are on -[Operational policy](../operational-policy.md#federation-agreements). The -`[[authz.federation.agreement]]` table is removed, and a configuration that -still holds it is refused at boot as an unknown key. - -### `[authz.grants]` - -| Key | Type | Default | Description | -|---|---|---|---| -| `allowed` | list of operation codes | `["commit_composition"]` | The operations of the `openehr_access` terminology the policy grants may grant. A `ROLE` committed with a capability that codes an operation this list does not name is refused with `403`, and one already stored is never honoured, so a compromised administrator account grants no more than you allow. Allow `compose_for` to let a professional name another `PERSON` of the same provider as the composer of what they commit ([Who is the committer](../security/committer.md#the-composer-of-a-professionals-composition)). An empty list lets the party store grant nothing; an unknown code refuses the start. Environment: `FERROEHR__AUTHZ__GRANTS__ALLOWED`, comma-separated. The codes and how a request reads its grants are on [Operational policy](../operational-policy.md#how-a-request-reads-its-grants). | - -### `[authz.rbac]` - -| Key | Type | Default | Description | -|---|---|---|---| -| `enabled` | bool | `true` | The coarse role gate (active when authentication is enabled). Off, every authenticated caller may use every enabled surface, reported as the `rbac_off` deployment gap. `ehr_access_default` and `admin_role` apply either way. | -| `admin_role` | string | `ADMIN` | Role required for admin-class operations. A blank value is a boot error. | -| `readonly_role` | string | `READONLY` | Role marking a principal read-only: refused on every write operation (create/update/delete/upload), even alongside granting roles. Reads and AQL queries are still allowed. | -| `role_issuers` | list of string | `[]` | The issuers whose role claims may grant `admin_role`. A token of any other issuer never holds it, a Basic user keeps the roles its own table grants, and a `hold_roles` policy grant never gives one. A `federation` issuer refuses the start. Empty, no token grants them. | -| `ehr_access_default` | enum{open,restricted} | `open` | What an EHR carrying no `ACCESS_CONTROL_SETTINGS` admits. `restricted` is object-level default-deny: only `admin_role` reaches a setting-less EHR, so an operator can still author the settings that open it. It is enforced whether `enabled` is on or off. With `[auth] enabled = false` nothing could enforce `restricted`, so that combination is a boot error. See [Security](../security.md#per-ehr-access-control-ehr_access). | - -Reading one subject's access log, acting as an EHDS Art. 10 access service, -and importing an EHR or an extract have no key here: each is a grant in the -CDR (`read_subject_audit`, `access_service`, `import_ehr` and -`import_ehr_extract`), -under `[authz.grants] allowed`. The keys that named a role for them before -5.7.1 are unknown keys, and the server refuses to start with one -([What the grants decide](../operational-policy.md#what-the-grants-decide)). - -> [!NOTE] -> The management surface is **not** configured under `[authz.rbac]`. -> [`[management.endpoints]`](#management) owns it, one level per endpoint, with -> no global default beside it: an endpoint you do not name is `off` and is not -> mounted. Only the `admin_only` level consults `authz.rbac.admin_role`. - ## `[api] admin` | Key | Type | Default | Description | @@ -739,401 +275,16 @@ Physical deletion is irreversible, so the group stays off by default. With it on, `/admin` also joins the group list the `OPTIONS` System-Options manifest advertises, so the manifest never names a group that answers `404`. -## `[auth.scim]` - -FerroEHR is a SCIM 2.0 service provider (RFC 7644) at `/scim/v2/`, the -endpoint an identity provider provisions each professional through. It is off -by default. - -| Key | Type | Default | Description | -|---|---|---|---| -| `filter_max_results` | integer | `100` | The most resources one list response returns, which `ServiceProviderConfig` declares as `filter.maxResults`. At least 1. | -| `max_deactivations` | integer | `100` | The most Users one client deactivates or deletes per window. Past it, a deactivation or deletion is **429** with `Retry-After` and logged at `error`. The count is kept in the database, so every replica shares one bound. At least 1. | -| `deactivation_window` | duration | `"1h"` | The length of that window. At least `"1min"`. | -| `contact_erasure_delay` | duration | `"0s"` | How long after a User's deletion the contacts of every version of its `PERSON` are erased (GDPR Art. 17). `"0s"` erases them in the deletion itself; at most `"30d"`. | -| `max_group_members` | integer | `5000` | The most members one Group holds. An add past it is **400** `invalidValue`. A membership change versions only the member's `PERSON`, so its cost does not grow with the Group. At least 1. | - -Who provisions is CDR data, read on every request: a provisioning client is -an OAuth client-credentials client of your own authorization server whose -`ACTOR` holds a `scim_provision` grant in force. The grant's -`binding_issuer` is the identifier issuer of the binding keys the client -provisions: the `identifier_issuer` of an `[auth.issuer..party]` table -your professionals log in through. Its `token_scope` is the scope a token of the client -must hold; SMART on openEHR defines none for SCIM, so the value is yours to -choose. Each User belongs to the one client whose `binding_issuer` issues its -key, so no two clients' grants name one. `[authz.grants] allowed` must admit -`scim_provision`. The first such grant is written with -[`ferroehr party-binding grant`](../operational-policy.md#the-first-grant), -since no administrator can log in before the persons it provisions exist; -[Operational policy](../operational-policy.md#what-the-grants-decide) has the -grant's terms. - -Every `meta.location` and discovery document names the resource by its URI -(RFC 7643 §3.1), under `/scim/v2` with -[`server.public_base_url`](config-server.md#public_base_url-the-one-public-url) -and `server.base_path`, so the table needs that key. - -The table's presence turns the endpoint on; it has no `enabled` key, and -setting one refuses the start. The start is refused when the table is present -without `server.public_base_url`, and when the [party mapping](#authzparty_binding) -lacks what a User is written with: a default person template with a -`user_name` selector, and `[authz.party_binding.professional_role]`. - -```toml -[server] -public_base_url = "https://cdr.example.com" - -[auth.scim] - -[authz.grants] -allowed = ["commit_composition", "scim_provision"] -``` - -`/scim/v2/ServiceProviderConfig` answers without a token, so a client can read -the authentication scheme before it holds one. Every other path needs a -bearer token of a client that acts for nobody and holds a `scim_provision` -grant in force: - -- no token, or one that does not verify, is **401** with - `WWW-Authenticate: Bearer`; -- a person's token, a client with no grant in force, a grant whose - `binding_issuer` is not the `identifier_issuer` of an `[auth.issuer..party]` - table, or another client's grant names too, and a token without the grant's `token_scope` are **403**, the - last with `WWW-Authenticate: Bearer error="insufficient_scope"` (RFC 6750 - §3.1). - -Every refusal is an RFC 7644 §3.12 `Error` message in `application/scim+json`. -The client's requests count against -[`[server.caller_rate]`](config-server.md) like any caller's, so each -replica gives the client an allowance of its own, and past it a request is -**429** with `Retry-After`. `/scim/v2/Schemas` serves the core User schema -reduced to `userName`, `active` and the SCIM attributes -`[[authz.party_binding.person.attribute]]` maps, and FerroEHR's extension -`urn:ietf:params:scim:schemas:extension:ferrohealth:2.0:User` with -`loginIdentifier`, the attribute that feeds the binding key. `/ResourceTypes` -lists the `User` type at `/Users`, and the `Group` type at `/Groups` with -FerroEHR's Group extension -`urn:ietf:params:scim:schemas:extension:ferrohealth:2.0:Group` and its -immutable boolean `careTeam` when Groups are served. - -The two extension URNs are a deliberate deviation from RFC 7643. They sit -under `urn:ietf:params:scim:schemas:extension:`, the sub-namespace RFC 7643 -§10.2 and RFC 3553 reserve for names IANA assigns, and neither name is in the -IANA "SCIM Schema URIs" registry (RFC 7643 §10.3). The reason is Microsoft -Entra ID: its provisioning client sends a custom attribute only under a name -of the form -`urn:ietf:params:scim:schemas:extension:CustomExtensionName:2.0:User:CustomAttribute` -("For SCIM applications, the attribute name must follow the pattern shown in -the example", *Customize Microsoft Entra attribute mappings*, vendored at -`docs/specs/microsoft-entra/docs/identity/app-provisioning/customize-application-attributes.md` -line 148). A schema id outside that namespace, which RFC 7643 §3 would allow, -leaves an Entra non-gallery application unable to send `loginIdentifier`, so -it could not provision anyone. The binding key fits no registered attribute: -`userName` is mutable, `externalId` is the client's own identifier for the -resource (RFC 7643 §3.1), and the Enterprise User extension (§4.3) carries no -login subject. The two URNs are the provisioning contract of the FerroHEALTH -products, fixed in the same way as the `/scim/v2` base path, and a client -writes them exactly as `/Schemas` lists them. - -### Users - -A User is a `PERSON` of the default person template performing the -professional `ROLE`: SCIM (RFC 7643, RFC 7644) provisions a workforce. A -patient needs no provisioning, since their own token's login binds their -`PERSON`. A representation is a `PARTY_RELATIONSHIP` of its own, written by -the patient, an administrator or a `write_representation` holder -(Regulation (EU) 2025/327 Art. 4(2)), and a User version that holds one in -its relationships is refused `422`. This is FerroEHR's own design. The client serves these operations (RFC 7644 §3): - -- `POST /scim/v2/Users` creates the `PERSON` and its `ROLE` in one demographic - CONTRIBUTION, under the client as committer, and answers **201** with the - User, its `Location` and its `ETag`. The body carries `userName` and the - binding key in `loginIdentifier`; `externalId` and every mapped attribute - are optional. A version that fits its template in full is `complete`, and - one that fits only with every lower limit at zero is `incomplete`, which the - User's `lifecycleState` and `missingPaths` name. A User created with - `active = false` is **400** `invalidValue`. -- `GET /scim/v2/Users/{id}` answers the User with its `ETag`, the weak tag of - its version, and **304** to an `If-None-Match` naming that version. -- `GET /scim/v2/Users` answers a `ListResponse`, an empty one with **200** - when nothing matches. `filter` takes `eq` and `and` over `userName`, - `externalId` and `id`; names and operators are compared in any case, and - anything else is **400** `invalidFilter`. `startIndex` and `count` page the - result, at most `max_results` at a time. - -The User's `userName`, `externalId` and binding key are `DV_IDENTIFIER`s at -their selectors, issued by the client's `binding_issuer`. A client sees only -its own Users, the ones whose key its `binding_issuer` issues: every other id -is **404** and absent from every list, as is a `PERSON` without a live -professional `ROLE`. The `userName` index spans every client, so a **409** -`uniqueness` tells one client that a `userName` exists under another; -`externalId` is unique within one client. Every SCIM request is an access -record of the client, with the `PERSON` as its object. - -A User is changed and removed through these operations: - -- `PUT /scim/v2/Users/{id}` replaces the User (RFC 7644 §3.5.1). A mapped - attribute the body leaves out is cleared; the binding key and `externalId` - are kept, and a left-out `active` keeps the lifecycle state. -- `PATCH /scim/v2/Users/{id}` applies the RFC 7644 §3.5.2 operations, value - paths and a `replace` without `path` included, and commits the result as - one version. The operation is read in any case, as the Entra ID client - sends `Replace`. -- `DELETE /scim/v2/Users/{id}` logically deletes the `PERSON` and its - professional `ROLE` in one demographic CONTRIBUTION and answers **204**. - Every later request on the id is **404**, the User leaves every list, and a - new User may take its `userName`. The binding key stays behind as a - tombstone: a login on it is refused as deprovisioned until the owning - client creates a User with it again. - -Each write answers with the User and its new `ETag`. An `If-Match` naming -another version is **412**, a changed binding key is **400** `mutability`, and -a write without `If-Match` is accepted (RFC 7644 §3.14 makes entity tags a -MAY). `active` drives the lifecycle state of the `PERSON` (RM common -§Version Lifecycle): - -| Current state | `active` in the request | Result | -|---|---|---| -| `complete` or `incomplete` | `true` or left out | `complete` when the template holds in full, else `incomplete` | -| `complete` | `false` | `inactive` | -| `incomplete` | `false` | `abandoned` | -| `inactive` | `true` | `complete`, or `incomplete` when the template does not hold | -| `abandoned` | `true` | `incomplete`, then `complete` in a second version when the template holds | -| `inactive` or `abandoned` | `false` or left out, with a change | **400** `invalidValue`: reactivate the User first | -| `inactive` or `abandoned` | `false` or left out, without a change | **200**, no new version | - -An inactive or abandoned User is still read and found by a filter, so its -client can reactivate it. When the second version of an `abandoned` User -fails, the User stays `incomplete` and the same request completes it. - -#### Roles - -A User's `roles` (RFC 7643 §4.1.2) are the roles the access policy's -[controller rules](../operational-policy.md#controller-rules) name. Each -value is one `ROLE` the User's `PERSON` performs, of the professional role -template, whose `name` is the value coded in the terminology the client's -`scim_provision` grant names, and whose `time_validity` starts on the day it -is added. The grant states which roles the client may hand out: - -| Element | Value | -|---|---| -| `role_terminology` | The terminology id the client's role values are coded in, exactly one | -| `role` | A role code the client may assign, one element per code | - -A request whose `roles` names a code the grant does not list, or any role -when the grant names no `role_terminology`, is **403** and changes nothing. -A `POST`, `PUT` or `PATCH` makes the User hold exactly the roles its result -lists: a new value commits a new `ROLE`, and a removed one ends its `ROLE` -the day before (its `time_validity` gains the date of the removal as its -exclusive end) and drops it from the `PERSON`'s `roles`. The change decides -the next request on the replica that took it, and on every other replica -once the commit's notification arrives, with no added transaction. A token's -role claims never drive a controller rule. These `ROLE`s carry no -capability, so a SCIM client writes them, and an administrator alone grants -a capability. RFC 7643 sets no vocabulary for `roles` and RFC 7644 §2 leaves -the authorization model out: the mapping is FerroEHR's own design. - -The versions of a deleted User are kept for the record-keeping duties that -need the professional's identification (GDPR Art. 6(1)(c), laid down in law -as Art. 6(3) requires: in the Netherlands BW 7:454(3), twenty years, and the -logging duty of the Besluit elektronische gegevensverwerking door -zorgaanbieders). Outside the Netherlands, name your national retention -provision. Enable the identity provider's protection against accidental -deletions beside `max_deactivations`. - -Only the attribution minimum waits for that horizon: the name, the binding key -and the identifiers, `userName` and `externalId` among them. The contacts -serve no attribution, so FerroEHR erases them (GDPR Art. 5(1)(e)): with -`auth.scim.contact_erasure_delay = 0` the deletion removes the `contacts` of every -version of the `PERSON` in the same transaction, and with a period a sweep -that runs every minute removes them once the period has passed. The sweep -reaches every deleted `PERSON` whose binding key the `binding_issuer` of a -`scim_provision` grant issues, one that has ended included, -an administrator's demographic `DELETE` included. Each version keeps its uid, -audit and contribution, and its node rows are derived again from the erased -body. A server signature on such a version is removed, because it was taken -over the content the erasure changed. Each erasure is an access record, a -delete of `party:#contacts`. A login on the key is still refused as -deprovisioned. - -### Groups - -When `[authz.party_binding.group]` names a `display_name` and -`[authz.party_binding.membership]` is set, `/scim/v2/Groups` is served beside -`/Users`, and `/scim/v2/ResourceTypes` lists the Group. A Group is a -demographic `GROUP` of the group template: - -- its `displayName` is the `GROUP`'s `PARTY_IDENTITY`, unique across the live - Groups after case folding, so a duplicate is **409** `uniqueness`; -- its `externalId` is a `DV_IDENTIFIER` at the `external_id` selector under - the client's group issuer: the `group_identifier_issuer` of the - `[auth.issuer..party]` table whose `identifier_issuer` is the client's - `binding_issuer`, so the group claim of that issuer's tokens matches it. - When that table sets none, the group issuer is the `binding_issuer` with - `/groups` appended (`urn:example:login` gives `urn:example:login/groups`), - with any trailing `/` of the `binding_issuer` dropped first. A deployment - whose tokens assert groups sets `group_claim` and a - `group_identifier_issuer` in the table, and that value is the group issuer; -- each member holds one inline `PARTY_RELATIONSHIP` of the membership - archetype, with its `PERSON` as `source` and the `GROUP` as `target`, - stored in the member's own version (RM demographic §Party Relationships). - No `ROLE` is created for a Group, and a `PERSON` in no Group has - `relationships` Void. -- its `careTeam`, in FerroEHR's Group extension, says whether it is a care - team: set at creation, `false` when left out, and never changed (**400** - `mutability`). A care team is served with `careTeam = true` and the - extension in its `schemas`; any other Group is served without either. A - care team's `GROUP` is named by the coded `care_team` and each membership - by the coded `member_of` of `openehr_access` (RM demographic `PARTY.type()` is the `name`), so - its members are in the care of the patients under the team's care. - Creating one and changing its members needs the client's - `write_care_relationship` grant beside `scim_provision`, and is **403** - without it ([Care teams provisioned over SCIM](../operational-policy.md#care-teams-provisioned-over-scim)). - The group template and the membership archetype must admit a - `DV_CODED_TEXT` name, as the default definitions do. - -A Group belongs to the client that created it; every other client gets -**404**. A member is a User of the same client: a member naming another -client's User, an unknown id or a Group (nested Groups are not supported) is -**400** `invalidValue`. What a Group allows stays with the token's scopes and -roles; the access record lists the Groups the token names that the person -belongs to, and a Group in `inactive` or `abandoned` lists no member. - -- `POST /scim/v2/Groups` creates the `GROUP` with its members, if any, and - answers **201** with the Group, its `Location` and `ETag`. -- `GET /scim/v2/Groups/{id}` and `GET /scim/v2/Groups` filter with `eq` and - `and` over `displayName`, `externalId` and `id`, and - `excludedAttributes=members` leaves the members out. Each member is served - with its `value`, `$ref` and `type`. -- `PATCH /scim/v2/Groups/{id}` answers **204** with the new `ETag` (RFC 7644 - §3.5.2). `add` of `members` adds the listed members; `remove` with the - filter `members[value eq ""]` removes that member, and `remove` of - `members` with neither a filter nor a value list removes them all. -- `PUT /scim/v2/Groups/{id}` replaces the `displayName` and the members, - keeps a left-out `externalId`, and answers **200** with the Group. -- `DELETE /scim/v2/Groups/{id}` logically deletes the `GROUP` with its - memberships, and every later request on the id is **404**. - -**Entra compatibility deviation.** A `remove` of `members` that carries a -`value` list removes only the listed members, the request Microsoft Entra ID -sends. RFC 7644 §3.5.2.2 removes "the attribute and all values" when no -filter is specified; FerroEHR follows Entra only when the `value` list is -present. - -A membership change is a new version of each member's `PERSON` it touches, -in one CONTRIBUTION, and the `GROUP` gets no version; a change costs the same -whatever the Group's size. The Group's `ETag` is its `GROUP` version with a -membership revision that moves with every membership change, so it changes -whenever its members do (RFC 7644 §3.14). The member User's `ETag` changes -too, since its `PERSON` holds the membership (RFC 7643 §4.1.2); its body does -not, because the User serves no `groups` attribute. Deleting a User deletes -the memberships its `PERSON` holds with it. Deleting a Group drops the -membership of each active member in the CONTRIBUTION that deletes the -`GROUP`. A `GROUP` an administrator set `inactive` or `abandoned` keeps its -version, since the version lifecycle draws no update of either state, and a -SCIM write to such a Group is **400** `invalidValue`. - -**Deactivated Users leave their Groups.** The version lifecycle draws no -update of an `inactive` or `abandoned` `PERSON` (RM common master06 §Version -Lifecycle), so such a `PERSON` cannot take a membership change, and an -inactive `PERSON` binds to nothing. Setting a User's `active` to `false` -therefore drops its memberships in the same version, and each Group's -`ETag` changes. A membership of a care-team Group stays, as does every other -care relationship, since SCIM never changes one ([Deprovisioning a team -member](../operational-policy.md#deprovisioning-a-team-member)). Microsoft Entra ID often disables a user and then removes it -from its groups; the later `remove` finds nothing to remove and answers -**204**. An `add` naming an inactive or abandoned User is **400** -`invalidValue` ("reactivate the User first"). A reactivated User belongs to -no plain Group until its client adds it again. - -### Provision from Microsoft Entra ID - -Microsoft Entra ID provisions through a non-gallery enterprise application. -FerroEHR validates the access token your own authorization server issues to -it, so the steps split between the two. - -1. **Map the person template.** The default - [party mapping](#the-party-mapping) maps `userName`, `externalId`, the - formatted, given and family name and the work email Entra sends. Set the - person section only to map more, or to key the binding on the object id - as the worked example there does. - - A value path such as `emails[type eq "work"].value` serves the value and - its `type`. FerroEHR holds one value per `type` and no preference among - them, so `/scim/v2/Schemas` declares `primary` read-only and the `primary` - Entra sends is ignored (RFC 7644 §3.3). -2. **Grant the client.** Grant its client `scim_provision`, with `ferroehr - party-binding grant` or as an administrator through the Demographic API: - the `--issuer` is your authorization server, the `binding_issuer` element the `identifier_issuer` of the - `[auth.issuer..party]` your professionals log in through, and the `token_scope` - element the scope its token holds. Set `server.public_base_url` to the URL - Entra reaches. In the Helm chart, a `config.auth.scim` value also adds the - `/scim/v2` path to the Ingress. `ferroehr config check` refuses a mapping - the endpoint cannot serve. -3. **Federate Entra's credential at your authorization server.** Entra's - Workload Identity Federation presents a signed assertion, which your - authorization server exchanges for a client-credentials access token - (RFC 7523 §2.2). These checks are your authorization server's, not - FerroEHR's, so verify each one there, as Microsoft's "Workload Identity - Federation for SCIM Provisioning" guide requires: - - [ ] `iss` is pinned to your full tenant issuer, - `https://login.microsoftonline.com//v2.0`, and the assertion - verifies against that tenant's key set. - - [ ] `aud` is pinned to `api://`, with one - workload-identity application per FerroEHR deployment. - - [ ] `azp` is pinned to the application id of Microsoft's provisioning - service. - - [ ] `uti` is cached for the lifetime of the assertion, and an assertion - whose `uti` was seen before is refused as a replay. - - [ ] The access token it issues holds the grant's `token_scope`, names the - client in `client_id`, and lives between 1 and 6 hours, the range - Microsoft's guide asks for. - - The assertion's `sub` is the object id of a Microsoft application that - every integration in the tenant shares, never your `client_id`, so it does - not meet RFC 7523 §3 item 2.B. Accepting it is a deviation of your - authorization server; record it there. Leaving Entra's **Secret Token** - blank, so that Entra uses its own token, is not supported: Microsoft - reserves it for testing, and every non-gallery application in the tenant - receives a token with the same `iss` and `aud` (RFC 9700 §2.3). A - long-lived bearer token is not supported either. -4. **Point Entra at FerroEHR.** Set the **Tenant URL** to - `/scim/v2` and run **Test Connection**. Entra queries - `/Users` with `filter=externalId eq ""`, which FerroEHR - answers with an empty `ListResponse`, and fetches a random User and a - random Group, each answered **404**. -5. **Map the attributes in Entra.** Map `userName`, `externalId`, `active` - and the attributes of step 1. Map the attribute that carries the - professional's login identifier to - `urn:ietf:params:scim:schemas:extension:ferrohealth:2.0:User:loginIdentifier`; - Entra sends it without listing the extension in `schemas`, which FerroEHR - accepts. An attribute the person template does not map is refused as - undefined, so remove the rest of Entra's default mappings. -6. **Protect against mass deactivation.** Turn on Entra's accidental - deletions prevention, with a threshold at or below `max_deactivations`. -7. **Provision groups.** Map the group's `objectId` to its `externalId`, so - the object ids Entra puts in the `groups` claim match, and provision only - the groups assigned to the application, which keeps a person's token under - the groups overage limit. Entra creates each Group with no member, reads it - with `excludedAttributes=members`, finds it by `displayName`, and adds and - removes members with PATCH. - -Entra writes `Replace` and `Add` with a capital letter, disables a User with -`active = false`, sends `DELETE` once the user is removed, and never sends a -null. A value cleared in Entra therefore stays in FerroEHR until the User is -replaced or deleted, or an administrator removes it. - ## The access-delay register The EHDS Art. 3(3) delay of the person's own access to newly registered data is a Member State option, and an -[admin register](../operational-policy.md#the-admin-registers), not a +[admin register](../access-policy.md#the-admin-registers), not a configuration key: you turn it on through `{ext}/admin/registers/access-delay` only where your Member State's rule provides for the delay, every version is kept with its committer, and a -change applies on the next request without a restart. `[privacy.access_delay]` -in `ferroehr.toml` is an unknown key and refuses boot. What the delay does is -on [delayed access by the person](../security.md#delayed-access-by-the-person-ehds-art-33). +change applies on the next request without a restart. What the delay does is +on [delayed access by the person](../access-control.md#delayed-access-by-the-person-ehds-art-33). | Member | Type | Default | Description | |---|---|---|---| @@ -1173,7 +324,7 @@ consume. `discovery` alone turns the document on. Which clients count as backend clients and which reach the DEMOGRAPHIC API is policy the CDR holds, never a key here: the `query_system_wide` and `access_demographic` grants of the client's `AGENT` -([Operational policy](../operational-policy.md#a-backend-client-and-a-demographic-client)). +([Operational policy](../policy-examples.md#a-backend-client-and-a-demographic-client)). No `smart` URL may carry a user name or password, whether or not the document is served: the discovery document publishes these URLs to every application, diff --git a/website/book/src/installation/config-authz.md b/website/book/src/installation/config-authz.md new file mode 100644 index 0000000000..422cbcea8c --- /dev/null +++ b/website/book/src/installation/config-authz.md @@ -0,0 +1,468 @@ +# Authorization keys + +`[authz]`: the coarse role gate, the assurance level, the party binding and the grant +ceiling. The other authentication keys are on [Authentication & access](config-auth.md). + + + +## `[authz]` + +Role-based (RBAC) authorization, the party binding, the grant ceiling and the +patient-data assurance gate. Which caller may read which data is the access +evaluator's, over each EHR's `access_directives` and the controller's access +policy, and takes no key here. How the parts fit together and the order a +request is decided in are on [How FerroEHR decides +access](../explanation/access-model.md). + +### `[authz.assurance]`: the assurance level patient data requires + +Off by default. What it refuses and the `401` challenge it sends are described +in [Security](../security.md#assurance-level-and-the-natural-person-on-patient-data). + +| Key | Type | Default | Description | +|---|---|---|---| +| `claim` | string | `acr` | The token claim carrying the authentication context class; a dotted path reaches into a JSON object. | +| `levels` | table of string → `low` \| `substantial` \| `high` | empty | Maps each value your identity provider puts in `claim` to an eIDAS level of assurance. A value the table does not name carries no level. File-only: the keys are usually URIs. | +| `minimum` | `low` \| `substantial` \| `high` | unset | The level a patient-data request must carry. Unset refuses nothing. | + +```toml +[authz.assurance] +minimum = "substantial" + +[authz.assurance.levels] +"http://eidas.europa.eu/LoA/low" = "low" +"http://eidas.europa.eu/LoA/substantial" = "substantial" +"http://eidas.europa.eu/LoA/high" = "high" +``` + +These are the values FerroSMART writes into `acr`. Behind FerroSMART, set +the floor to substantial at least: the xShare Yellow Button that FerroBRIDGE +serves reads the patient's record with their own exchanged token, which +this gate holds to the floor +([Behind FerroSMART](../behind-ferrosmart.md#the-patients-own-token-through-ferrobridge)). + +Boot refuses a `minimum` with an empty `levels` table or with no value mapped at +or above it (every patient-data request would be refused), a blank `claim` +beside a declared table, and a `levels` value that is blank or carries +whitespace, a quote or a backslash, because the refusal names the accepted +values in one quoted, space-separated `acr_values` parameter (RFC 9470 §3). + +A Basic credential carries no level, so with `minimum` set every Basic user, +mapped to a person or not, is refused on patient data. While `minimum` is unset +and a Basic user is mapped in `[[authz.party_binding.basic_user]]`, boot logs a +`warn` naming those users. + +The access record carries the acting mode and the professional the caller +classification names; see [Audit trail](../ehds-logging.md#the-ehds-logging-elements-mapped). +The token's `fhirUser` classifies the caller, and its RFC 8693 `act` names who +acts for them. + +### `[authz.party_binding]` + +How a person is attributed. There is no switch: binding is how FerroEHR +attributes a person, and `enabled` is refused at boot. + +| Key | Type | Default | Description | +|---|---|---|---| +| `provider` | `{ issuer, id }` | **required** once `[auth]` admits a credential | The healthcare provider this deployment acts for, as an identifier issuer and id (in the Netherlands the URA). Every access record of a bound or provisional person and every version a person commits name it (EHDS Art. 13(4), Annex II 3.2(a)). | +| `namespace` | string | `demographic` | The `PARTY_REF.namespace` a bound party is written under, the value of the ITS-REST overview example (`committer.external_ref.namespace="demographic"`), held to the `OBJECT_REF.namespace` pattern `[a-zA-Z][a-zA-Z0-9_.:/&?=+-]*`. | +| `basic_user` | `[[authz.party_binding.basic_user]]` tables | `[]` | One per Basic user: `user`, `key_issuer` (the `identifier_issuer` of an `[auth.issuer..party]` table) and `key`, the binding key the user's `PERSON` carries. A Basic user with no table, a table naming no Basic user and a `key_issuer` no table names refuse the start. | +| `issuer` | `[[authz.party_binding.issuer]]` tables | `[]` | How the tokens of one issuer are read when a first login creates a provisional `PERSON`; see [Just-in-time creation](#just-in-time-creation). | +| `provisional_report_after` | duration | `"30d"` | The age past which `ferroehr party-binding check` reports a provisional `PERSON`. | + +```toml +[authz.party_binding] +provider = { issuer = "urn:oid:2.16.528.1.1007.3.3", id = "12345678" } + +[[authz.party_binding.basic_user]] +user = "clinician" +key_issuer = "urn:example:staff-login" +key = "3f2b0c1e-0000-4000-8000-000000000001" +``` + +#### The party mapping + +SCIM provisioning, just-in-time creation and the login binding read and +write the same demographic parties under one mapping. It names the +templates each party is valid against, the identifier selectors of the +binding key, `userName` and `externalId`, and where each SCIM attribute and +OpenID Connect claim goes. Names go in `PARTY.identities` and identifiers +in `PARTY.details` (RM demographic §Names and Addresses, §Party +Identification), and boot refuses a name mapped into `details` or an +identifier mapped into `identities`. No openEHR specification governs this +mapping: it is FerroEHR's own design, and its targets are RM demographic +paths. + +| Section | Keys | Description | +|---|---|---| +| `[[authz.party_binding.person.template]]` | `template_id`, `key`, `user_name`, `external_id`, `default` | One per template a professional's `PERSON` may use, so a migrated template can stay beside a new one. `key`, `user_name` and `external_id` are selectors, each `{ path, type }`: the path of the `ELEMENT` holding the `DV_IDENTIFIER` and its `type`. Every identifier can sit at one path (the repeated element of an identifier cluster), so two selectors at one path are told apart by `type`, and the key by its issuer, the `identifier_issuer` of an `[auth.issuer..party]` table. Exactly one table sets `default = true`: SCIM and just-in-time creation create new persons with it. | +| `[[authz.party_binding.person.attribute]]` | `scim`, `oidc`, `jit`, `name`, `path` | One per mapped value: a SCIM attribute path (the RFC 7644 `valuePath` form, `emails[type eq "work"].value`, and the FerroEHR extension `urn:ietf:params:scim:schemas:extension:ferrohealth:2.0:User:loginIdentifier` that feeds the binding key), an OpenID Connect claim, whether just-in-time creation writes it (`jit`, default `false`), whether it is the name the committer reads (`name`, at most one), and `path`, one path per template id. `id`, `schemas`, `meta`, `active`, `userName` and `externalId` are SCIM's own and are never mapped. | +| `[authz.party_binding.professional_role]` | `template_id` | The template of the professional `ROLE`, rooted at `ROLE`. A `PERSON` is a professional while it lists a `ROLE` of this template that names it as `performer`, is `complete` or `incomplete`, and whose `time_validity` holds today. | +| `[authz.party_binding.group]` | `template_id`, `external_id`, `display_name` | The template of a SCIM Group's `GROUP`, its `externalId` selector and the path of its `displayName`. | +| `[authz.party_binding.membership]` | `archetype_id` | The `PARTY_RELATIONSHIP` archetype of a group membership, as each membership's `archetype_node_id` carries it (the interface form of an ADL 2 id, `openEHR-DEMOGRAPHIC-PARTY_RELATIONSHIP.membership.v1`). SCIM serves `/Groups` when the group table names a `display_name` and this table is set. | +| `[authz.party_binding.patient]` | `template_id`, `identifier`, `name` | The template of a patient's `PERSON`, the subject of an EHR and the target of a representation: the path of the `ELEMENT` holding its identifiers (each a `DV_IDENTIFIER` of any type and issuer) and the path of its name. A `PERSON` written under this template is validated against it. | + +With no mapping key set, every section maps FerroEHR's [default +demographic definitions](default-demographic-definitions.md), which the +server stores as it boots when the definition store holds no definition of +their id. An empty configuration has this mapping: + +```toml +[[authz.party_binding.person.template]] +template_id = "openEHR-DEMOGRAPHIC-PERSON.healthcare_professional.v1.0.0" +default = true +key = { path = "/details[id2]/items[id3]", type = "login" } +user_name = { path = "/details[id2]/items[id3]", type = "scim_user_name" } +external_id = { path = "/details[id2]/items[id3]", type = "scim_external_id" } + +[[authz.party_binding.person.template]] +template_id = "openEHR-DEMOGRAPHIC-PERSON.patient.v3.0.0" +key = { path = "/details[id2]/items[id3]", type = "login" } +user_name = { path = "/details[id2]/items[id3]", type = "scim_user_name" } +external_id = { path = "/details[id2]/items[id3]", type = "scim_external_id" } + +[[authz.party_binding.person.attribute]] +scim = "name.formatted" +name = true +path = { "openEHR-DEMOGRAPHIC-PERSON.healthcare_professional.v1.0.0" = "/identities[id4]/details[id5]/items[id6]", "openEHR-DEMOGRAPHIC-PERSON.patient.v3.0.0" = "/identities[id6]/details[id7]/items[id8]" } + +[[authz.party_binding.person.attribute]] +scim = "name.givenName" +path = { "openEHR-DEMOGRAPHIC-PERSON.healthcare_professional.v1.0.0" = "/identities[id4]/details[id5]/items[id7]", "openEHR-DEMOGRAPHIC-PERSON.patient.v3.0.0" = "/identities[id6]/details[id7]/items[id9]" } + +[[authz.party_binding.person.attribute]] +scim = "name.familyName" +path = { "openEHR-DEMOGRAPHIC-PERSON.healthcare_professional.v1.0.0" = "/identities[id4]/details[id5]/items[id8]", "openEHR-DEMOGRAPHIC-PERSON.patient.v3.0.0" = "/identities[id6]/details[id7]/items[id10]" } + +[[authz.party_binding.person.attribute]] +scim = 'emails[type eq "work"].value' +path = { "openEHR-DEMOGRAPHIC-PERSON.healthcare_professional.v1.0.0" = "/contacts[id9]/addresses[id10]/details[id11]/items[id12]" } + +[authz.party_binding.professional_role] +template_id = "openEHR-DEMOGRAPHIC-ROLE.healthcare_professional.v1.0.0" + +[authz.party_binding.group] +template_id = "openEHR-DEMOGRAPHIC-GROUP.care_team.v1.0.0" +external_id = { path = "/details[id2]/items[id3]", type = "scim_external_id" } +display_name = "/identities[id4]/details[id5]/items[id6]" + +[authz.party_binding.membership] +archetype_id = "openEHR-DEMOGRAPHIC-PARTY_RELATIONSHIP.membership.v1" + +[authz.party_binding.patient] +template_id = "openEHR-DEMOGRAPHIC-PERSON.patient.v3.0.0" +identifier = "/details[id2]/items[id3]" +name = "/identities[id6]/details[id7]/items[id8]" +``` + +The template ids are the ADL 2 ids of the stored archetypes, and the +membership archetype is named in the interface form each membership's +`archetype_node_id` carries. The patient template is a person template too, +never the default: a patient's login binds their `PERSON` in it. A +representation needs no section: FerroEHR recognises it by its coded name, in +any archetype (see +[Representatives](../caller-facts.md#representatives)). The default +key is of the type `login`, so an `[auth.issuer..party]` table whose +`identifier_type` is `login` needs no mapping key. + +A section you set replaces that section's default whole: a deployment that +sets `[[authz.party_binding.person.template]]` maps its own attributes too. +A deployment with templates of its own sets the sections that name them and +stores its templates before boot (`ferroehr definitions load`); the server +stores nothing under its ids, and still stores the default definitions, +which no section of its mapping then names. + +A worked example over the default definitions, with the Microsoft Entra +object id as the binding key. It sets the person section, and every other +section keeps its default: + +```toml +[[authz.party_binding.person.template]] +template_id = "openEHR-DEMOGRAPHIC-PERSON.healthcare_professional.v1.0.0" +default = true +key = { path = "/details[id2]/items[id3]", type = "guid" } +user_name = { path = "/details[id2]/items[id3]", type = "scim_user_name" } +external_id = { path = "/details[id2]/items[id3]", type = "scim_external_id" } + +[[authz.party_binding.person.attribute]] +scim = "name.formatted" +oidc = "name" +jit = true +name = true +path = { "openEHR-DEMOGRAPHIC-PERSON.healthcare_professional.v1.0.0" = "/identities[id4]/details[id5]/items[id6]" } +``` + +With Microsoft Entra ID, map the object id to `externalId` (Entra's +matching) and to the binding-key attribute (the binding): two attributes, +two selectors. The key's party table's `identifier_type` is `guid`, so a +key differing only in case binds one login. + +Boot refuses, naming the key: no or two `default` tables; a selector path +that does not compile; two equal selectors; any selector under the Dutch +BSN namespace (OID `2.16.840.1.113883.2.4.6.3`); a key fed by an email +address, a phone number, `preferred_username`, `name`, `upn` or +`unique_name`; a template that is absent, rooted at another class or lacks +a mapped path; and a path whose type cannot carry its source. Deleting a template +the mapping names is refused with `409`. + +The parties the binding relies on are protected: a `PERSON` of a mapped +template carrying a selector identifier, its professional `ROLE`, a +representation (a `PARTY_RELATIONSHIP` of its own named +`openehr_access::represents`), and a `GROUP` of the group template. Only an +administrator (`authz.rbac.admin_role`) writes one through the demographic +API, including the creation of a party that carries a selector identifier; +a `write_representation` holder writes a representation for the providers +its grant names, and the patient a representation targets writes one on the +basis `HL7_RoleCode::DELEGATEE`. +The policy parties (a party holding a capability coded in +`openehr_access`, an acts-for relationship or an `openehr_access::client_id` client identifier) +are recognised by what they hold and take no key of this mapping; they are an administrator's to write and to read, +never a SCIM client's: see [Operational policy](../operational-policy.md#who-writes-and-reads-a-policy-party). +An administrator's version that leaves a protected identifier out is refused +with `422`. A present binding key is immutable (RFC 7643 §2.2): a version +that changes it is refused with `403`, and +[`POST /admin/party/binding-key`](../operations-admin-apis.md) is the one +change. Each selector value binds one live party: a commit that gives a +binding key, a `userName` (compared after RFC 8265 width mapping, lower case +and NFC), an `externalId` or a group `displayName` a second party is refused +with `409`. A deleted `PERSON` leaves its key as a tombstone that refuses +the login until an administrator binds the key again. + +#### Changing the mapping + +The side table is filled from the configured mapping and the party +versions. The first boot fills it and stores the mapping's digest, which +covers the templates, the selectors, the role, the group and the membership. +It leaves out the key issuers: the `identifier_issuer` of each +`[auth.issuer..party]` table. Each running replica holds +a lease it renews every 20 seconds, and the lease lists the key issuers the +replica derives keys for. + +**Adding or removing a key issuer needs no stop and no refill.** Each key +issuer is a key space with a state: + +| State | Its keys bind a login | What happens next | +|---|---|---| +| `pending` | No: the login is answered `503` with a `Retry-After` | Once every live replica names the issuer, a replica fills its keys from the party versions | +| `filling` | No: `503` with a `Retry-After` | The fill runs online in pages and the issuer turns `active` | +| `active` | Yes | A replica that starts without the issuer turns it `retiring` | +| `retiring` | No: the login is refused with `403 refused-unbound` | Once no live replica names it, its keys are deleted; once every live replica names it again, it is filled anew | + +So a rolling upgrade that adds an issuer serves every other issuer +throughout, and the new issuer's logins bind on every replica once the last +replica without it is replaced. A replica restarted without an issuer stops +that issuer's logins binding on every replica at once, so revoking an issuer +needs no downtime. A fill that finds two parties carrying one +key under the new issuer keeps it `pending`, logs both parties, and looks +again after five minutes; the other issuers keep binding. + +**A change to the templates, selectors, role, group or membership is a +stop-the-world step.** A replica whose mapping digest differs from the stored +one refuses to start, naming both digests: + +1. Stop every replica. With Helm, scale the deployment to zero first: a + rolling upgrade would start new replicas beside old ones. +2. Run `ferroehr party-binding refill` with the new configuration. It + refuses while a replica's lease was renewed within the last minute, and + refuses a store in which two parties carry one selector value, naming + both. +3. Start the replicas with the new mapping. A replica still holding the old + mapping refuses to start. + +#### How a login is looked up + +Every request of a person is looked up in the binding side table of the +party store, on the party database role, with no cache, so a change to a +party takes effect on the next request on every instance. The table holds +the binding key of each `PERSON` of a mapped template that performs a +professional `ROLE` (a `ROLE` of the mapped role template that its `roles` +list, that names it as `performer`, whose state is `complete` or +`incomplete` and whose `time_validity` holds today's date in UTC) or that +is the source of a representation. A key of type `guid` or +`uuid` is compared in lower case. The table is written in each party +commit's transaction and can be rebuilt from the party versions alone. + +The request is refused with `403` and the binding code in the problem body +when the login matches two parties (`refused-ambiguous`), when its party is +`inactive` (`refused-inactive`) or `abandoned` (`refused-abandoned`), when +its key belongs to a deleted party (`refused-deprovisioned`), when the token +carries no `sub` (`refused-key-claim-missing`), when the party lacks the +marker the caller's kind needs (`refused-wrong-marker`), when the groups a +token asserts cannot be read (`refused-groups-unavailable`), and when a +representative reaches a subject its party has no live +representation of, stored in the CDR for the provider the deployment acts +for and not written by the representative itself +(`refused-representation-unrecorded`). A party +store that cannot answer is answered `503`. + +A person whose login matches no party is refused with `403` and +`refused-unbound` on every request, reads and writes alike; only the public +endpoints outside the auth layer answer. The problem names the identifier +issuer to provision the person under, and the refusal of a token without +`sub` names that claim instead. No setting serves an unbound person +under a login-only committer, so provision every professional (through +[SCIM](config-scim.md#authscim) or the demographic API) before you add an issuer, or +let the issuer create a provisional `PERSON` at the first login +([just-in-time creation](#just-in-time-creation)). Each +refusal writes one `warn` line naming the issuer and the outcome, never the +claim value, and counts into the `binding_refusals` metric by `issuer` and +`outcome`. + +A representative reaches only the EHRs of a subject their `PERSON` holds a +live representation of, stored in the CDR for the provider +`[authz.party_binding.provider]` names and read from the store, never from +the token (EHDS Art. 4(2)). The access evaluator holds every request that +names an EHR to those EHRs, whatever the token's scopes cover, and refuses +any other with `403` `refused-not-represented`; a query must name one with +`ehr_id`, and an operation that names no EHR is refused the same way. +Templates stay readable. A professional's token whose only clinical scopes +are `patient/` is confined to its launch EHR, and its commits record the +professional, never `PARTY_SELF`. See +[Representatives](../caller-facts.md#representatives). + +#### Just-in-time creation + +Just-in-time creation lets a professional with no party work under their own +account at their first login, before SCIM or an administrator completes the +record. When a professional's login matches no party, and a +`create_at_login` grant in the CDR admits it, FerroEHR commits one `PERSON` +of the default template with lifecycle state `553|incomplete|`, which RM +common §Incomplete Content allows for "incomplete demographic details", and +its professional `ROLE` in the same demographic contribution, then serves the +request bound to it. The next request binds to that `PERSON` and creates +nothing. When a login creates a party is FerroEHR's own design: no openEHR +specification governs it. + +Which logins are created is operational policy, so it is CDR data and no +configuration key: an administrator writes a `ROLE` whose capability grants +`openehr_access::create_at_login`, naming the issuer and the admission +conditions, through the Demographic API. The grant is read on each first +login, so a change applies to the next one without a restart. The +[Operational policy](../policy-examples.md#just-in-time-admission) page +documents the grant and has a worked example. `[authz.grants] allowed` +must list `create_at_login`, which the default does not, or no such grant +can be written or honoured. + +The `[[authz.party_binding.issuer]]` table only says how an issuer's tokens +are read, and an issuer without one reads the defaults: + +| Key | Type | Default | Description | +|---|---|---|---| +| `issuer` | string | required | An issuer an `[auth.issuer..party]` table binds. | +| `user_name_claim` | string | `sub` | The claim the `userName` is read from. It must be one the issuer controls: an email address, a phone number, `preferred_username`, `name`, `upn` and `unique_name` refuse the start. | +| `idp_claim` | string | `idp` | The dotted claim path an `admit_idp` condition reads the identity provider from (the Microsoft Entra `idp` claim). | + +Creation also needs a default person template with a `user_name` selector, +`[authz.party_binding.professional_role]`, and an attribute that maps an +OpenID Connect name claim (`name`, `given_name`, `family_name`, +`middle_name` or `nickname`) to the default template. The default mapping +has them. When a grant admits a login and the mapping lacks one, the login +is not created and the server logs what is missing. + +```toml +[[authz.party_binding.issuer]] +issuer = "https://login.microsoftonline.com//v2.0" +user_name_claim = "oid" +``` + +What it writes is the attribution minimum: the binding key, the `userName` +and the name claims the token carries. Any other mapped attribute is written +only where its `[[authz.party_binding.person.attribute]]` sets `jit = true` +(GDPR Art. 25(2), data protection by default), and `externalId` is never +written, since RFC 7643 §3.1 leaves it to the provisioning client. The +version is committed with change type `249|creation|`, a description naming +just-in-time creation and the issuer, and the person's own committer: the +name, the login identifier and an `external_ref` naming the new `PERSON`. +FerroEHR reads every value from the access token only (RFC 9068 §2.2.2), so +the issuer must put the name claims in the access token. + +It runs only for a person or a delegated caller of the issuer, never for a +representative, a patient, a system or a `federation` caller, and never for a +login whose outcome is anything other than unbound: an ambiguous, inactive, +abandoned or deprovisioned party, a token without the key claim and a party +with the wrong marker are refused as before. A `PERSON` a SCIM client deleted +is never created again by a later login, whatever the identity provider still +issues. A login that no grant in force admits, or whose token carries no +mapped name claim, is refused with `403` and `refused-unbound`. + +Concurrent first requests of one login commit one `PERSON`: the binding key's +unique index refuses the second commit, and that request binds to the first +one's `PERSON`. A login whose `userName` another party already holds is +refused with `403` and binds nothing. Just-in-time creation only creates: it +never updates, deactivates or deletes a `PERSON`, so a later login with +changed claims changes nothing. + +A `PERSON` whose latest version is `incomplete` is provisional. The access +record of each of its requests carries `binding = provisional`, a demographic +read and an AQL query over `VERSION/lifecycle_state` show it, and +`ferroehr party-binding check` reports the provisional persons older than +`provisional_report_after` under `side_table.provisional`. What a provisional person may do is decided by +their SMART scopes and roles, as for anyone. A SCIM client whose +`binding_issuer` is the issuer's `identifier_issuer` completes the `PERSON`: +it finds it by `userName`, with a binding key equal to its own, writes the +`externalId` with a `PATCH`, and a complete `PUT` completes it. SCIM +`active = false` abandons it. + +The lawful basis for the attribution minimum (key, `userName`, name) is GDPR +Art. 6(1)(c): EHDS Art. 13(4) and the logging duties need the professional +identified. An operator who opts a contact attribute in with `jit = true` +names its own basis, Art. 6(1)(b) or (f). Because the data come from the +identity provider and not from the person, tell the professionals what Art. 14 +asks: what is copied, from which source, and why. On a realm or tenant that +creates persons, make the name attributes administrator-controlled, as the key +is; [Enterprise identity providers](../identity-providers.md#just-in-time-creation) +shows the settings per identity provider. + +### Imports and system clients + +The systems whose wrapped committers an import may carry are no key: a +`creating_system` element of the importer's import grant names each one +([What the grants decide](../operational-policy.md#what-the-grants-decide)). + +The system clients are not configuration. An OAuth client-credentials client +is granted what it may commit, import or export in the CDR, as an `ACTOR` +carrying its `client_id` that acts for a provider and performs a `ROLE` whose +capabilities grant the operations; see +[What a system client may do](../operational-policy.md#what-a-system-client-may-do). + +### Federation agreements + +A federation agreement is CDR data, not a configuration key: a grant of +`federated_person_access` or `federated_organisation_access` on the partner's +party, read on every request and judged when it is written. The configuration +keeps what the agreements are judged against: the `federation` issuers, their +`[auth.issuer..federation]` tables, `[authz.grants] allowed` (which must name both +codes before an agreement can be written). The period a `chained` agreement +is held to is the access log retention of the controller's access policy +(`ACCESS_POLICY.log_retention`). The model, the codes and the rules are on +[Operational policy](../operational-policy.md#federation-agreements). + +### `[authz.grants]` + +| Key | Type | Default | Description | +|---|---|---|---| +| `allowed` | list of operation codes | `["commit_composition"]` | The operations of the `openehr_access` terminology the policy grants may grant. A `ROLE` committed with a capability that codes an operation this list does not name is refused with `403`, and one already stored is never honoured, so a compromised administrator account grants no more than you allow. Allow `compose_for` to let a professional name another `PERSON` of the same provider as the composer of what they commit ([Who is the committer](../security/committer.md#the-composer-of-a-professionals-composition)). An empty list lets the party store grant nothing; an unknown code refuses the start. Environment: `FERROEHR__AUTHZ__GRANTS__ALLOWED`, comma-separated. The codes and how a request reads its grants are on [Operational policy](../operational-policy.md#how-a-request-reads-its-grants). | + +### `[authz.rbac]` + +| Key | Type | Default | Description | +|---|---|---|---| +| `enabled` | bool | `true` | The coarse role gate (active when authentication is enabled). Off, every authenticated caller may use every enabled surface, reported as the `rbac_off` deployment gap. `ehr_access_default` and `admin_role` apply either way. | +| `admin_role` | string | `ADMIN` | Role required for admin-class operations. A blank value is a boot error. | +| `readonly_role` | string | `READONLY` | Role marking a principal read-only: refused on every write operation (create/update/delete/upload), even alongside granting roles. Reads and AQL queries are still allowed. | +| `role_issuers` | list of string | `[]` | The issuers whose role claims may grant `admin_role`. A token of any other issuer never holds it, a Basic user keeps the roles its own table grants, and a `hold_roles` policy grant never gives one. A `federation` issuer refuses the start. Empty, no token grants them. | +| `ehr_access_default` | enum{open,restricted} | `open` | What an EHR carrying no `ACCESS_CONTROL_SETTINGS` admits. `restricted` is object-level default-deny: only `admin_role` reaches a setting-less EHR, so an operator can still author the settings that open it. It is enforced whether `enabled` is on or off. With `[auth] enabled = false` nothing could enforce `restricted`, so that combination is a boot error. See [Security](../access-control.md#per-ehr-access-control-ehr_access). | + +Reading one subject's access log, acting as an EHDS Art. 10 access service, +and importing an EHR or an extract have no key here: each is a grant in the +CDR (`read_subject_audit`, `access_service`, `import_ehr` and +`import_ehr_extract`), +under `[authz.grants] allowed`. The keys that named a role for them before +5.7.1 are unknown keys, and the server refuses to start with one +([What the grants decide](../operational-policy.md#what-the-grants-decide)). + +> [!NOTE] +> The management surface is **not** configured under `[authz.rbac]`. +> [`[management.endpoints]`](config-auth.md#management) owns it, one level per endpoint, with +> no global default beside it: an endpoint you do not name is `off` and is not +> mounted. Only the `admin_only` level consults `authz.rbac.admin_role`. diff --git a/website/book/src/installation/config-cli.md b/website/book/src/installation/config-cli.md index 55b5494b90..009c705682 100644 --- a/website/book/src/installation/config-cli.md +++ b/website/book/src/installation/config-cli.md @@ -10,6 +10,9 @@ environment-name grammar, and file discovery are on the ## The command line +Every command with every option, as `--help` prints it, is on the generated +[Command-line reference](../reference/cli.md). This section explains them. + Two flags are global: they apply to the server and to every subcommand: | Flag | Description | @@ -153,7 +156,7 @@ Kubernetes Job, an init container, a CI/CD stage), then boot the server with all. `verify` still reads all five `_sqlx_migrations` bookkeeping tables, which no least-privilege role can do, so point `[database] migrate_url` at the credential that prepares the schema. See -[Operations](../operations.md#which-credential-prepares-the-schema). +[Operations](../database-operations.md#which-credential-prepares-the-schema). ### `ferroehr definitions load` @@ -171,7 +174,7 @@ the same text is left alone, so the step runs at every start; one stored under the same id with other text is refused, because a stored definition never changes and a changed one takes a new version in its id. -A deployment whose [party mapping](config-auth.md#the-party-mapping) names +A deployment whose [party mapping](config-authz.md#the-party-mapping) names templates of its own runs it first, so the mapping finds them when the server boots: as a one-shot compose service, a Helm init container or a setup step. The [default demographic definitions](default-demographic-definitions.md), @@ -185,13 +188,13 @@ ferroehr party-binding refill # rebuild the party binding side table under the ``` Rebuilds the binding side table from the party versions under the -configured [party mapping](config-auth.md#the-party-mapping) and stores the +configured [party mapping](config-authz.md#the-party-mapping) and stores the mapping's digest. Run it with every replica stopped after a change to the templates, selectors, role, group or membership: it refuses while a replica holds a live lease, and refuses a store in which two parties carry one selector value, naming both. A key issuer added or removed needs no refill: the running replicas fill and retire its keys themselves -([Changing the mapping](config-auth.md#changing-the-mapping)). +([Changing the mapping](config-authz.md#changing-the-mapping)). ### `ferroehr party-binding check` @@ -202,7 +205,7 @@ ferroehr party-binding check [--admin ]... [--admin-key ``` The pre-flight of a migration to party binding. It reads the party versions -under the configured [party mapping](config-auth.md#the-party-mapping) and +under the configured [party mapping](config-authz.md#the-party-mapping) and writes nothing: the side-table categories are read from a refill inside a transaction that is rolled back, so it runs before any boot fill and beside a running server. It connects with the configured database credentials and @@ -217,7 +220,7 @@ The report is a JSON document on stdout: - `inactive` and `abandoned`: the key-bearing `PERSON`s whose head is `800|inactive|` or `801|abandoned|`; - `side_table.provisional`: the provisional `PERSON`s that - [just-in-time creation](config-auth.md#just-in-time-creation) created more + [just-in-time creation](config-authz.md#just-in-time-creation) created more than `[authz.party_binding] provisional_report_after` days ago (default 30) and that SCIM or an administrator has not completed, by container id and creation time, oldest first, with no name or other personal data; @@ -289,7 +292,7 @@ performs whose capability grants the operation, with one scope element per `--element`, whose value is a `DV_TEXT`, and one `provider` element per `--provider-issuer` and the `--provider-id` in the same position, whose value is a `DV_IDENTIFIER` with that issuer and id, as a `write_care_relationship` -grant names the providers it writes for. It is the first grant of a new deployment, typically the +grant names the providers it writes for. It is the first grant of a new deployment, usually the `scim_provision` of the client that provisions the administrators, since no administrator can log in before their `PERSON` exists; every later grant is an administrator's write through the Demographic API. The commits take the @@ -318,7 +321,7 @@ ferroehr access-log import --input ``` The access log's integrity and transfer, described on the -[audit page](../audit.md#seals-checkpoints-and-the-transfer-of-a-log). `checkpoint` +[audit page](../audit-integrity.md#seals-checkpoints-and-the-transfer-of-a-log). `checkpoint` and `export` need the keyring's OpenPGP key (`record.signing.mode = "pgp"`). `verify` prints each finding and exits 1 when the log does not verify, so a scheduled job can alert on it; pass `--checkpoint` a checkpoint you kept @@ -335,7 +338,7 @@ ferroehr audit-chain verify [--seal ] # verify against the newest or a ke ``` The system records are the records outside the access log, described on the -[audit page](../audit.md#seals-checkpoints-and-the-transfer-of-a-log). Both need +[audit page](../audit-integrity.md#seals-checkpoints-and-the-transfer-of-a-log). Both need the keyring's OpenPGP key (`record.signing.mode = "pgp"`) to seal or to verify a seal. `verify` prints each finding and exits 1 when the records do not verify; pass `--seal` a seal you kept outside this system to verify diff --git a/website/book/src/installation/config-integrations.md b/website/book/src/installation/config-integrations.md index d8ede5a63f..f95a5312fb 100644 --- a/website/book/src/installation/config-integrations.md +++ b/website/book/src/installation/config-integrations.md @@ -110,7 +110,7 @@ contribution moves the merged patient's pseudonym onto the survivor's `PERSON`, and both EHRs inherit the survivor's care relationships and representatives from the next request. Writing the element needs the `write_care_relationship` grant or an administrator, as a care relationship -does ([The pseudonymisation boundary](../security.md#the-subject-link-in-the-party-domain) +does ([The pseudonymisation boundary](../pseudonymisation.md#the-subject-link-in-the-party-domain) names what this changes). ### The patient's EHRs @@ -473,18 +473,11 @@ read back from it. The server takes S3 credentials from this table only. It reads no `AWS_*` environment variable, no profile file and no instance metadata. -Since 6.0.0 the S3 keys live in their own table. A configuration from an -earlier release that sets `url`, `bucket`, `region`, `access_key_id` or -`secret_access_key` directly under `[record.multimedia]` is refused at boot as -an unknown key; move those keys to `[record.multimedia.s3]`, and their -environment variables from `FERROEHR__RECORD__MULTIMEDIA__` to -`FERROEHR__RECORD__MULTIMEDIA__S3__`. - An enabled integration whose `url` is set but blank, not an absolute URL, or carries a scheme other than `http`/`https` is a **boot error**. That case is easy to reach by accident (an unset Compose variable expanding to nothing, or -an empty Helm value) and used to boot cleanly and then fail on the first -multimedia commit, so it is refused where an operator can still act on it. +an empty Helm value), so it is refused at boot, where an operator can still +act on it. > [!WARNING] > Offloaded blobs are PHI. The bucket must be private and encrypted, and reached diff --git a/website/book/src/installation/config-privacy.md b/website/book/src/installation/config-privacy.md index d641e8d710..c74ab35298 100644 --- a/website/book/src/installation/config-privacy.md +++ b/website/book/src/installation/config-privacy.md @@ -30,7 +30,7 @@ Both rules run on the write path, before anything is stored. A refusal is `422 Unprocessable Entity` with one `errors[]` entry per finding (sent when the request carries `Prefer: return=representation`), each naming the RM path and the rule that matched. **A refusal never echoes the -offending value** — it would otherwise travel into the response body, the +offending value**: it would otherwise travel into the response body, the access log and the traces, which is the leak the rule exists to prevent. ```toml @@ -78,7 +78,7 @@ namespace. Every value that arrives from elsewhere, a client writing which is why declaring the namespace is the deployment's act. **Empty is the default, and it leaves the rule out of force.** A pseudonym -namespace is a deployment fact — which service mints the tokens — and there is +namespace is a deployment fact (which service mints the tokens) and there is no name a server could invent for an operator. Declaring one is the same act as turning the rule on. An EHR with no subject reference at all is unaffected either way: that is the default `EHR_STATUS` the openEHR REST API describes, @@ -98,8 +98,8 @@ re-pseudonymising. ### Identified parties -A party proxy inside clinical content — the composer, participations, the -health care facility and the feeder-audit party slots — is governed by which +A party proxy inside clinical content (the composer, participations, the +health care facility and the feeder-audit party slots) is governed by which class it is: | | `name` | `identifiers` | @@ -157,7 +157,7 @@ which is announced at boot with a warning naming what it permits. Cross-domain **cohort queries**: select a population in the demographic domain, resolve it to the EHRs whose `EHR_STATUS` subject names it, and run AQL over -exactly those EHRs. A FerroEHR extension — no openEHR spec governs it. The wire contract and a +exactly those EHRs. A FerroEHR extension; no openEHR spec governs it. The wire contract and a worked example are in [Querying with AQL](../querying-aql.md#cohort-queries-across-the-pseudonymisation-boundary). **Off until a predicate is bound.** Which demographic leaf may be selected on is @@ -186,8 +186,8 @@ city = { archetype = "openEHR-DEMOGRAPHIC-ADDRESS.address.v1", node = "at0012", ### The allow-list -Exactly five keys are bindable — `city`, `postcode_area`, `sex`, `age_band` and -`organisation` — and an unknown key is a **boot error**. Each binding carries +Exactly five keys are bindable (`city`, `postcode_area`, `sex`, `age_band` and +`organisation`), and an unknown key is a **boot error**. Each binding carries three fields: | Field | Description | @@ -196,7 +196,7 @@ three fields: | `node` | The ELEMENT's `archetype_node_id` at-code, e.g. `at0012`. | | `kind` | How a caller's value is matched: `text` (exact, against `value/value`), `text_prefix` (prefix, `LIKE`-escaped), `coded` (exact, against `value/defining_code/code_string`), or `birth_date` (an inclusive age band in whole years, `40-49`). | -`age_band` must be bound `birth_date`, and no other key may be — both halves are +`age_band` must be bound `birth_date`, and no other key may be: both halves are boot errors, because a mismatch would bind a predicate that matches nothing while reporting an empty cohort. diff --git a/website/book/src/installation/config-scim.md b/website/book/src/installation/config-scim.md new file mode 100644 index 0000000000..08cf720cc2 --- /dev/null +++ b/website/book/src/installation/config-scim.md @@ -0,0 +1,389 @@ +# SCIM provisioning + +`[auth.scim]`: provisioning users and care teams from your identity provider. + + + +## `[auth.scim]` + +FerroEHR is a SCIM 2.0 service provider (RFC 7644) at `/scim/v2/`, the +endpoint an identity provider provisions each professional through. It is off +by default. + +| Key | Type | Default | Description | +|---|---|---|---| +| `filter_max_results` | integer | `100` | The most resources one list response returns, which `ServiceProviderConfig` declares as `filter.maxResults`. At least 1. | +| `max_deactivations` | integer | `100` | The most Users one client deactivates or deletes per window. Past it, a deactivation or deletion is **429** with `Retry-After` and logged at `error`. The count is kept in the database, so every replica shares one bound. At least 1. | +| `deactivation_window` | duration | `"1h"` | The length of that window. At least `"1min"`. | +| `contact_erasure_delay` | duration | `"0s"` | How long after a User's deletion the contacts of every version of its `PERSON` are erased (GDPR Art. 17). `"0s"` erases them in the deletion itself; at most `"30d"`. | +| `max_group_members` | integer | `5000` | The most members one Group holds. An add past it is **400** `invalidValue`. A membership change versions only the member's `PERSON`, so its cost does not grow with the Group. At least 1. | + +Who provisions is CDR data, read on every request: a provisioning client is +an OAuth client-credentials client of your own authorization server whose +`ACTOR` holds a `scim_provision` grant in force. The grant's +`binding_issuer` is the identifier issuer of the binding keys the client +provisions: the `identifier_issuer` of an `[auth.issuer..party]` table +your professionals log in through. Its `token_scope` is the scope a token of the client +must hold; SMART on openEHR defines none for SCIM, so the value is yours to +choose. Each User belongs to the one client whose `binding_issuer` issues its +key, so no two clients' grants name one. `[authz.grants] allowed` must admit +`scim_provision`. The first such grant is written with +[`ferroehr party-binding grant`](../operational-policy.md#the-first-grant), +since no administrator can log in before the persons it provisions exist; +[Operational policy](../operational-policy.md#what-the-grants-decide) has the +grant's terms. + +Every `meta.location` and discovery document names the resource by its URI +(RFC 7643 §3.1), under `/scim/v2` with +[`server.public_base_url`](config-server.md#public_base_url-the-one-public-url) +and `server.base_path`, so the table needs that key. + +The table's presence turns the endpoint on; it has no `enabled` key, and +setting one refuses the start. The start is refused when the table is present +without `server.public_base_url`, and when the [party mapping](config-authz.md#authzparty_binding) +lacks what a User is written with: a default person template with a +`user_name` selector, and `[authz.party_binding.professional_role]`. + +```toml +[server] +public_base_url = "https://cdr.example.com" + +[auth.scim] + +[authz.grants] +allowed = ["commit_composition", "scim_provision"] +``` + +`/scim/v2/ServiceProviderConfig` answers without a token, so a client can read +the authentication scheme before it holds one. Every other path needs a +bearer token of a client that acts for nobody and holds a `scim_provision` +grant in force: + +- no token, or one that does not verify, is **401** with + `WWW-Authenticate: Bearer`; +- a person's token, a client with no grant in force, a grant whose + `binding_issuer` is not the `identifier_issuer` of an `[auth.issuer..party]` + table, or another client's grant names too, and a token without the grant's `token_scope` are **403**, the + last with `WWW-Authenticate: Bearer error="insufficient_scope"` (RFC 6750 + §3.1). + +Every refusal is an RFC 7644 §3.12 `Error` message in `application/scim+json`. +The client's requests count against +[`[server.caller_rate]`](config-server.md) like any caller's, so each +replica gives the client an allowance of its own, and past it a request is +**429** with `Retry-After`. `/scim/v2/Schemas` serves the core User schema +reduced to `userName`, `active` and the SCIM attributes +`[[authz.party_binding.person.attribute]]` maps, and FerroEHR's extension +`urn:ietf:params:scim:schemas:extension:ferrohealth:2.0:User` with +`loginIdentifier`, the attribute that feeds the binding key. `/ResourceTypes` +lists the `User` type at `/Users`, and the `Group` type at `/Groups` with +FerroEHR's Group extension +`urn:ietf:params:scim:schemas:extension:ferrohealth:2.0:Group` and its +immutable boolean `careTeam` when Groups are served. + +The two extension URNs are a deliberate deviation from RFC 7643. They sit +under `urn:ietf:params:scim:schemas:extension:`, the sub-namespace RFC 7643 +§10.2 and RFC 3553 reserve for names IANA assigns, and neither name is in the +IANA "SCIM Schema URIs" registry (RFC 7643 §10.3). The reason is Microsoft +Entra ID: its provisioning client sends a custom attribute only under a name +of the form +`urn:ietf:params:scim:schemas:extension:CustomExtensionName:2.0:User:CustomAttribute` +("For SCIM applications, the attribute name must follow the pattern shown in +the example", *Customize Microsoft Entra attribute mappings*, vendored at +`docs/specs/microsoft-entra/docs/identity/app-provisioning/customize-application-attributes.md` +line 148). A schema id outside that namespace, which RFC 7643 §3 would allow, +leaves an Entra non-gallery application unable to send `loginIdentifier`, so +it could not provision anyone. The binding key fits no registered attribute: +`userName` is mutable, `externalId` is the client's own identifier for the +resource (RFC 7643 §3.1), and the Enterprise User extension (§4.3) carries no +login subject. The two URNs are the provisioning contract of the FerroHEALTH +products, fixed in the same way as the `/scim/v2` base path, and a client +writes them exactly as `/Schemas` lists them. + +### Users + +A User is a `PERSON` of the default person template performing the +professional `ROLE`: SCIM (RFC 7643, RFC 7644) provisions a workforce. A +patient needs no provisioning, since their own token's login binds their +`PERSON`. A representation is a `PARTY_RELATIONSHIP` of its own, written by +the patient, an administrator or a `write_representation` holder +(Regulation (EU) 2025/327 Art. 4(2)), and a User version that holds one in +its relationships is refused `422`. This is FerroEHR's own design. The client serves these operations (RFC 7644 §3): + +- `POST /scim/v2/Users` creates the `PERSON` and its `ROLE` in one demographic + CONTRIBUTION, under the client as committer, and answers **201** with the + User, its `Location` and its `ETag`. The body carries `userName` and the + binding key in `loginIdentifier`; `externalId` and every mapped attribute + are optional. A version that fits its template in full is `complete`, and + one that fits only with every lower limit at zero is `incomplete`, which the + User's `lifecycleState` and `missingPaths` name. A User created with + `active = false` is **400** `invalidValue`. +- `GET /scim/v2/Users/{id}` answers the User with its `ETag`, the weak tag of + its version, and **304** to an `If-None-Match` naming that version. +- `GET /scim/v2/Users` answers a `ListResponse`, an empty one with **200** + when nothing matches. `filter` takes `eq` and `and` over `userName`, + `externalId` and `id`; names and operators are compared in any case, and + anything else is **400** `invalidFilter`. `startIndex` and `count` page the + result, at most `max_results` at a time. + +The User's `userName`, `externalId` and binding key are `DV_IDENTIFIER`s at +their selectors, issued by the client's `binding_issuer`. A client sees only +its own Users, the ones whose key its `binding_issuer` issues: every other id +is **404** and absent from every list, as is a `PERSON` without a live +professional `ROLE`. The `userName` index spans every client, so a **409** +`uniqueness` tells one client that a `userName` exists under another; +`externalId` is unique within one client. Every SCIM request is an access +record of the client, with the `PERSON` as its object. + +A User is changed and removed through these operations: + +- `PUT /scim/v2/Users/{id}` replaces the User (RFC 7644 §3.5.1). A mapped + attribute the body leaves out is cleared; the binding key and `externalId` + are kept, and a left-out `active` keeps the lifecycle state. +- `PATCH /scim/v2/Users/{id}` applies the RFC 7644 §3.5.2 operations, value + paths and a `replace` without `path` included, and commits the result as + one version. The operation is read in any case, as the Entra ID client + sends `Replace`. +- `DELETE /scim/v2/Users/{id}` logically deletes the `PERSON` and its + professional `ROLE` in one demographic CONTRIBUTION and answers **204**. + Every later request on the id is **404**, the User leaves every list, and a + new User may take its `userName`. The binding key stays behind as a + tombstone: a login on it is refused as deprovisioned until the owning + client creates a User with it again. + +Each write answers with the User and its new `ETag`. An `If-Match` naming +another version is **412**, a changed binding key is **400** `mutability`, and +a write without `If-Match` is accepted (RFC 7644 §3.14 makes entity tags a +MAY). `active` drives the lifecycle state of the `PERSON` (RM common +§Version Lifecycle): + +| Current state | `active` in the request | Result | +|---|---|---| +| `complete` or `incomplete` | `true` or left out | `complete` when the template holds in full, else `incomplete` | +| `complete` | `false` | `inactive` | +| `incomplete` | `false` | `abandoned` | +| `inactive` | `true` | `complete`, or `incomplete` when the template does not hold | +| `abandoned` | `true` | `incomplete`, then `complete` in a second version when the template holds | +| `inactive` or `abandoned` | `false` or left out, with a change | **400** `invalidValue`: reactivate the User first | +| `inactive` or `abandoned` | `false` or left out, without a change | **200**, no new version | + +An inactive or abandoned User is still read and found by a filter, so its +client can reactivate it. When the second version of an `abandoned` User +fails, the User stays `incomplete` and the same request completes it. + +#### Roles + +A User's `roles` (RFC 7643 §4.1.2) are the roles the access policy's +[controller rules](../access-policy.md#controller-rules) name. Each +value is one `ROLE` the User's `PERSON` performs, of the professional role +template, whose `name` is the value coded in the terminology the client's +`scim_provision` grant names, and whose `time_validity` starts on the day it +is added. The grant states which roles the client may hand out: + +| Element | Value | +|---|---| +| `role_terminology` | The terminology id the client's role values are coded in, exactly one | +| `role` | A role code the client may assign, one element per code | + +A request whose `roles` names a code the grant does not list, or any role +when the grant names no `role_terminology`, is **403** and changes nothing. +A `POST`, `PUT` or `PATCH` makes the User hold exactly the roles its result +lists: a new value commits a new `ROLE`, and a removed one ends its `ROLE` +the day before (its `time_validity` gains the date of the removal as its +exclusive end) and drops it from the `PERSON`'s `roles`. The change decides +the next request on the replica that took it, and on every other replica +once the commit's notification arrives, with no added transaction. A token's +role claims never drive a controller rule. These `ROLE`s carry no +capability, so a SCIM client writes them, and an administrator alone grants +a capability. RFC 7643 sets no vocabulary for `roles` and RFC 7644 §2 leaves +the authorization model out: the mapping is FerroEHR's own design. + +The versions of a deleted User are kept for the record-keeping duties that +need the professional's identification (GDPR Art. 6(1)(c), laid down in law +as Art. 6(3) requires: in the Netherlands BW 7:454(3), twenty years, and the +logging duty of the Besluit elektronische gegevensverwerking door +zorgaanbieders). Outside the Netherlands, name your national retention +provision. Enable the identity provider's protection against accidental +deletions beside `max_deactivations`. + +Only the attribution minimum waits for that horizon: the name, the binding key +and the identifiers, `userName` and `externalId` among them. The contacts +serve no attribution, so FerroEHR erases them (GDPR Art. 5(1)(e)): with +`auth.scim.contact_erasure_delay = 0` the deletion removes the `contacts` of every +version of the `PERSON` in the same transaction, and with a period a sweep +that runs every minute removes them once the period has passed. The sweep +reaches every deleted `PERSON` whose binding key the `binding_issuer` of a +`scim_provision` grant issues, one that has ended included, +an administrator's demographic `DELETE` included. Each version keeps its uid, +audit and contribution, and its node rows are derived again from the erased +body. A server signature on such a version is removed, because it was taken +over the content the erasure changed. Each erasure is an access record, a +delete of `party:#contacts`. A login on the key is still refused as +deprovisioned. + +### Groups + +When `[authz.party_binding.group]` names a `display_name` and +`[authz.party_binding.membership]` is set, `/scim/v2/Groups` is served beside +`/Users`, and `/scim/v2/ResourceTypes` lists the Group. A Group is a +demographic `GROUP` of the group template: + +- its `displayName` is the `GROUP`'s `PARTY_IDENTITY`, unique across the live + Groups after case folding, so a duplicate is **409** `uniqueness`; +- its `externalId` is a `DV_IDENTIFIER` at the `external_id` selector under + the client's group issuer: the `group_identifier_issuer` of the + `[auth.issuer..party]` table whose `identifier_issuer` is the client's + `binding_issuer`, so the group claim of that issuer's tokens matches it. + When that table sets none, the group issuer is the `binding_issuer` with + `/groups` appended (`urn:example:login` gives `urn:example:login/groups`), + with any trailing `/` of the `binding_issuer` dropped first. A deployment + whose tokens assert groups sets `group_claim` and a + `group_identifier_issuer` in the table, and that value is the group issuer; +- each member holds one inline `PARTY_RELATIONSHIP` of the membership + archetype, with its `PERSON` as `source` and the `GROUP` as `target`, + stored in the member's own version (RM demographic §Party Relationships). + No `ROLE` is created for a Group, and a `PERSON` in no Group has + `relationships` Void. +- its `careTeam`, in FerroEHR's Group extension, says whether it is a care + team: set at creation, `false` when left out, and never changed (**400** + `mutability`). A care team is served with `careTeam = true` and the + extension in its `schemas`; any other Group is served without either. A + care team's `GROUP` is named by the coded `care_team` and each membership + by the coded `member_of` of `openehr_access` (RM demographic `PARTY.type()` is the `name`), so + its members are in the care of the patients under the team's care. + Creating one and changing its members needs the client's + `write_care_relationship` grant beside `scim_provision`, and is **403** + without it ([Care teams provisioned over SCIM](../caller-facts.md#care-teams-provisioned-over-scim)). + The group template and the membership archetype must admit a + `DV_CODED_TEXT` name, as the default definitions do. + +A Group belongs to the client that created it; every other client gets +**404**. A member is a User of the same client: a member naming another +client's User, an unknown id or a Group (nested Groups are not supported) is +**400** `invalidValue`. What a Group allows stays with the token's scopes and +roles; the access record lists the Groups the token names that the person +belongs to, and a Group in `inactive` or `abandoned` lists no member. + +- `POST /scim/v2/Groups` creates the `GROUP` with its members, if any, and + answers **201** with the Group, its `Location` and `ETag`. +- `GET /scim/v2/Groups/{id}` and `GET /scim/v2/Groups` filter with `eq` and + `and` over `displayName`, `externalId` and `id`, and + `excludedAttributes=members` leaves the members out. Each member is served + with its `value`, `$ref` and `type`. +- `PATCH /scim/v2/Groups/{id}` answers **204** with the new `ETag` (RFC 7644 + §3.5.2). `add` of `members` adds the listed members; `remove` with the + filter `members[value eq ""]` removes that member, and `remove` of + `members` with neither a filter nor a value list removes them all. +- `PUT /scim/v2/Groups/{id}` replaces the `displayName` and the members, + keeps a left-out `externalId`, and answers **200** with the Group. +- `DELETE /scim/v2/Groups/{id}` logically deletes the `GROUP` with its + memberships, and every later request on the id is **404**. + +**Entra compatibility deviation.** A `remove` of `members` that carries a +`value` list removes only the listed members, the request Microsoft Entra ID +sends. RFC 7644 §3.5.2.2 removes "the attribute and all values" when no +filter is specified; FerroEHR follows Entra only when the `value` list is +present. + +A membership change is a new version of each member's `PERSON` it touches, +in one CONTRIBUTION, and the `GROUP` gets no version; a change costs the same +whatever the Group's size. The Group's `ETag` is its `GROUP` version with a +membership revision that moves with every membership change, so it changes +whenever its members do (RFC 7644 §3.14). The member User's `ETag` changes +too, since its `PERSON` holds the membership (RFC 7643 §4.1.2); its body does +not, because the User serves no `groups` attribute. Deleting a User deletes +the memberships its `PERSON` holds with it. Deleting a Group drops the +membership of each active member in the CONTRIBUTION that deletes the +`GROUP`. A `GROUP` an administrator set `inactive` or `abandoned` keeps its +version, since the version lifecycle draws no update of either state, and a +SCIM write to such a Group is **400** `invalidValue`. + +**Deactivated Users leave their Groups.** The version lifecycle draws no +update of an `inactive` or `abandoned` `PERSON` (RM common master06 §Version +Lifecycle), so such a `PERSON` cannot take a membership change, and an +inactive `PERSON` binds to nothing. Setting a User's `active` to `false` +therefore drops its memberships in the same version, and each Group's +`ETag` changes. A membership of a care-team Group stays, as does every other +care relationship, since SCIM never changes one ([Deprovisioning a team +member](../caller-facts.md#deprovisioning-a-team-member)). Microsoft Entra ID often disables a user and then removes it +from its groups; the later `remove` finds nothing to remove and answers +**204**. An `add` naming an inactive or abandoned User is **400** +`invalidValue` ("reactivate the User first"). A reactivated User belongs to +no plain Group until its client adds it again. + +### Provision from Microsoft Entra ID + +Microsoft Entra ID provisions through a non-gallery enterprise application. +FerroEHR validates the access token your own authorization server issues to +it, so the steps split between the two. + +1. **Map the person template.** The default + [party mapping](config-authz.md#the-party-mapping) maps `userName`, `externalId`, the + formatted, given and family name and the work email Entra sends. Set the + person section only to map more, or to key the binding on the object id + as the worked example there does. + + A value path such as `emails[type eq "work"].value` serves the value and + its `type`. FerroEHR holds one value per `type` and no preference among + them, so `/scim/v2/Schemas` declares `primary` read-only and the `primary` + Entra sends is ignored (RFC 7644 §3.3). +2. **Grant the client.** Grant its client `scim_provision`, with `ferroehr + party-binding grant` or as an administrator through the Demographic API: + the `--issuer` is your authorization server, the `binding_issuer` element the `identifier_issuer` of the + `[auth.issuer..party]` your professionals log in through, and the `token_scope` + element the scope its token holds. Set `server.public_base_url` to the URL + Entra reaches. In the Helm chart, a `config.auth.scim` value also adds the + `/scim/v2` path to the Ingress. `ferroehr config check` refuses a mapping + the endpoint cannot serve. +3. **Federate Entra's credential at your authorization server.** Entra's + Workload Identity Federation presents a signed assertion, which your + authorization server exchanges for a client-credentials access token + (RFC 7523 §2.2). These checks are your authorization server's, not + FerroEHR's, so verify each one there, as Microsoft's "Workload Identity + Federation for SCIM Provisioning" guide requires: + - [ ] `iss` is pinned to your full tenant issuer, + `https://login.microsoftonline.com//v2.0`, and the assertion + verifies against that tenant's key set. + - [ ] `aud` is pinned to `api://`, with one + workload-identity application per FerroEHR deployment. + - [ ] `azp` is pinned to the application id of Microsoft's provisioning + service. + - [ ] `uti` is cached for the lifetime of the assertion, and an assertion + whose `uti` was seen before is refused as a replay. + - [ ] The access token it issues holds the grant's `token_scope`, names the + client in `client_id`, and lives between 1 and 6 hours, the range + Microsoft's guide asks for. + + The assertion's `sub` is the object id of a Microsoft application that + every integration in the tenant shares, never your `client_id`, so it does + not meet RFC 7523 §3 item 2.B. Accepting it is a deviation of your + authorization server; record it there. Leaving Entra's **Secret Token** + blank, so that Entra uses its own token, is not supported: Microsoft + reserves it for testing, and every non-gallery application in the tenant + receives a token with the same `iss` and `aud` (RFC 9700 §2.3). A + long-lived bearer token is not supported either. +4. **Point Entra at FerroEHR.** Set the **Tenant URL** to + `/scim/v2` and run **Test Connection**. Entra queries + `/Users` with `filter=externalId eq ""`, which FerroEHR + answers with an empty `ListResponse`, and fetches a random User and a + random Group, each answered **404**. +5. **Map the attributes in Entra.** Map `userName`, `externalId`, `active` + and the attributes of step 1. Map the attribute that carries the + professional's login identifier to + `urn:ietf:params:scim:schemas:extension:ferrohealth:2.0:User:loginIdentifier`; + Entra sends it without listing the extension in `schemas`, which FerroEHR + accepts. An attribute the person template does not map is refused as + undefined, so remove the rest of Entra's default mappings. +6. **Protect against mass deactivation.** Turn on Entra's accidental + deletions prevention, with a threshold at or below `max_deactivations`. +7. **Provision groups.** Map the group's `objectId` to its `externalId`, so + the object ids Entra puts in the `groups` claim match, and provision only + the groups assigned to the application, which keeps a person's token under + the groups overage limit. Entra creates each Group with no member, reads it + with `excludedAttributes=members`, finds it by `displayName`, and adds and + removes members with PATCH. + +Entra writes `Replace` and `Add` with a capital letter, disables a User with +`active = false`, sends `DELETE` once the user is removed, and never sends a +null. A value cleared in Entra therefore stays in FerroEHR until the User is +replaced or deleted, or an administrator removes it. diff --git a/website/book/src/installation/config-server.md b/website/book/src/installation/config-server.md index 2045f26a3e..8c96339c86 100644 --- a/website/book/src/installation/config-server.md +++ b/website/book/src/installation/config-server.md @@ -141,7 +141,7 @@ document are never refused by it. Native TLS termination on the main listener, unset by default; deployments commonly terminate TLS at an ingress. `client_auth = "required"` is the IHE ATNA ITI-19 mutually-authenticated-node posture (see the -[Audit trail chapter](../audit.md#node-authentication-iti-19-mutual-tls)). The +[Audit trail chapter](../audit-integrity.md#node-authentication-iti-19-mutual-tls)). The separate-port management listener always stays plain HTTP, so under `deployment.profile = "production"` setting `management.listen` opens the [`plaintext_listener`](configuration.md#deploymentprofile) gap. @@ -378,9 +378,9 @@ statement_timeout = "1min" |---|---|---|---| | `url` | secret URL | `postgres://ferroehr:ferroehr@localhost:5432/ferroehr` | Connection DSN. The default suits a local from-source run against a localhost PostgreSQL, and the server logs a prominent warning at boot while it is in use; **production MUST set it**. Credentials are redacted from every rendering. `DATABASE_URL` is a recognized lower-priority alias. | | `url_file` | path | unset | Read the DSN from a file instead of the key above, for a mounted secret. Preferred over the environment form in Kubernetes: an environment value is readable through `/proc//environ` and inherited by every child process. At most one of the pair, where the built-in development default does not count as "set". | -| `migrate_url` | secret URL | unset | DSN that PREPARES the schema, used for that one boot step and then closed. Preparation spans every schema of a database at once, which no domain-scoped runtime credential can do, so a deployment separating the runtime roles names the credential that can here. It prepares every domain whose DSN reaches the SAME DATABASE — which is the whole of the separated-credential posture, where each domain has a login role of its own on one database; a domain whose DSN reaches a different database is prepared on that database's `database..migrate_url` (on the domain's own DSN when that is unset). Which it is, is read from the server (`pg_control_system()` plus `current_database()`), never from the DSN text. Unset, it falls back to `url`. See [Operations → Which credential prepares the schema](../operations.md#which-credential-prepares-the-schema). | +| `migrate_url` | secret URL | unset | DSN that PREPARES the schema, used for that one boot step and then closed. Preparation spans every schema of a database at once, which no domain-scoped runtime credential can do, so a deployment separating the runtime roles names the credential that can here. It prepares every domain whose DSN reaches the SAME DATABASE, which is the whole of the separated-credential posture, where each domain has a login role of its own on one database; a domain whose DSN reaches a different database is prepared on that database's `database..migrate_url` (on the domain's own DSN when that is unset). Which it is, is read from the server (`pg_control_system()` plus `current_database()`), never from the DSN text. Unset, it falls back to `url`. See [Operations → Which credential prepares the schema](../database-operations.md#which-credential-prepares-the-schema). | | `migrate_url_file` | path | unset | Read `migrate_url` from a file instead, for a mounted secret. At most one of the pair. | -| `migrate` | enum{apply,verify} | `apply` | Whether the server applies its embedded migrations at boot. `apply` is what makes an empty configuration boot against an empty database. `verify` issues **no DDL at all**: it checks that the database already carries exactly this build's migrations and refuses to start otherwise, so the serving DSN can authenticate as a role with no DDL rights. That check still READS every `_sqlx_migrations` table of each database, which no least-privilege role can do, so pair it with `migrate_url` above and with `ferroehr db migrate` run out of band; see [Operations](../operations.md#which-credential-prepares-the-schema). | +| `migrate` | enum{apply,verify} | `apply` | Whether the server applies its embedded migrations at boot. `apply` is what makes an empty configuration boot against an empty database. `verify` issues **no DDL at all**: it checks that the database already carries exactly this build's migrations and refuses to start otherwise, so the serving DSN can authenticate as a role with no DDL rights. That check still READS every `_sqlx_migrations` table of each database, which no least-privilege role can do, so pair it with `migrate_url` above and with `ferroehr db migrate` run out of band; see [Operations](../database-operations.md#which-credential-prepares-the-schema). | | `connection_budget` | int | `40` | The most connections the instance opens to PostgreSQL while it serves: its three pools, the audit runtime's four and its listener connections together. The pools are sized inside it, and a `max_connections` whose pools and listeners exceed it is refused at startup. The default lets two instances share PostgreSQL's default `max_connections` of 100. See [Sizing the pool](#sizing-the-pool). | | `max_connections` | int | unset | The size of each domain's pool (clinical, party and audit each have one). Unset, it is four per core the server may run on, at least 10, within the pool's share of `connection_budget`, and never more than `server.max_concurrent_requests`. See [Sizing the pool](#sizing-the-pool). | | `min_connections` | int | unset | Connections each pool keeps open while idle, which the server opens before it answers ready. Unset, the server keeps every connection of the pool. A one-shot command (`ferroehr db migrate`, `party-binding refill`) opens only what it uses. | @@ -480,7 +480,7 @@ One DSN per storage domain. Every domain always lives in its own schema (`clinical`, `party`, `audit`) and every pool carries only its own on its `search_path`, so no statement can reach another domain's relations without naming a schema it is not granted. Setting a `url` here adds the CREDENTIAL -separation, and — if the DSN names another host — lets the domain live in a +separation, and (if the DSN names another host) lets the domain live in a database or cluster of its own. ```toml @@ -497,20 +497,20 @@ url_file = "/run/secrets/db-party-dsn" Why a schema is not always enough: a base backup, WAL archiving and physical replication carry every schema of a database together -([PostgreSQL 18, Backup and Restore](https://www.postgresql.org/docs/18/backup-dump.html)), +([PostgreSQL 19, Backup and Restore](https://www.postgresql.org/docs/19/backup-dump.html)), so a separation that must survive those is a separation of databases. The Swiss EPDV Art. 10 Abs. 1 lit. b asks for storage "von anderen Datenbeständen getrennt" and the DSV Art. 4 Abs. 5 for the log to be kept "getrennt vom System, in welchem die Personendaten bearbeitet werden"; openEHR reads the same way for the identity cross-reference, which "could be located on different machines" (BASE `architecture_overview/master07-security.adoc` §Anonymity). No openEHR spec -governs pools or database roles — this is our own design. +governs pools or database roles: this is our own design. What the server checks at boot: - a runtime role that can read another domain's relations is refused, always; - two domains configured on **different** DSNs that turn out to authenticate as - the **same** database role are refused — a separation that exists only in the + the **same** database role are refused: a separation that exists only in the configuration is worse than none, because it reads as one that holds; - a missing domain role is a warning under `deployment.profile = "sandbox"` and a refusal under `production`, where there are no grants to separate anything diff --git a/website/book/src/installation/configuration.md b/website/book/src/installation/configuration.md index 3936b0f685..6007c51efa 100644 --- a/website/book/src/installation/configuration.md +++ b/website/book/src/installation/configuration.md @@ -140,14 +140,6 @@ environment carries the same strings: `FERROEHR__RECORD__QUERY__TIMEOUT=45s`. `[server]` and `[auth]` are family sections that keep their own key shapes until the family releases move them. -### Keys a release before v5.7.0 read - -v5.7.0 moved the configuration tree to one table per concern. A key an -earlier release read is an unknown key like any other: the start is refused -naming it, with the keys its table does read, so -`ferroehr config check --config ` lists every key an old file still -sets. The v5.7.0 changelog maps each old key to its replacement. - ## `deployment.spec_profile` ```toml diff --git a/website/book/src/installation/default-demographic-definitions.md b/website/book/src/installation/default-demographic-definitions.md index 4fc649169e..66030f914c 100644 --- a/website/book/src/installation/default-demographic-definitions.md +++ b/website/book/src/installation/default-demographic-definitions.md @@ -1,7 +1,7 @@ # Default demographic definitions Party binding and SCIM provisioning write demographic parties under the -templates and archetypes the [party mapping](config-auth.md#the-party-mapping) +templates and archetypes the [party mapping](config-authz.md#the-party-mapping) names, and the server refuses to boot while the definition store lacks one of them. FerroEHR ships a default set of seven ADL 2 archetypes. The binary carries them, every boot stores each one whose id the definition store does @@ -126,11 +126,11 @@ the files above; the first boot then keeps them. With no mapping key set, `[authz.party_binding]` maps all of them but the provider `ORGANISATION`, which the acts-for relationship of the policy parties -targets ([the default mapping](config-auth.md#the-party-mapping)). SCIM serves +targets ([the default mapping](config-authz.md#the-party-mapping)). SCIM serves `/scim/v2/Groups`, and each client's Groups' `externalId`s are written under its `[auth.issuer..party]` table's `group_identifier_issuer`, or under one derived from its `binding_issuer` when the table sets none -([Groups](config-auth.md#groups)). A test boots an empty configuration, +([Groups](config-scim.md#groups)). A test boots an empty configuration, stores the set as boot does, and provisions a SCIM User, a Group with the User as its member and a representation through it, so the default mapping and the files cannot drift apart. diff --git a/website/book/src/installation/from-source.md b/website/book/src/installation/from-source.md index 612ac5825c..bef49b3852 100644 --- a/website/book/src/installation/from-source.md +++ b/website/book/src/installation/from-source.md @@ -71,7 +71,7 @@ It runs its schema migrations at boot and then serves on the configured bind address (default `0.0.0.0:8080`). That boot-time migration is a setting, not a fixture: `db.migrate = "verify"` makes the server issue no DDL at all, for a deployment whose database role has none of those rights (see -[Operations](../operations.md#applying-migrations)). +[Operations](../database-operations.md#applying-migrations)). Two global flags and three subcommand groups round the CLI out: diff --git a/website/book/src/installation/hardening-detection-response.md b/website/book/src/installation/hardening-detection-response.md index 5442381462..2118bc6eeb 100644 --- a/website/book/src/installation/hardening-detection-response.md +++ b/website/book/src/installation/hardening-detection-response.md @@ -29,12 +29,10 @@ you can judge the exposure rather than reading "secrets" generically. | S3 credentials | `secrets.multimediaSecretAccessKey` (with `secrets.multimediaAccessKeyId`) | offloaded `DV_MULTIMEDIA` blobs, which **are PHI** | | The viewer's OIDC client secret | `viewer.existingSecret`, when the viewer is enabled | the ability to impersonate the viewer at your identity provider | -The rendered `ferroehr.toml` itself is **not** in that list, and that is worth -stating because it used to be: while a Basic user's hash had nowhere secure to go, -configuring one moved the whole configuration file into a Secret. Every credential -the server models now has either a `*_file` sibling or a Secret-borne environment -route, so no key takes that branch today; the chart keeps it only so that a -secret key added upstream tomorrow fails safe instead of landing in a ConfigMap. +The rendered `ferroehr.toml` itself is **not** in that list. Every credential +the server models has either a `*_file` sibling or a Secret-borne environment +route. The chart can still move the file into a Secret, so that a secret key +added upstream fails safe instead of landing in a ConfigMap. The first row is the one that matters most, and it has a property worth naming: **the DSN is a bearer credential.** Any process that can read it can use it, from @@ -357,7 +355,7 @@ reach), and any read of Secrets in this namespace by a principal that is not the kubelet, since that is what reading the DSN looks like from the API side. **Kubernetes `Events` are a third source**, and distinct from both: they are the -cluster's account of what happened to your objects, they expire (typically an +cluster's account of what happened to your objects, they expire (often an hour), and they are where this chart's failures show up first: `Readiness probe failed: HTTP probe failed with statuscode: 503` when a dependency is down, `FailedCreate … violates PodSecurity "restricted:latest"` when a pod spec diff --git a/website/book/src/installation/hardening-network-policy.md b/website/book/src/installation/hardening-network-policy.md index c764168e9f..969d98b6d6 100644 --- a/website/book/src/installation/hardening-network-policy.md +++ b/website/book/src/installation/hardening-network-policy.md @@ -288,7 +288,7 @@ unless its key is set, so add only the rows you have switched on: | OTLP collector | `config.telemetry.otlp.endpoint` | 4317 gRPC / 4318 HTTP | in-cluster | | Token issuer (metadata + key set) | each `config.auth.issuer` table, **unless** it sets its own `jwks_file` | 443 | off-cluster | | FHIR terminology server | `config.the [terminology] table` plus its `url` | 443 | off-cluster | -| FerroTERM in the cluster | `terminology.enabled` | 8080 | in-cluster, and the **chart renders this rule itself** — it chose the destination when it wired the CDR at the Service, so you do not add it to `rules`. Omitted, terminology would fail silently: under the shipped fail-open posture an unresolvable binding is accepted, so nothing refuses and nothing logs. | +| FerroTERM in the cluster | `terminology.enabled` | 8080 | in-cluster, and the **chart renders this rule itself**: it chose the destination when it wired the CDR at the Service, so you do not add it to `rules`. Omitted, terminology would fail silently: under the shipped fail-open posture an unresolvable binding is accepted, so nothing refuses and nothing logs. | | Terminology token endpoint | `config.[terminology].oauth.token_endpoint` | 443 | off-cluster | | Object store | `config.record.multimedia.enabled` plus `config.record.multimedia.s3.url` (unset means AWS regional resolution) | 443, or the endpoint's | off-cluster | | Syslog audit repository | `config.audit.syslog.url` | 6514 TCP (TLS) | off-cluster | @@ -336,4 +336,4 @@ restore the rule → ready again, with no restart So: **verify an egress policy by restarting a pod, not by watching the one that is already running.** (The recovery in the last line needing no restart is the readiness check re-testing its dependencies on every probe, the same property -described for [migrations](kubernetes.md#health-probes).) +described for [migrations](kubernetes-security.md#health-probes).) diff --git a/website/book/src/installation/hardening-supply-chain.md b/website/book/src/installation/hardening-supply-chain.md index 2229f6f78d..8ac977c545 100644 --- a/website/book/src/installation/hardening-supply-chain.md +++ b/website/book/src/installation/hardening-supply-chain.md @@ -89,8 +89,8 @@ identity: | Artifact | Signing workflow | SAN on a release build | SAN on a development build | |---|---|---|---| -| the three images | `build-image.yml` — the reusable builder both callers use | `…/build-image.yml@refs/tags/vX.Y.Z` (the release pipeline) | `…/build-image.yml@refs/heads/main` (via `containers.yml`) | -| the chart | `build-chart.yml` — the reusable chart lane | `…/build-chart.yml@refs/tags/vX.Y.Z` (the release pipeline's chart leg) | `…/build-chart.yml@refs/heads/main` (a `workflow_dispatch` chart-only publish, or the recovery of a release's chart leg for a tag cut before a re-run could finish it) | +| the three images | `build-image.yml`: the reusable builder both callers use | `…/build-image.yml@refs/tags/vX.Y.Z` (the release pipeline) | `…/build-image.yml@refs/heads/main` (via `containers.yml`) | +| the chart | `build-chart.yml`: the reusable chart lane | `…/build-chart.yml@refs/tags/vX.Y.Z` (the release pipeline's chart leg) | `…/build-chart.yml@refs/heads/main` (a `workflow_dispatch` chart-only publish, or the recovery of a release's chart leg for a tag cut before a re-run could finish it) | | the release binaries | `release-build.yml` | `…/release-build.yml@refs/tags/vX.Y.Z` | *(none; the lane only runs on a tag)* | All three prefixed with `https://github.com/FerroHEALTH/FerroEHR/.github/workflows/`, @@ -282,11 +282,9 @@ comments on) a tracking issue, **and** it fails the run. A red scheduled run nobody looks at is not a control, and an issue with no failing check can be closed without the finding being addressed. -The PostgreSQL image is what this lane exists for, and it has already fired: the -`3.17.5` release moved that image onto a rebuilt PostgreSQL 18.4 base to pull in -current Debian packages, changing nothing about FerroEHR itself. The distroless -images carry almost no OS package surface, and when the lane was written none of -the three published images carried a fixable HIGH or CRITICAL finding. +The PostgreSQL image is what this lane exists for: it carries a Debian package +surface, and a fixable finding there is answered by rebuilding the image on a +current base. The distroless images carry almost no OS package surface. The remediation side is standing machinery, not a per-incident scramble. The PostgreSQL image applies Debian security updates at its own build time, so an diff --git a/website/book/src/installation/index.md b/website/book/src/installation/index.md index 00c2a8d84a..2c21f3593a 100644 --- a/website/book/src/installation/index.md +++ b/website/book/src/installation/index.md @@ -3,8 +3,9 @@ FerroEHR is one self-contained binary that connects to a PostgreSQL 19 database. There is no application server to install and no language runtime to provision: the binary links a pure-Rust TLS stack and needs no OpenSSL and no -JVM, so all you choose is how to run it and where the database lives. This part -covers the three paths and the full configuration surface. +JVM, so all you choose is how to run it and where the database lives. This +section covers the three paths; every key is in the +[configuration reference](configuration.md). - **[Try it in Codespaces](codespaces.md):** one click boots the published images in a GitHub Codespace in your browser, with the Swagger UI and the @@ -45,10 +46,10 @@ not this build's) which lets the runtime role hold no DDL rights. Something else then runs `ferroehr db migrate` under a migrator role first. That check still reads every schema's migration state, so a least-privilege deployment also sets `database.migrate_url` to the credential that can. Both postures are laid -out in [Operations → Applying migrations](../operations.md#applying-migrations). +out in [Operations → Applying migrations](../database-operations.md#applying-migrations). v6 needs a new, empty database: it does not upgrade a database a v5 release prepared, and you move the records with the archive dump and load -([Operations → Upgrading from v5 to v6](../operations.md#upgrading-from-v5-to-v6)). +([Operations → Upgrading from v5 to v6](../upgrades.md#upgrading-from-v5-to-v6)). **A deployment declares what it may hold.** The top-level `deployment.profile` key is `sandbox` by default: the server starts whatever diff --git a/website/book/src/installation/kubernetes-integrations.md b/website/book/src/installation/kubernetes-integrations.md new file mode 100644 index 0000000000..3966e9ae83 --- /dev/null +++ b/website/book/src/installation/kubernetes-integrations.md @@ -0,0 +1,503 @@ +# Kubernetes: integrations + +Turning on the optional integrations through the chart. Installing the chart is on +[Kubernetes & Helm](kubernetes.md). + + + +## Integrations + +### Any server setting is reachable + +The chart renders its `config` tree **verbatim** into `ferroehr.toml`. So +`config.` sets *any* key in the +[configuration reference](configuration.md), including keys this page and +`values.yaml` never mention. There is no allow-list to extend and no chart +release to wait for: + +```yaml +# values.yaml — [record.query] plan_cache_capacity, which values.yaml never names +config: + query: + plan_cache_capacity: 512 +``` + +```shell +helm upgrade ferroehr oci://ghcr.io/ferrohealth/charts/ferroehr \ + --version 43.0.1 -n ferroehr --reuse-values \ + --set config.record.query.plan_cache_capacity=512 +``` + +Turning something off is the same edit in reverse: remove the key (or set the +integration's `enabled` back to `false`) and upgrade. The tables below are a +curated starting point for the switches most deployments want; they are not +the boundary of what the chart supports. + +Two things make this safe to rely on: + +- **A typo is a boot refusal, not a silent default.** The server sweeps its + configuration strictly and rejects an unknown key with a did-you-mean, so a + misspelled path fails loudly at startup instead of quietly doing nothing. + Check before you deploy with the schema and boot gates described under + [Check your values before you deploy them](../upgrades.md#check-your-values-before-you-deploy-them). +- **Credentials do not belong in this tree.** `config` becomes a mounted + file; secrets have their own routes (`secrets.*`, `existingSecret`, and the + `*_file` key siblings); see + [Secrets and mounted config](kubernetes.md#secrets-and-mounted-config). + +### The common switches + +Every switch below lives in the chart's `config` tree, so its key *is* the +TOML key from the [configuration reference](configuration.md). Most are **off +by default**; the ones that ship on are marked, and enabling any of the others +is an explicit, auditable decision: + +| Integration | Chart key | Default | Notes | +|---|---|---|---| +| Specification generation | `config.deployment.spec_profile` | `development` | One coupled choice; `stable` runs the released generations. | +| ADMIN API | `config.api.admin` | off | Physical, irreversible delete. Gate behind admin RBAC. | +| Terminology extension API | `config.api.terminology` | off | 404 when off. | +| Outbox feed | `config.authz.grants.allowed` admitting `read_change_feed` | none | The commit-event feed for the readers a `read_change_feed` grant in the CDR names; FerroBRIDGE delivers it to a broker. See [Change events](../beyond-core/outbox-feed.md). | +| Bearer tokens | `config.auth.issuer` | unset | The issuer tables by name, each with its `issuer` and, for an issuer whose users sign in, a `party` table; each issuer's metadata and key set are read in the background from the start, and the pod is not ready until they are; asymmetric algorithms only. | +| Party binding | `config.authz.party_binding.provider` | unset | Required once authentication admits a credential: the healthcare provider the deployment acts for. Each Basic user maps to its binding key under `config.authz.party_binding.basic_user`. | +| RBAC | `config.authz.rbac.enabled` | **on** | The coarse role gate (active while `config.auth.enabled`). | +| S3 multimedia | `config.record.multimedia.enabled` | off | ⚠ Offloaded blobs are PHI. Private, encrypted, HTTPS bucket; keys via `secrets.multimediaAccessKeyId` and `secrets.multimediaSecretAccessKey`. | +| Terminology server | `config.terminology` | off | The one FHIR terminology server, at `config.terminology.endpoint.url`. To run FerroTERM in the cluster instead, use `terminology.enabled` ([FerroTERM](#ferroterm-a-terminology-server-beside-the-cdr-off-by-default)), which sets these keys for you. | +| ATNA audit trail | `config.audit.enabled` | **on** | On with the local store only; forwarding (`config.audit.syslog`, `config.audit.fhir_feed`) is opt-in per sink. | +| Version signing | `config.record.signing.enabled` | **on** (`config.record.signing.mode: digest`) | `pgp` mode needs a `config.files` key plus `secrets.signingKeyPassphrase`, and fails closed at boot without a usable key. | +| OTLP telemetry | `config.telemetry.otlp.endpoint` | unset | Setting the endpoint is all it takes; without a `config.telemetry.otlp` table nothing is exported. With `networkPolicy.egress.enabled`, add a rule for the collector, since a blocked exporter drops spans without an error. | + +Full detail on each is in [Beyond the core](../beyond-core/index.md), +[Security](../security.md), and [Operations](../operations.md). + +The [usage report](../usage-report.md) is on by default, and +`usageReport.enabled=false` switches it off for FerroEHR, for FerroTERM and for +FerroBRIDGE. Each of those takes its own `terminology.usageReport.enabled` or +`bridge.usageReport.enabled` when you want it to differ. FerroPIX runs from its +own chart, which cannot read this chart's switch: set +`ferropix.usageReport.enabled=false` as well, or the chart refuses to render. + +### FerroEHR Viewer (a second workload, off by default) + +`viewer.enabled` renders a second Deployment and Service for the viewer +beside the CDR, from its own image +(`viewer.image.repository`, tagged `appVersion` by default so the two move +together). It is off by default: the viewer is a separate product surface with +its own attack surface, and a CDR is complete without it. + +Three properties are worth knowing before you switch it on: + +- **It reaches the CDR strictly over the REST API**, which + `viewer.networkPolicy.enabled` (on by default) *enforces* rather than + assumes: the viewer's egress admits the CDR Service, DNS and outbound HTTPS + for an identity provider, and nothing else. It holds no database credential. +- **It is a human-facing web UI**, so `viewer.ingress.enabled` is the normal way + to reach it, and `viewer.auth.oidc.enabled` with an issuer, client id and + `viewer.auth.oidc.publicBaseUrl` is how you keep a person who should not see + PHI out of it. Its client secret comes from `viewer.existingSecret`, mounted + as a file exactly as the server's DSN is. +- **`viewer.replicaCount` is 1 deliberately.** The viewer holds session state + in process, so a second replica needs sticky sessions at the ingress or users + are logged out on a reroute. + +The viewer carries the same security context as the server, and the chart's +render gate holds it to the same Restricted profile and the same pod-isolation +settings: a release whose two workloads disagreed about `hostUsers` would be a +posture nobody could state in one sentence. The deployment probe harness then +reads that back off the *running* viewer container, exactly as it does for the +server: its uid, its empty capability bounding set, its read-only root and its +seccomp filter come from the container runtime's own spec, its admission from an +`enforce=restricted` namespace, and its login page from an HTTP request made +inside the cluster through the viewer Service, so the second workload is never +vouched for by the first. What that run does **not** establish is stated in its +own record: the viewer's OIDC path, the screens behind a session, and whether a +CNI enforces the viewer's NetworkPolicy. Its screens are documented in the +[viewer](../viewer/index.md) chapter. + +### FerroPIX (the patient identity source, on by default) + +The CDR keeps no patient-to-record cross-reference of its own by default: it +asks an IHE patient identity source over PIXm (ITI-83) which pseudonym the +clinical domain holds for a patient +([`[pixm]`](config-integrations.md#pixm)). The chart takes +[FerroPIX](https://github.com/FerroHEALTH/FerroPIX) as the chart dependency +`ferropix` (`oci://ghcr.io/ferrohealth/charts`, pinned in `Chart.lock`), so +its Deployment, Service, NetworkPolicy and configuration are its own chart's, +and every key under `ferropix:` is that chart's value. With +`ferropix.enabled` (the default) the chart writes +`config.record.subject_index = "pixm"` and `config.pixm.endpoint.url` at the +FerroPIX Service, and refuses a values file that sets either too. With the +egress policy on, it adds the rule to FerroPIX's pods. + +You supply FerroPIX's PostgreSQL URL and sealing key, its issuer, the +pseudonymisation domain whose consumer is the CDR's client, and the CDR's side +of the same facts: + +```yaml +ferropix: + database: {existingSecret: ferropix-db} + dataKey: {existingSecret: ferropix-data-key} + config: + public_base_url: https://pix.example.org + auth: + issuer: + pix: {issuer: https://idp.example.org/realms/pix, audience: [https://pix.example.org/fhir]} + trust: + issuer: [{issuer: pix, clients: [hospital-source]}] + pseudonym_domain: + - {namespace: urn:oid:2.999.7.1, name: Clinical domain, consumer_client_id: ferroehr} +config: + privacy: + subject_namespaces: [urn:oid:2.999.7.1] + pixm: + assigning_authority: urn:oid:2.999.7.1 + endpoint: + credentials: + oauth: + token_endpoint: https://idp.example.org/realms/pix/protocol/openid-connect/token + client_id: ferroehr + scope: system/Patient.rs +secrets: + ehrIndexClientSecret: +``` + +`secrets.ehrIndexClientSecret` is mounted at +`/etc/ferroehr-secrets/ehr_index.oauth.client_secret`, and the chart injects +the matching `client_secret_file`; the production overlay reads it from a +Secret you own through `extraEnv` instead. Another PIX Manager: +`ferropix.enabled: false` and `config.pixm.endpoint.url`. A CDR run on its +own: `ferropix.enabled: false` and `config.record.subject_index: local`. + +The chart pins FerroPIX 0.0.44 by digest (`ferropix.image`) with the +FerroPIX chart built for it (0.5.6). Since FerroPIX 0.0.40 an +`[auth.issuer.]` entry names its `issuer` and its own `audience`, and +FerroPIX reads the caller from the standard claims of an RFC +9068 `at+jwt` access token, and a client credentials token, whose `sub` is +its `client_id`, is a machine's. It refuses `kind` (other than +`federation`), `preset` and the `profile` table, and an audience written on +the auth section itself. Since 0.0.21 a +Patient Identity Source is admitted only with a client credentials token, +and a Basic user holding a `system/` scope refuses the start. In FerroPIX's +configuration, `public_base_url` is a top-level key, the clients that may act +as a Patient Identity Source sit in the `[[trust.issuer]]` table apart from the +`[auth.issuer.]` entry that names the issuer, `config.auth.issuer` is a +map of issuers by name, and `trust.issuer[].issuer` names the issuer by that +name, never by its URL. + +The restricted-profile gate holds FerroPIX's pods to the Pod Security +Standards `restricted` profile like every other pod in the release. FerroPIX's +chart sets the two properties this chart adds for its own pods itself: +`enableServiceLinks: false`, and a user namespace per pod unless FerroPIX's +own `hostUsers` value, under `ferropix:`, is `true`. + +### FerroTERM (a terminology server beside the CDR, off by default) + +[FerroTERM](https://github.com/FerroHEALTH/FerroTERM) is the Ferro family's +FHIR terminology server: R4, R4B and R5 endpoints over a precomputed index, no +JVM, no database, one distroless image. `terminology.enabled` renders it as a +third workload beside the CDR and the viewer, and points the CDR at it, so +archetype value-set bindings resolve at commit and AQL `TERMINOLOGY()` expands +through it. The CDR's own `/terminology/*` extension routes are a separate +switch: they answer only with `config.api.terminology=true`, which is +`false` by default, and return `404` otherwise whether or not FerroTERM is +running. It is the Helm equivalent of the +[compose terminology overlay](compose-overlays.md#the-terminology-overlay-ferroterm). + +```shell +helm upgrade --install ferroehr oci://ghcr.io/ferrohealth/charts/ferroehr \ + --version 43.0.1 -n ferroehr --reuse-values \ + --set terminology.enabled=true +``` + +That renders a Deployment, a ClusterIP Service, its own ServiceAccount, a +ConfigMap holding the code systems, and a NetworkPolicy. It also writes three +two things into the CDR's `ferroehr.toml`: `config.terminology.on_error` from +`terminology.failOnError`, and `config.terminology.endpoint.url` at the +Service address. + +Because the chart writes those two, a values file that contradicts either is +refused at render rather than silently overwritten. Two shapes are refused +while `terminology.wireCdr` is on: + +- **`config.terminology.endpoint.url`**: two answers to "which server resolves a + binding" is how resolution ends up pointed somewhere nobody chose. +- **`config.terminology.on_error`** disagreeing with + `terminology.failOnError`: same reason, for the posture that decides whether + an unresolvable binding is a `422`. + +Set `terminology.wireCdr=false` to keep your own server and run FerroTERM +unwired. The CDR asks one terminology server, so a server of your own and the +in-cluster FerroTERM are an either-or. + +**No Ingress is rendered, and no value renders one.** The CDR is the only +caller, which is the posture the [hosted sandbox](https://sandbox.ferroehr.eu) +runs and what the SNOMED CT Affiliate Licence asks of a public deployment: +clause 2.2.4 permits a public system to serve SNOMED-encoded data provided users +cannot extract a substantial portion of the release and no fee is charged, and +clause 2.7 requires measures so the release cannot be downloaded except by +authorised users. A published FHIR terminology endpoint answers `$expand` and +`$lookup` to every client that reaches it, and FerroTERM has neither +authentication nor a rate limit of its own. Its NetworkPolicy is therefore the +one in this chart that narrows sources by default: ingress admits the CDR's pods +on the terminology port and nothing else, egress admits DNS. +`terminology.networkPolicy.extraIngressFrom` adds a peer you decide to admit. +**No boolean opens this port** the way `networkPolicy.ingressAllowAll` opens the +CDR's, and a peer you add is admitted exactly as written, which includes +admitting everything: a `namespaceSelector: {}` selects every namespace in the +cluster (networking/v1: "if present but empty, it selects all namespaces"). The +values schema therefore refuses an empty peer, and an empty `podSelector` or +`namespaceSelector` inside one, so reaching that state takes labels you chose +rather than a blank. + +**Out of the box it serves the shaped seed**, which is synthetic content under +the reserved `example.test` domain: two code systems and two value sets, the +same content the conformance lane binds to. The chart carries those files and +mounts them as a ConfigMap, so a fresh install from the registry serves +terminology with no repository checkout. +`terminology.codeSystems.existingConfigMap` swaps in a ConfigMap of your own FHIR +JSON. No licensed terminology ships with FerroEHR or FerroTERM. One caveat with +a ConfigMap of your own: the pod's rollout annotation hashes the chart's own seed +files and the NAME you gave, not the contents of an object the chart does not +own, so editing that ConfigMap updates the volume while the running pods keep +serving what they read at boot. Restart the workload after such an edit +(`kubectl rollout restart deployment/ferroehr-terminology`). + +**A real release is an index you build off-cluster.** Run +`ferroterm-build --rf2 --out ` on a machine that holds the +archive, put the output on a PersistentVolume, and name that claim in +`terminology.index.persistentVolumeClaim`. The chart mounts it **read-only** at +`terminology.index.mountPath` and sets `FERROTERM__TERMINOLOGY__INDEX`; with no claim named, +the variable is absent and the seed is served alone. The chart provisions no +storage and renders no build Job, for the same reason it provisions no database: +unpacking a licensed archive is a step whose licence terms are yours, not a step +a chart should start on its own. + +Naming a claim also switches this Deployment to `strategy: Recreate`. A rolling +update creates the replacement pod before the outgoing one goes away, and a +`ReadWriteOnce` volume can only be attached by one node, so the new pod would +sit Pending on the attachment while `kubectl` reported a progressing rollout. +Recreate stops the old pods first, which costs a short terminology outage at +every upgrade and finishes. If your index volume is `ReadOnlyMany`, override it +with `terminology.strategy={type: RollingUpdate}`. FerroTERM's +[loading page](https://ferroterm.eu/docs/operate/loading-snomed.html) covers the +other code systems and their build flags. Size the memory limit for the edition +before you mount it: `terminology.resources` ships a 1536Mi limit, and the same +FerroTERM page states the resident size of each edition, which the limit must +cover. + +**The fail posture is the CDR's shipped one.** `terminology.failOnError` +defaults to `false`, so a binding the server cannot resolve is accepted; `true` +turns an unreachable terminology server into a `422` refusal. The +[terminology page](../beyond-core/terminology.md#when-the-terminology-server-cannot-answer) +explains both. A code the server resolves as outside its value set is refused +with `422` under either posture. + +**FerroTERM's licence.** BUSL-1.1 from the same Licensor as FerroEHR: +non-commercial production use is free, any other production use needs a +commercial licence. Its README says which is which. The licence for whatever +code systems you load is separate and yours to hold; SNOMED CT needs an +Affiliate Licence (free in Member countries, see +[snomed.org/get-snomed](https://www.snomed.org/get-snomed)), and every surface +showing its content carries the notice clause 8.3.1 prescribes plus the release +version and date. + +**More than one replica needs two other keys.** `terminology.replicaCount` is a +throughput choice (each replica loads its own copy of the index, so watch the +memory limit), and above 1 the pods spread one per node by default, the same +soft constraint the CDR gets. Turn `terminology.podDisruptionBudget.enabled` on +with it: without a budget a node drain may take every terminology replica at +once, and the CDR's own budget does not cover these pods. It is off by default +because the shipped replica count is 1 and a budget over a single pod blocks the +drain it exists to survive. + +FerroTERM carries the same security context as the CDR and the viewer, and the +chart's render gate holds all three to the same Restricted profile. The +deployment probe harness reads this workload back off a running cluster too: its +applied runtime posture, the shaped seed reaching the process from the ConfigMap +volume, a refusal on the terminology port from a pod the policy does not name, +and the CDR resolving a bound code through the Service. Its image is +pinned by digest in `terminology.image.digest` and moves on FerroTERM's own +release line, so it does not follow `appVersion` the way the viewer image does. +Because that digest is set, `terminology.image.tag` alone deploys nothing: the +digest wins, and a tag pointing anywhere else is refused at render rather than +ignored. Clear the digest to deploy by tag. + +### FerroBRIDGE (the FHIR bridge, off by default) + +[FerroBRIDGE](https://github.com/FerroHEALTH/FerroBRIDGE) maps between FHIR R4 +and openEHR with FHIRconnect mappings and reaches FerroEHR over ITS-REST. +FerroEHR itself serves no FHIR API for clinical data, so FerroBRIDGE is the +component that does. `bridge.enabled` renders it as its own workload in the same +release: a Deployment, a ClusterIP Service, its own ServiceAccount, a ConfigMap +holding its configuration file, and a NetworkPolicy. + +The chart writes three sections of that file for you: + +- **`[cdr.endpoint]`:** `url` is this release's CDR Service with its REST base + path (`http://:`), and + `[cdr.endpoint.credentials.oauth]` names the client of `bridge.cdr.oauth` and + its secret, a file mounted from your Secret. +- **`[terminology]`:** with `terminology.enabled` on, `endpoint.url` is the + chart's FerroTERM Service at `/r4` and `wire_version` is `r4`. With it off the + section is absent, and you may set your own under `bridge.config`. +- **`[mappings]`:** `directory` is where the mapping files below are mounted. + +**FerroBRIDGE reaches the CDR as a machine.** It obtains and renews a token +with the OAuth 2.0 client credentials grant (RFC 6749 §4.4) from an issuer +the CDR trusts, and the CDR checks it as it checks every token. A Basic +user is a person and holds no `system/` scope, so the chart has no Basic mode. +Add the issuer to `config.auth.issuer`, name +FerroBRIDGE's client in `bridge.cdr.oauth`, and, when it commits what +`$toopenehr` maps, grant the client in the CDR: an `AGENT` carrying its +`client_id` and performing a `ROLE` that grants `commit_composition`, as +[A system client](../policy-examples.md#a-system-client) shows. The +render is refused when `bridge.cdr.oauth.issuer` is not an issuer of +`config.auth.issuer`. FerroBRIDGE reads the token endpoint from that issuer's +metadata; when the authorization server serves none there, set +`bridge.cdr.oauth.tokenEndpoint`, and `issuer` still names the issuer the CDR +trusts. + +```yaml +config: + auth: + issuer: + - issuer: https://idp.example.org/realms/machines + audience: [ferroehr-machines] +bridge: + cdr: + existingSecret: ferroehr-bridge-cdr + oauth: + issuer: https://idp.example.org/realms/machines + clientId: ferrobridge + scope: system/composition-*.cruds system/template-*.r system/aql-*.rs + audience: ferroehr-machines +``` + +**The client secret comes from a Secret you create.** The chart never takes it +as a value. The Secret carries the key `client_secret`, which is mounted as a +file and named by `client_secret_file`, so it is in neither the ConfigMap nor +the environment. + +```shell +kubectl -n ferroehr create secret generic ferroehr-bridge-cdr \ + --from-file=client_secret=./bridge-client-secret +``` + +**The mapping files come from a ConfigMap you create**, named in +`bridge.mappings.existingConfigMap`, with each key listed in +`bridge.mappings.files`. The chart mounts every key on its own: a whole +ConfigMap volume also carries the kubelet's `..data` snapshot directories, and +FerroBRIDGE reads those as a second and third copy of every file and +refuses the start with a duplicate mapping name. FerroBRIDGE fetches each +template a mapping context names from the CDR at boot, so upload the templates +first; a template the CDR does not hold stops the start. Without a mapping set +FerroBRIDGE still starts, and `$tofhir` and `$toopenehr` answer `503`. + +**A mapping set needs `[auth]`.** With mappings FerroBRIDGE serves its +FHIRconnect operations, and it refuses to start them until FerroBRIDGE's +`[auth]` keys `issuer` and `audience`, set under `bridge.config`, name the +authorization server whose tokens its callers present, or until its `enabled` +is `false`, which serves them to every caller the NetworkPolicy admits. The keys are FerroBRIDGE's own +([configuration reference](https://ferrobridge.eu/docs/operate/configuration.html)). + +```yaml +bridge: + enabled: true + cdr: + existingSecret: ferroehr-bridge-cdr + oauth: + issuer: https://idp.example.org/realms/machines + clientId: ferrobridge + mappings: + existingConfigMap: ferroehr-bridge-mappings + files: + - vital_signs.context.yml + - blood_pressure.yml + config: + auth: + issuer: + callers: + issuer: https://idp.example.org + audience: [https://bridge.example.org/fhir] + networkPolicy: + ingressFrom: + - podSelector: + matchLabels: + app.kubernetes.io/name: my-fhir-client +``` + +**It stays inside the cluster.** A caller FerroBRIDGE admits acts on the CDR +under the client above. So the chart +renders no Ingress for it and no value renders one, the Service is always +ClusterIP, and the NetworkPolicy admits only the peers you list in +`bridge.networkPolicy.ingressFrom`. An empty list is refused at render, and the +values schema refuses a peer that selects everything (an empty peer, or an empty +`podSelector` or `namespaceSelector` inside one). There is no key that admits +every source. Egress admits this release's CDR, FerroTERM when it runs, and +DNS; `bridge.networkPolicy.extraEgress` adds a rule for an upstream you name in +`bridge.config`. When you narrow the CDR's own `networkPolicy.ingressFrom`, the +chart adds FerroBRIDGE's pods to it, and FerroTERM's policy admits them too. + +**Anything else goes in `bridge.config`**, rendered into the same file with +the keys of FerroBRIDGE's +[configuration reference](https://ferrobridge.eu/docs/operate/configuration.html). +FerroBRIDGE refuses an unknown key at boot. The render refuses a key the chart +writes (`cdr.endpoint`, `server.listen`, `terminology` while +FerroTERM runs, `mappings.directory` while the chart mounts the mappings) and +any secret-shaped key, such as a password, a token or `cdm.url`: set its +`_file` sibling and mount the file with `bridge.extraVolumes` and +`bridge.extraVolumeMounts`. FerroBRIDGE's FHIR facade (`[facade]`) keeps its +identity map in a file it writes, and the root filesystem is read-only, so +turning the facade on also takes a PersistentVolumeClaim of yours mounted with +those two keys and named in `facade.identity_store`, with +`bridge.strategy={type: Recreate}` when the claim is ReadWriteOnce. Back that +volume up with the CDR's database. + +Probes use FerroBRIDGE's own endpoints: liveness `/health/liveness`, readiness +`/health/readiness`, which answers `503` while the CDR or FerroTERM is +unreachable. FerroBRIDGE carries the same security context as the other +workloads and the release-wide `hostUsers` setting, and the render gate holds +it to the same Restricted profile. Its image is pinned by digest in +`bridge.image.digest` and moves on FerroBRIDGE's own release line, never with +`appVersion`; a tag other than the pin is refused while the digest is set. The +deployment probe harness boots it on a cluster and reads back its runtime +posture, its admission, the credential being used for the template fetch, a +refusal on its port from a pod outside `ingressFrom`, and its readiness from a +pod inside it. FerroBRIDGE's own deployment documentation is at +. + +### Per-domain backups (one CronJob per domain, off by default) + +`backup.enabled` renders one CronJob per pseudonymisation domain: +`backup.clinical.schedule` dumps the clinical schemas, `backup.party.schedule` +dumps the identities, and each writes to its own existing claim +(`backup.clinical.persistentVolumeClaim`, `backup.party.persistentVolumeClaim`). +The image is `backup.image.repository`, which carries `pg_dump`. + +**A third job renders for the audit domain when `database.audit.existingSecret` +gives it a database of its own.** While the trail shares the clinical database +the clinical dump names its schema and nothing more is needed; once it is +somewhere else, that dump cannot reach it and nothing else would take it, so +`backup.audit.schedule`, `backup.audit.existingSecret` and +`backup.audit.persistentVolumeClaim` become required the same way the other +two are, and the clinical dump stops naming the `audit` schema. + +The chart refuses to render rather than let the separation collapse quietly: a +missing claim is an error naming the value, and naming the **same** claim for +any two domains is an error too, because one volume holding the clinical record +beside the identities is the state per-domain backups exist to prevent. + +Each job needs **its own backup credential**, named by +`backup.clinical.existingSecret`, `backup.party.existingSecret` and, when it +renders, +`backup.audit.existingSecret`, and +the render is refused without them. It cannot be the pool's credential: each +domain's runtime role is revoked from the other domains, so a dump taken through +one would be silently partial. Give each domain a read-only role on that +domain's schema alone. Every job reads its DSN from a mounted file, never an +environment variable. + +The chart provisions no storage. Create the claims yourself, and give them +different access control; that part no chart can do for you. The restore +procedure, and the `ferroehr db verify` gate that judges it, are on the +[Operating](../operations.md) page. diff --git a/website/book/src/installation/kubernetes-security.md b/website/book/src/installation/kubernetes-security.md new file mode 100644 index 0000000000..fe8f5bef0c --- /dev/null +++ b/website/book/src/installation/kubernetes-security.md @@ -0,0 +1,312 @@ +# Kubernetes: security posture, probes and authentication + +What the chart enforces about the workload, how it probes health, and the authentication +it requires before it installs. Installing the chart is on [Kubernetes & Helm](kubernetes.md). + + + +## Security posture + +The chart pins the following, and its render gate holds it: the Restricted fields +are asserted per container for every workload in the render, the two isolation +settings are asserted to agree across a release's workloads, and the golden +renders pin the exact bytes so a changed default fails a diff. + +| Field | Value | +|---|---| +| `runAsNonRoot` | `true` (uid/gid 65532, the distroless `nonroot` user) | +| `readOnlyRootFilesystem` | `true` (a writable `emptyDir` is mounted at `/tmp`) | +| `allowPrivilegeEscalation` | `false` | +| `capabilities.drop` | `[ALL]` | +| `seccompProfile.type` | `RuntimeDefault` (pod and container) | +| `hostUsers` | `false`; the pod gets its own user namespace | +| `supplementalGroupsPolicy` | `Strict`; only the groups the manifest names | +| ServiceAccount token | not mounted (the workload never calls the K8s API) | +| `enableServiceLinks` | `false` (see below; not a preference) | +| NetworkPolicy | ports narrowed to the API (and management) port; **sources admitted unless you narrow them** with `networkPolicy.ingressFrom`; set `networkPolicy.ingressAllowAll: false` to have the chart refuse the open state (see [§Ingress](hardening-network-policy.md#ingress-ports-are-narrowed-sources-are-yours)) | + +The whole set satisfies the Pod Security **Restricted** profile, and the +[deployment probe harness](./kubernetes-hardening.md) reads it back off a running +pod rather than off the rendered manifest: the container runtime's own spec for +the security context, the API server for admission, the EndpointSlice for +readiness. + +Satisfying the profile and **enforcing** it are different things, and only one of +them is yours to do. Enforcement comes from a label on the namespace, which a +chart cannot set for a namespace it does not own, so label it, or the posture +above is a convention nothing checks and nothing fails when a future change +regresses it: + +```shell +kubectl label --overwrite namespace ferroehr \ + pod-security.kubernetes.io/enforce=restricted \ + pod-security.kubernetes.io/enforce-version=latest +``` + +With the label in place the API server refuses a non-compliant pod outright +([Pod Security +Admission](https://kubernetes.io/docs/concepts/security/pod-security-admission/)), +which is a stronger guarantee than any check the chart can make about itself. +The install notes print this as a prerequisite for the same reason. + +`enableServiceLinks: false` is load-bearing, not hygiene. The kubelet injects a +[set of Service link environment +variables](https://kubernetes.io/docs/concepts/services-networking/service/#environment-variables) +for every Service in the namespace, and for a Service named `ferroehr*` those +land inside the server's reserved `FERROEHR_` namespace, whose strict boot-time +sweep rejects unknown variables and refuses to start. Leaving service links on +makes every install crash-loop. + +Egress restriction is opt-in (`networkPolicy.egress.enabled`) because egress +targets (the database, broker, terminology server) are deployment-specific; +when you enable it the chart always admits DNS and you add rules for the rest. +In the default posture the server's only outbound traffic is DNS and PostgreSQL, +so those two rules suffice; each integration you switch on adds a target, and a +blocked one can fail silently. The full destination table is in +[Namespaces, network & policy](./hardening-network-policy.md#egress-deny-by-default-and-what-it-breaks). + +Two limits worth stating plainly. First, with `networkPolicy.ingressFrom` empty +the rendered ingress rule carries no `from` selector, and a rule without `from` +admits **every** source, other namespaces included. Only the port list is +narrowed in that state, so set `ingressFrom` to your ingress controller for a PHI +workload, and set `networkPolicy.ingressAllowAll: false` if an open ingress rule +must never render at all; the full treatment is +[§Ingress](hardening-network-policy.md#ingress-ports-are-narrowed-sources-are-yours). +The viewer's own policy carries the same pair under `viewer.networkPolicy`. +Second, a NetworkPolicy is only as real as the CNI that implements it: +on a cluster whose network plugin does not enforce NetworkPolicy the object is +documentation rather than a control, and nothing in Kubernetes reports that. +Confirm it by attempting a connection the policy should refuse. + +The database-side controls (the server certificate behind `sslmode=verify-full`, +pgaudit, at-rest encryption, WAL archiving / PITR) belong to whoever provisions +PostgreSQL; the chart mounts the CA (`database.caConfigMap`) but cannot enforce +the rest. See +[Operations](../operations.md). + +### TLS at the pod + +The production overlay ends TLS at the Ingress and accepts `plaintext_listener` +by name. To close that gap instead, the server terminates TLS itself +(`config.server.tls`), and every client the chart wires to it follows: the +viewer and FerroBRIDGE call `https://:`, the kubelet +probes over HTTPS, the Service declares `appProtocol: https`, and a +ServiceMonitor that scrapes the API port uses `https` too. + +The clients check the server's certificate against a CA you name in +`service.tls.caExistingSecret`. The certificate must carry the Service name +(the release's full name, `ferroehr` for a release called `ferroehr`) as a DNS +SAN, which no public CA issues, so the chart refuses to render a TLS listener +beside an enabled viewer, FerroBRIDGE or API-port scrape while that value is +empty. Name a Secret that holds the CA certificate alone: every pod and the +ServiceMonitor that read it then read no private key, and a ServiceMonitor in +another namespace reads its own copy there. A cert-manager `Certificate` +writes the key pair and the CA into one Secret (`tls.crt`, `tls.key`, +`ca.crt`); copy `ca.crt` out of it (trust-manager's `Bundle` does this) rather +than naming that Secret. The Ingress in front of the TLS listener must reach +it over HTTPS too, and how a controller is told so is controller-specific, so +the chart refuses to render the Ingress with server TLS on until +`ingress.backendTlsAnnotations` names it: + +```yaml +config: + deployment.accepts: [] # nothing left to accept for the listener + server: + tls: + certificate_file: /etc/ferroehr-tls/tls.crt + key_file: /etc/ferroehr-tls/tls.key + reload_interval: 1min +extraVolumes: + - name: server-tls + secret: + secretName: ferroehr-server-tls + defaultMode: 0440 + items: + - { key: tls.crt, path: tls.crt } + - { key: tls.key, path: tls.key } +extraVolumeMounts: + - { name: server-tls, mountPath: /etc/ferroehr-tls, readOnly: true } +service: + tls: + caExistingSecret: ferroehr-server-ca # ca.crt alone +ingress: + backendTlsAnnotations: # ingress-nginx + nginx.ingress.kubernetes.io/backend-protocol: HTTPS +``` + +When cert-manager renews the certificate, the kubelet updates the mounted +files and the server serves the new pair within +`config.server.tls.reload_interval` (a minute above; unset, only `SIGHUP` +reads the files again), with no restart; a renewed pair that fails to load is logged and the old one stays in +service. A rotated client CA (`client_ca_file`, for `client_auth`) is picked up +on the same interval, and the connections already open keep the trust anchor +they were verified against. + +The viewer reads the mounted CA through its own `cdr.tls.trust_roots_file`, +beside the image's roots. FerroBRIDGE reads it through `SSL_CERT_DIR`, which +the chart sets to the image's system roots plus the mounted CA, so its other +peers that verify through the platform verifier stay trusted. For an OIDC +issuer whose certificate comes from a private CA, name a Secret holding that +CA in `viewer.auth.oidc.caExistingSecret` (key `viewer.auth.oidc.caExistingSecretKey`, +`ca.crt` by default): the chart mounts it and points the viewer's +`[oidc.tls] trust_roots_file` at it. For the server's own `[auth]` +issuer behind a private CA, name the Secret in `auth.caExistingSecret` (key +`auth.caExistingSecretKey`, `ca.crt` by default): the chart mounts it and points +the server's `[auth.tls] trust_roots_file` at it. The ServiceMonitor reads the Secret from its own namespace, and +the `prometheus.io/scheme: https` pod annotation follows the listener when +`metrics.enabled` is set. With `config.server.tls.client_auth: required` the +kubelet probes cannot present a client certificate, so the chart refuses to +render it; keep it at `none` or `optional`. +`config.management.listen` stays plain HTTP on its own listener. + +## Health probes + +All three probes use the always-on, unauthenticated, PHI-free health routes on the +main HTTP port. They need no configuration at all: no management surface, no +access level, nothing to forget: + +| Probe | Route | Contract | +|---|---|---| +| liveness | `/health/liveness` | 200 while the process is up; touches no dependency | +| readiness | `/health/readiness` | 200 (up or degraded) or 503 (down, booting or draining): checks the database ping, migrations applied and the audit sender, each bounded at one second | +| startup | `/health/liveness` | the same constant, with a long failure threshold, so a slow first boot is not killed mid-migration | + +That split is deliberate: a database outage must fail *readiness* (the pod stops +receiving traffic) and never liveness (which would restart the container in a +loop). + +> [!NOTE] +> The chart offers no `exec` probe: the `httpGet` probes above are what it +> runs. The binary's `healthcheck` subcommand asks `/health/readiness`. + +> [!WARNING] +> **Migrations run only at boot, so a replaced or wiped database leaves the pods +> NotReady until something migrates it.** Readiness reports the `migrations` +> indicator `down` (its detail on `/management/health`: `core schema tables +> missing (migrations not applied)`) while `db` reads `up`: the pod reaches PostgreSQL, finds no +> schema, and does not migrate again, because migration is a startup step. +> Liveness keeps passing (correctly: the process is healthy), so the kubelet never +> restarts the container and the Deployment sits with no ready replicas and no +> error in the logs after the first one: +> +> ```shell +> kubectl -n ferroehr get pods # Running, not READY +> curl -s http://ferroehr:8080/health/readiness # 503, "migrations" down, "db" up +> kubectl -n ferroehr rollout restart deploy/ferroehr +> ``` +> +> The check re-tests the schema on every probe, so a pod recovers on its own within +> one `probes.readiness.periodSeconds` of the schema existing; an untouched pod +> returns to ready, with no restart, once anything else has migrated. What needs +> the restart is the case where the only thing that would migrate is the pod +> itself. +> +> That is what makes the interaction with flow (b) load-bearing: when migrations +> run out of band, the migration step must complete *before* the Deployment rolls, +> or the first pods sit unready waiting for a schema. `migrations.job.enabled` +> does exactly that, as a hook Helm waits on. Durable storage is the other +> half: an `emptyDir`-backed or otherwise disposable PostgreSQL puts a clinical +> repository one node eviction away from this state. +> +> One recovery path does **not** self-heal, and it is worth knowing before you try +> it: restoring or dropping *part* of the schema set. A restore that brings back +> some of a domain's relations without its migration bookkeeping makes the next +> migration run fail permanently with `relation "version" already exists`: the +> pod crash-loops, and restarting it retries the same failure. Recreate the whole +> database rather than one schema. + +The management surface is independent of the probes and stays ops-only +(`/management/info`, `/prometheus`, `/metrics`, `/env`, `/loggers`, +`/flamegraph`). Unlike the bare binary, the chart ships +`config.management.enabled: true` with **every endpoint off**, so nothing is +exposed until you opt one in. Set +`config.management.endpoints.prometheus: public` plus `metrics.enabled=true` +to add the `prometheus.io/*` scrape annotations; set `config.management.listen` +to serve the surface on its own internal listener, so `/management` is never +reachable on the clinical API port. The health probes stay on the main port +regardless of all of this, and the install notes warn you if you add the scrape +annotations while the endpoint is still `off`. + +Those annotations are honoured by a Prometheus that discovers targets in its own +scrape configuration. An **operator-managed** Prometheus +(kube-prometheus-stack) ignores them and selects targets through +[ServiceMonitor](https://prometheus-operator.dev/docs/developer/getting-started/) +objects instead, so set `metrics.serviceMonitor.enabled=true` there; +`metrics.serviceMonitor.labels` is where the label your Prometheus' +`serviceMonitorSelector` matches on goes. It needs the `monitoring.coreos.com` +CRDs installed first, or the install fails on an unknown kind. + +## Authentication is required, and the chart says so before it installs + +`config.auth.enabled` defaults to **true**, and the server requires at least one +mechanism with it: a `401` challenge has to name a scheme the server actually +implements ([RFC 9110 §11.6.1](https://www.rfc-editor.org/rfc/rfc9110#section-11.6.1)), +so it exits rather than run as an openEHR API that can only refuse every request. + +The chart therefore **refuses to render** a values file that enables +authentication without configuring one, so `helm install` stops with an +actionable error instead of reporting success and crash-looping: + +```text +Error: execution error at (ferroehr/templates/deployment.yaml:...): +config.auth.enabled is true but no authentication mechanism is configured... +``` + +Pick one: + +```yaml +config: + auth: + issuer: + keycloak: + issuer: https://keycloak.example.org/realms/ferroehr + audience: [ferroehr] + profile: + token_types: [JWT] + party: + identifier_issuer: urn:example:staff-login + identifier_type: uuid + authz: + rbac: + role_issuers: [keycloak] + party_binding: + provider: { issuer: "urn:oid:2.16.528.1.1007.3.3", id: "12345678" } +``` + +or Basic auth, whose password hashes go in `secrets.basicUserPasswordHashes` +while the user stays under `config.auth.basic.users`; its scopes and roles +are grants on its `PERSON`, and `config.authz.rbac.first_admin` names the +Basic user that holds `admin_role`. The authorization server's registry is +the one list of clients, so a token whose `aud` names FerroEHR admits its +client ([Authentication & access](config-auth.md)). +A Basic user is a person: each maps to the binding key of its `PERSON` under +`config.authz.party_binding.basic_user`, under the identifier issuer of the +`party` table under its issuer in `config.auth.issuer` (see +`deploy/helm/ci/basic-auth-values.yaml`). + +The server stores FerroEHR's +[default demographic definitions](default-demographic-definitions.md) as it +boots, and with no mapping key set the party mapping names them, so a chart +install needs no list of definitions. A party mapping that names templates +of your own needs them in the definition store before the server boots, +which refuses a mapping whose templates it lacks. `definitions.files` lists +them, each a `name` ending in `.opt` (OPT 1.4) or `.adls` (ADL 2) and its +`content`: the chart puts them in a ConfigMap of their own and runs +`ferroehr definitions load` on them as an init container, with the server's +image, configuration and secrets, in the order listed. A definition already +stored with the same text is left alone, so the step runs at every pod +start, and one stored under its id with other text fails the pod. The list +is empty by default. `deploy/helm/ci/basic-auth-values.yaml` keeps the +default mapping and provisions its user through `/scim/v2/Users` (see +[`[auth.scim]`](config-scim.md#authscim)). + +An issuer with `sender_constraint: required` runs on any number of +replicas: each records the DPoP proofs it accepts in the database they all +share, so a proof replayed to another replica is refused there (RFC 9449 +§11.1). + +> [!WARNING] +> `config.auth.enabled: false` makes the chart render, and serves **every** +> request unauthenticated. On a repository holding patient data that is a +> development-only choice; the chart makes you state it explicitly rather than +> reaching it by omission. diff --git a/website/book/src/installation/kubernetes.md b/website/book/src/installation/kubernetes.md index df00d70c63..2b303c0ec9 100644 --- a/website/book/src/installation/kubernetes.md +++ b/website/book/src/installation/kubernetes.md @@ -5,8 +5,11 @@ Kubernetes workload (non-root, read-only root filesystem, a NetworkPolicy that admits its serving port only, its own user namespace) against an **external** PostgreSQL 19. This chapter covers installing it, verifying what you installed, the database role model it -expects, the security posture it pins, the health probes, the optional -integrations, and upgrades. +expects, its secrets, and staying available while things move. Upgrading the +release is on [Upgrades](../upgrades.md#upgrading-the-helm-release). The security posture, the health probes +and authentication are on [Kubernetes: security posture, probes and +authentication](kubernetes-security.md), and the optional integrations on +[Kubernetes: integrations](kubernetes-integrations.md). @@ -52,7 +55,7 @@ render without one. A deployment holding patient data starts from the the in-instance EHR index, for a CDR run on its own. By default the chart runs FerroPIX, the IHE patient identity source, beside the CDR and points the EHR index at it, which needs FerroPIX's own Secrets and an -issuer: see [FerroPIX](#ferropix-the-patient-identity-source-on-by-default). +issuer: see [FerroPIX](kubernetes-integrations.md#ferropix-the-patient-identity-source-on-by-default). With neither, the render is refused and names both choices, as the server's boot would be. @@ -277,16 +280,16 @@ says what it runs: accepts the plaintext listener by name. - **The access log retention** is no chart value: it is the controller's access policy (`ACCESS_POLICY.log_retention`), written through the admin - API once the server runs ([Audit trail](../audit.md#retention-and-who-chooses-it)). + API once the server runs ([Audit trail](../ehds-logging.md#retention-and-who-chooses-it)). - **The category map** is no chart value: it is the [audit category register](config-audit.md#the-audit-category-register), an - [admin register](../operational-policy.md#the-admin-registers) you write + [admin register](../access-policy.md#the-admin-registers) you write through the admin API once the server runs. Until then the category map FerroEHR ships applies. The access delay is an admin register too. The [Audit](config-audit.md) page has the category vocabulary, and the -[audit trail](../audit.md#retention-and-who-chooses-it) page the access log +[audit trail](../ehds-logging.md#retention-and-who-chooses-it) page the access log retention the controller declares in its access policy. ### The production overlay @@ -342,7 +345,7 @@ under `production` with `plaintext_listener` as its only gap, both over all three domains on one cluster by naming `shared_cluster`. Against your own databases, `shared_cluster` is first judged when the pod starts. -## Database roles — who runs migrations +## Database roles: who runs migrations The chart expects a PostgreSQL role model in which the runtime pod is never a superuser. Four roles cover the single-domain posture: @@ -406,7 +409,7 @@ the demographic one and that pool shares the first, which is the schema-only posture, still separated and still verified at boot. Creating the four domain roles is a database step the chart cannot do for you; -[Operations](../operations.md#turning-the-schema-split-into-a-role-split) has +[Operations](../database-operations.md#turning-the-schema-split-into-a-role-split) has the statements and what `ferroehr db verify` reports. `database.migrateExistingSecret` is what the pod prepares the schema with, and @@ -504,814 +507,6 @@ not propagate. > Argon2id hash is not a plaintext password, but it is an offline cracking target, > which is what the boot-time OWASP parameter floor exists to make expensive. -## Security posture - -The chart pins the following, and its render gate holds it: the Restricted fields -are asserted per container for every workload in the render, the two isolation -settings are asserted to agree across a release's workloads, and the golden -renders pin the exact bytes so a changed default fails a diff. - -| Field | Value | -|---|---| -| `runAsNonRoot` | `true` (uid/gid 65532, the distroless `nonroot` user) | -| `readOnlyRootFilesystem` | `true` (a writable `emptyDir` is mounted at `/tmp`) | -| `allowPrivilegeEscalation` | `false` | -| `capabilities.drop` | `[ALL]` | -| `seccompProfile.type` | `RuntimeDefault` (pod and container) | -| `hostUsers` | `false`; the pod gets its own user namespace | -| `supplementalGroupsPolicy` | `Strict`; only the groups the manifest names | -| ServiceAccount token | not mounted (the workload never calls the K8s API) | -| `enableServiceLinks` | `false` (see below; not a preference) | -| NetworkPolicy | ports narrowed to the API (and management) port; **sources admitted unless you narrow them** with `networkPolicy.ingressFrom`; set `networkPolicy.ingressAllowAll: false` to have the chart refuse the open state (see [§Ingress](hardening-network-policy.md#ingress-ports-are-narrowed-sources-are-yours)) | - -The whole set satisfies the Pod Security **Restricted** profile, and the -[deployment probe harness](./kubernetes-hardening.md) reads it back off a running -pod rather than off the rendered manifest: the container runtime's own spec for -the security context, the API server for admission, the EndpointSlice for -readiness. - -Satisfying the profile and **enforcing** it are different things, and only one of -them is yours to do. Enforcement comes from a label on the namespace, which a -chart cannot set for a namespace it does not own, so label it, or the posture -above is a convention nothing checks and nothing fails when a future change -regresses it: - -```shell -kubectl label --overwrite namespace ferroehr \ - pod-security.kubernetes.io/enforce=restricted \ - pod-security.kubernetes.io/enforce-version=latest -``` - -With the label in place the API server refuses a non-compliant pod outright -([Pod Security -Admission](https://kubernetes.io/docs/concepts/security/pod-security-admission/)), -which is a stronger guarantee than any check the chart can make about itself. -The install notes print this as a prerequisite for the same reason. - -`enableServiceLinks: false` is load-bearing, not hygiene. The kubelet injects a -[set of Service link environment -variables](https://kubernetes.io/docs/concepts/services-networking/service/#environment-variables) -for every Service in the namespace, and for a Service named `ferroehr*` those -land inside the server's reserved `FERROEHR_` namespace, whose strict boot-time -sweep rejects unknown variables and refuses to start. Leaving service links on -makes every install crash-loop. - -Egress restriction is opt-in (`networkPolicy.egress.enabled`) because egress -targets (the database, broker, terminology server) are deployment-specific; -when you enable it the chart always admits DNS and you add rules for the rest. -In the default posture the server's only outbound traffic is DNS and PostgreSQL, -so those two rules suffice; each integration you switch on adds a target, and a -blocked one can fail silently. The full destination table is in -[Namespaces, network & policy](./hardening-network-policy.md#egress-deny-by-default-and-what-it-breaks). - -Two limits worth stating plainly. First, with `networkPolicy.ingressFrom` empty -the rendered ingress rule carries no `from` selector, and a rule without `from` -admits **every** source, other namespaces included. Only the port list is -narrowed in that state, so set `ingressFrom` to your ingress controller for a PHI -workload, and set `networkPolicy.ingressAllowAll: false` if an open ingress rule -must never render at all; the full treatment is -[§Ingress](hardening-network-policy.md#ingress-ports-are-narrowed-sources-are-yours). -The viewer's own policy carries the same pair under `viewer.networkPolicy`. -Second, a NetworkPolicy is only as real as the CNI that implements it: -on a cluster whose network plugin does not enforce NetworkPolicy the object is -documentation rather than a control, and nothing in Kubernetes reports that. -Confirm it by attempting a connection the policy should refuse. - -The database-side controls (the server certificate behind `sslmode=verify-full`, -pgaudit, at-rest encryption, WAL archiving / PITR) belong to whoever provisions -PostgreSQL; the chart mounts the CA (`database.caConfigMap`) but cannot enforce -the rest. See -[Operations](../operations.md). - -### TLS at the pod - -The production overlay ends TLS at the Ingress and accepts `plaintext_listener` -by name. To close that gap instead, the server terminates TLS itself -(`config.server.tls`), and every client the chart wires to it follows: the -viewer and FerroBRIDGE call `https://:`, the kubelet -probes over HTTPS, the Service declares `appProtocol: https`, and a -ServiceMonitor that scrapes the API port uses `https` too. - -The clients check the server's certificate against a CA you name in -`service.tls.caExistingSecret`. The certificate must carry the Service name -(the release's full name, `ferroehr` for a release called `ferroehr`) as a DNS -SAN, which no public CA issues, so the chart refuses to render a TLS listener -beside an enabled viewer, FerroBRIDGE or API-port scrape while that value is -empty. Name a Secret that holds the CA certificate alone: every pod and the -ServiceMonitor that read it then read no private key, and a ServiceMonitor in -another namespace reads its own copy there. A cert-manager `Certificate` -writes the key pair and the CA into one Secret (`tls.crt`, `tls.key`, -`ca.crt`); copy `ca.crt` out of it (trust-manager's `Bundle` does this) rather -than naming that Secret. The Ingress in front of the TLS listener must reach -it over HTTPS too, and how a controller is told so is controller-specific, so -the chart refuses to render the Ingress with server TLS on until -`ingress.backendTlsAnnotations` names it: - -```yaml -config: - deployment.accepts: [] # nothing left to accept for the listener - server: - tls: - certificate_file: /etc/ferroehr-tls/tls.crt - key_file: /etc/ferroehr-tls/tls.key - reload_interval: 1min -extraVolumes: - - name: server-tls - secret: - secretName: ferroehr-server-tls - defaultMode: 0440 - items: - - { key: tls.crt, path: tls.crt } - - { key: tls.key, path: tls.key } -extraVolumeMounts: - - { name: server-tls, mountPath: /etc/ferroehr-tls, readOnly: true } -service: - tls: - caExistingSecret: ferroehr-server-ca # ca.crt alone -ingress: - backendTlsAnnotations: # ingress-nginx - nginx.ingress.kubernetes.io/backend-protocol: HTTPS -``` - -When cert-manager renews the certificate, the kubelet updates the mounted -files and the server serves the new pair within -`config.server.tls.reload_interval` (a minute above; unset, only `SIGHUP` -reads the files again), with no restart; a renewed pair that fails to load is logged and the old one stays in -service. A rotated client CA (`client_ca_file`, for `client_auth`) is picked up -on the same interval, and the connections already open keep the trust anchor -they were verified against. - -The viewer reads the mounted CA through its own `cdr.tls.trust_roots_file`, -beside the image's roots. FerroBRIDGE reads it through `SSL_CERT_DIR`, which -the chart sets to the image's system roots plus the mounted CA, so its other -peers that verify through the platform verifier stay trusted. For an OIDC -issuer whose certificate comes from a private CA, name a Secret holding that -CA in `viewer.auth.oidc.caExistingSecret` (key `viewer.auth.oidc.caExistingSecretKey`, -`ca.crt` by default): the chart mounts it and points the viewer's -`[oidc.tls] trust_roots_file` at it. For the server's own `[auth]` -issuer behind a private CA, name the Secret in `auth.caExistingSecret` (key -`auth.caExistingSecretKey`, `ca.crt` by default): the chart mounts it and points -the server's `[auth.tls] trust_roots_file` at it. The ServiceMonitor reads the Secret from its own namespace, and -the `prometheus.io/scheme: https` pod annotation follows the listener when -`metrics.enabled` is set. With `config.server.tls.client_auth: required` the -kubelet probes cannot present a client certificate, so the chart refuses to -render it; keep it at `none` or `optional`. -`config.management.listen` stays plain HTTP on its own listener. - -## Health probes - -All three probes use the always-on, unauthenticated, PHI-free health routes on the -main HTTP port. They need no configuration at all: no management surface, no -access level, nothing to forget: - -| Probe | Route | Contract | -|---|---|---| -| liveness | `/health/liveness` | 200 while the process is up; touches no dependency | -| readiness | `/health/readiness` | 200 (up or degraded) or 503 (down, booting or draining): checks the database ping, migrations applied and the audit sender, each bounded at one second | -| startup | `/health/liveness` | the same constant, with a long failure threshold, so a slow first boot is not killed mid-migration | - -That split is deliberate: a database outage must fail *readiness* (the pod stops -receiving traffic) and never liveness (which would restart the container in a -loop). - -> [!NOTE] -> There is no `exec` probe option. One existed and was removed: it ran the -> binary's `healthcheck` subcommand, which then asked the openEHR status -> document rather than a health route, so **readiness never touched the -> database** and a pod with a dead database reported Ready and took clinical -> traffic. The subcommand now asks `/health/readiness`, and the `httpGet` -> probes above remain what the chart runs. - -> [!WARNING] -> **Migrations run only at boot, so a replaced or wiped database leaves the pods -> NotReady until something migrates it.** Readiness reports the `migrations` -> indicator `down` (its detail on `/management/health`: `core schema tables -> missing (migrations not applied)`) while `db` reads `up`: the pod reaches PostgreSQL, finds no -> schema, and does not migrate again, because migration is a startup step. -> Liveness keeps passing (correctly: the process is healthy), so the kubelet never -> restarts the container and the Deployment sits with no ready replicas and no -> error in the logs after the first one: -> -> ```shell -> kubectl -n ferroehr get pods # Running, not READY -> curl -s http://ferroehr:8080/health/readiness # 503, "migrations" down, "db" up -> kubectl -n ferroehr rollout restart deploy/ferroehr -> ``` -> -> The check re-tests the schema on every probe, so a pod recovers on its own within -> one `probes.readiness.periodSeconds` of the schema existing; an untouched pod -> returns to ready, with no restart, once anything else has migrated. What needs -> the restart is the case where the only thing that would migrate is the pod -> itself. -> -> That is what makes the interaction with flow (b) load-bearing: when migrations -> run out of band, the migration step must complete *before* the Deployment rolls, -> or the first pods sit unready waiting for a schema. `migrations.job.enabled` -> does exactly that, as a hook Helm waits on. Durable storage is the other -> half: an `emptyDir`-backed or otherwise disposable PostgreSQL puts a clinical -> repository one node eviction away from this state. -> -> One recovery path does **not** self-heal, and it is worth knowing before you try -> it: restoring or dropping *part* of the schema set. A restore that brings back -> some of a domain's relations without its migration bookkeeping makes the next -> migration run fail permanently with `relation "version" already exists`: the -> pod crash-loops, and restarting it retries the same failure. Recreate the whole -> database rather than one schema. - -The management surface is independent of the probes and stays ops-only -(`/management/info`, `/prometheus`, `/metrics`, `/env`, `/loggers`, -`/flamegraph`). Unlike the bare binary, the chart ships -`config.management.enabled: true` with **every endpoint off**, so nothing is -exposed until you opt one in. Set -`config.management.endpoints.prometheus: public` plus `metrics.enabled=true` -to add the `prometheus.io/*` scrape annotations; set `config.management.listen` -to serve the surface on its own internal listener, so `/management` is never -reachable on the clinical API port. The health probes stay on the main port -regardless of all of this, and the install notes warn you if you add the scrape -annotations while the endpoint is still `off`. - -Those annotations are honoured by a Prometheus that discovers targets in its own -scrape configuration. An **operator-managed** Prometheus -(kube-prometheus-stack) ignores them and selects targets through -[ServiceMonitor](https://prometheus-operator.dev/docs/developer/getting-started/) -objects instead, so set `metrics.serviceMonitor.enabled=true` there; -`metrics.serviceMonitor.labels` is where the label your Prometheus' -`serviceMonitorSelector` matches on goes. It needs the `monitoring.coreos.com` -CRDs installed first, or the install fails on an unknown kind. - -## Authentication is required, and the chart says so before it installs - -`config.auth.enabled` defaults to **true**, and the server requires at least one -mechanism with it: a `401` challenge has to name a scheme the server actually -implements ([RFC 9110 §11.6.1](https://www.rfc-editor.org/rfc/rfc9110#section-11.6.1)), -so it exits rather than run as an openEHR API that can only refuse every request. - -The chart therefore **refuses to render** a values file that enables -authentication without configuring one, so `helm install` stops with an -actionable error instead of reporting success and crash-looping: - -```text -Error: execution error at (ferroehr/templates/deployment.yaml:...): -config.auth.enabled is true but no authentication mechanism is configured... -``` - -Pick one: - -```yaml -config: - auth: - issuer: - keycloak: - issuer: https://keycloak.example.org/realms/ferroehr - audience: [ferroehr] - profile: - token_types: [JWT] - party: - identifier_issuer: urn:example:staff-login - identifier_type: uuid - authz: - rbac: - role_issuers: [keycloak] - party_binding: - provider: { issuer: "urn:oid:2.16.528.1.1007.3.3", id: "12345678" } -``` - -or Basic auth, whose password hashes go in `secrets.basicUserPasswordHashes` -while the user stays under `config.auth.basic.users`; its scopes and roles -are grants on its `PERSON`, and `config.authz.rbac.first_admin` names the -Basic user that holds `admin_role`. The authorization server's registry is -the one list of clients, so a token whose `aud` names FerroEHR admits its -client ([Authentication & access](config-auth.md)). -A Basic user is a person: each maps to the binding key of its `PERSON` under -`config.authz.party_binding.basic_user`, under the identifier issuer of the -`party` table under its issuer in `config.auth.issuer` (see -`deploy/helm/ci/basic-auth-values.yaml`). - -The server stores FerroEHR's -[default demographic definitions](default-demographic-definitions.md) as it -boots, and with no mapping key set the party mapping names them, so a chart -install needs no list of definitions. A party mapping that names templates -of your own needs them in the definition store before the server boots, -which refuses a mapping whose templates it lacks. `definitions.files` lists -them, each a `name` ending in `.opt` (OPT 1.4) or `.adls` (ADL 2) and its -`content`: the chart puts them in a ConfigMap of their own and runs -`ferroehr definitions load` on them as an init container, with the server's -image, configuration and secrets, in the order listed. A definition already -stored with the same text is left alone, so the step runs at every pod -start, and one stored under its id with other text fails the pod. The list -is empty by default. `deploy/helm/ci/basic-auth-values.yaml` keeps the -default mapping and provisions its user through `/scim/v2/Users` (see -[`[auth.scim]`](config-auth.md#authscim)). - -An issuer with `sender_constraint: required` runs on any number of -replicas: each records the DPoP proofs it accepts in the database they all -share, so a proof replayed to another replica is refused there (RFC 9449 -§11.1). - -> [!WARNING] -> `config.auth.enabled: false` makes the chart render, and serves **every** -> request unauthenticated. On a repository holding patient data that is a -> development-only choice; the chart makes you state it explicitly rather than -> reaching it by omission. - -## Integrations - -### Any server setting is reachable - -The chart renders its `config` tree **verbatim** into `ferroehr.toml`. So -`config.` sets *any* key in the -[configuration reference](configuration.md), including keys this page and -`values.yaml` never mention. There is no allow-list to extend and no chart -release to wait for: - -```yaml -# values.yaml — [record.query] plan_cache_capacity, which values.yaml never names -config: - query: - plan_cache_capacity: 512 -``` - -```shell -helm upgrade ferroehr oci://ghcr.io/ferrohealth/charts/ferroehr \ - --version 43.0.1 -n ferroehr --reuse-values \ - --set config.record.query.plan_cache_capacity=512 -``` - -Turning something off is the same edit in reverse: remove the key (or set the -integration's `enabled` back to `false`) and upgrade. The tables below are a -curated starting point for the switches most deployments want; they are not -the boundary of what the chart supports. - -Two things make this safe to rely on: - -- **A typo is a boot refusal, not a silent default.** The server sweeps its - configuration strictly and rejects an unknown key with a did-you-mean, so a - misspelled path fails loudly at startup instead of quietly doing nothing. - Check before you deploy with the schema and boot gates described under - [Check your values before you deploy them](#check-your-values-before-you-deploy-them). -- **Credentials do not belong in this tree.** `config` becomes a mounted - file; secrets have their own routes (`secrets.*`, `existingSecret`, and the - `*_file` key siblings); see - [Secrets and mounted config](#secrets-and-mounted-config). - -### The common switches - -Every switch below lives in the chart's `config` tree, so its key *is* the -TOML key from the [configuration reference](configuration.md). Most are **off -by default**; the ones that ship on are marked, and enabling any of the others -is an explicit, auditable decision: - -| Integration | Chart key | Default | Notes | -|---|---|---|---| -| Specification generation | `config.deployment.spec_profile` | `development` | One coupled choice; `stable` runs the released generations. | -| ADMIN API | `config.api.admin` | off | Physical, irreversible delete. Gate behind admin RBAC. | -| Terminology extension API | `config.api.terminology` | off | 404 when off. | -| Outbox feed | `config.authz.grants.allowed` admitting `read_change_feed` | none | The commit-event feed for the readers a `read_change_feed` grant in the CDR names; FerroBRIDGE delivers it to a broker. See [Change events](../beyond-core/outbox-feed.md). | -| Bearer tokens | `config.auth.issuer` | unset | The issuer tables by name, each with its `issuer` and, for an issuer whose users sign in, a `party` table; each issuer's metadata and key set are read in the background from the start, and the pod is not ready until they are; asymmetric algorithms only. | -| Party binding | `config.authz.party_binding.provider` | unset | Required once authentication admits a credential: the healthcare provider the deployment acts for. Each Basic user maps to its binding key under `config.authz.party_binding.basic_user`. | -| RBAC | `config.authz.rbac.enabled` | **on** | The coarse role gate (active while `config.auth.enabled`). | -| S3 multimedia | `config.record.multimedia.enabled` | off | ⚠ Offloaded blobs are PHI. Private, encrypted, HTTPS bucket; keys via `secrets.multimediaAccessKeyId` and `secrets.multimediaSecretAccessKey`. | -| Terminology server | `config.terminology` | off | The one FHIR terminology server, at `config.terminology.endpoint.url`. To run FerroTERM in the cluster instead, use `terminology.enabled` ([FerroTERM](#ferroterm-a-terminology-server-beside-the-cdr-off-by-default)), which sets these keys for you. | -| ATNA audit trail | `config.audit.enabled` | **on** | On with the local store only; forwarding (`config.audit.syslog`, `config.audit.fhir_feed`) is opt-in per sink. | -| Version signing | `config.record.signing.enabled` | **on** (`config.record.signing.mode: digest`) | `pgp` mode needs a `config.files` key plus `secrets.signingKeyPassphrase`, and fails closed at boot without a usable key. | -| OTLP telemetry | `config.telemetry.otlp.endpoint` | unset | Setting the endpoint is all it takes; without a `config.telemetry.otlp` table nothing is exported. With `networkPolicy.egress.enabled`, add a rule for the collector, since a blocked exporter drops spans without an error. | - -Full detail on each is in [Beyond the core](../beyond-core/index.md), -[Security](../security.md), and [Operations](../operations.md). - -The [usage report](../usage-report.md) is on by default, and -`usageReport.enabled=false` switches it off for FerroEHR, for FerroTERM and for -FerroBRIDGE. Each of those takes its own `terminology.usageReport.enabled` or -`bridge.usageReport.enabled` when you want it to differ. FerroPIX runs from its -own chart, which cannot read this chart's switch: set -`ferropix.usageReport.enabled=false` as well, or the chart refuses to render. - -### FerroEHR Viewer (a second workload, off by default) - -`viewer.enabled` renders a second Deployment and Service for the viewer -beside the CDR, from its own image -(`viewer.image.repository`, tagged `appVersion` by default so the two move -together). It is off by default: the viewer is a separate product surface with -its own attack surface, and a CDR is complete without it. - -Three properties are worth knowing before you switch it on: - -- **It reaches the CDR strictly over the REST API**, which - `viewer.networkPolicy.enabled` (on by default) *enforces* rather than - assumes: the viewer's egress admits the CDR Service, DNS and outbound HTTPS - for an identity provider, and nothing else. It holds no database credential. -- **It is a human-facing web UI**, so `viewer.ingress.enabled` is the normal way - to reach it, and `viewer.auth.oidc.enabled` with an issuer, client id and - `viewer.auth.oidc.publicBaseUrl` is how you keep a person who should not see - PHI out of it. Its client secret comes from `viewer.existingSecret`, mounted - as a file exactly as the server's DSN is. -- **`viewer.replicaCount` is 1 deliberately.** The viewer holds session state - in process, so a second replica needs sticky sessions at the ingress or users - are logged out on a reroute. - -The viewer carries the same security context as the server, and the chart's -render gate holds it to the same Restricted profile and the same pod-isolation -settings: a release whose two workloads disagreed about `hostUsers` would be a -posture nobody could state in one sentence. The deployment probe harness then -reads that back off the *running* viewer container, exactly as it does for the -server: its uid, its empty capability bounding set, its read-only root and its -seccomp filter come from the container runtime's own spec, its admission from an -`enforce=restricted` namespace, and its login page from an HTTP request made -inside the cluster through the viewer Service, so the second workload is never -vouched for by the first. What that run does **not** establish is stated in its -own record: the viewer's OIDC path, the screens behind a session, and whether a -CNI enforces the viewer's NetworkPolicy. Its screens are documented in the -[viewer](../viewer/index.md) chapter. - -### FerroPIX (the patient identity source, on by default) - -The CDR keeps no patient-to-record cross-reference of its own by default: it -asks an IHE patient identity source over PIXm (ITI-83) which pseudonym the -clinical domain holds for a patient -([`[pixm]`](config-integrations.md#pixm)). The chart takes -[FerroPIX](https://github.com/FerroHEALTH/FerroPIX) as the chart dependency -`ferropix` (`oci://ghcr.io/ferrohealth/charts`, pinned in `Chart.lock`), so -its Deployment, Service, NetworkPolicy and configuration are its own chart's, -and every key under `ferropix:` is that chart's value. With -`ferropix.enabled` (the default) the chart writes -`config.record.subject_index = "pixm"` and `config.pixm.endpoint.url` at the -FerroPIX Service, and refuses a values file that sets either too. With the -egress policy on, it adds the rule to FerroPIX's pods. - -You supply FerroPIX's PostgreSQL URL and sealing key, its issuer, the -pseudonymisation domain whose consumer is the CDR's client, and the CDR's side -of the same facts: - -```yaml -ferropix: - database: {existingSecret: ferropix-db} - dataKey: {existingSecret: ferropix-data-key} - config: - public_base_url: https://pix.example.org - auth: - issuer: - pix: {issuer: https://idp.example.org/realms/pix, audience: [https://pix.example.org/fhir]} - trust: - issuer: [{issuer: pix, clients: [hospital-source]}] - pseudonym_domain: - - {namespace: urn:oid:2.999.7.1, name: Clinical domain, consumer_client_id: ferroehr} -config: - privacy: - subject_namespaces: [urn:oid:2.999.7.1] - pixm: - assigning_authority: urn:oid:2.999.7.1 - endpoint: - credentials: - oauth: - token_endpoint: https://idp.example.org/realms/pix/protocol/openid-connect/token - client_id: ferroehr - scope: system/Patient.rs -secrets: - ehrIndexClientSecret: -``` - -`secrets.ehrIndexClientSecret` is mounted at -`/etc/ferroehr-secrets/ehr_index.oauth.client_secret`, and the chart injects -the matching `client_secret_file`; the production overlay reads it from a -Secret you own through `extraEnv` instead. Another PIX Manager: -`ferropix.enabled: false` and `config.pixm.endpoint.url`. A CDR run on its -own: `ferropix.enabled: false` and `config.record.subject_index: local`. - -The chart pins FerroPIX 0.0.44 by digest (`ferropix.image`) with the -FerroPIX chart built for it (0.5.6). Since FerroPIX 0.0.40 an -`[auth.issuer.]` entry names its `issuer` and its own `audience`, and -FerroPIX reads the caller from the standard claims of an RFC -9068 `at+jwt` access token, and a client credentials token, whose `sub` is -its `client_id`, is a machine's. It refuses `kind` (other than -`federation`), `preset` and the `profile` table, and an audience written on -the auth section itself. Since 0.0.21 a -Patient Identity Source is admitted only with a client credentials token, -and a Basic user holding a `system/` scope refuses the start. Since FerroPIX 0.0.8, `public_base_url` is a -top-level key and the clients that may act as a Patient Identity Source sit -in the `[[trust.issuer]]` table, apart from the `[auth.issuer.]` entry that -names the issuer; FerroPIX refuses the older `server.public_base_url` and `auth.issuer[].clients`, so an -upgrade from a chart that pinned FerroPIX 0.0.7 moves those two keys in your -values. Since FerroPIX 0.0.37, `config.auth.issuer` is a map of issuers by name, -and `trust.issuer[].issuer` names the issuer by that name, never by its URL. - -The restricted-profile gate holds FerroPIX's pods to the Pod Security -Standards `restricted` profile like every other pod in the release. FerroPIX's -chart sets the two properties this chart adds for its own pods itself: -`enableServiceLinks: false`, and a user namespace per pod unless FerroPIX's -own `hostUsers` value, under `ferropix:`, is `true`. - -### FerroTERM (a terminology server beside the CDR, off by default) - -[FerroTERM](https://github.com/FerroHEALTH/FerroTERM) is the Ferro family's -FHIR terminology server: R4, R4B and R5 endpoints over a precomputed index, no -JVM, no database, one distroless image. `terminology.enabled` renders it as a -third workload beside the CDR and the viewer, and points the CDR at it, so -archetype value-set bindings resolve at commit and AQL `TERMINOLOGY()` expands -through it. The CDR's own `/terminology/*` extension routes are a separate -switch: they answer only with `config.api.terminology=true`, which is -`false` by default, and return `404` otherwise whether or not FerroTERM is -running. It is the Helm equivalent of the -[compose terminology overlay](compose.md#the-terminology-overlay-ferroterm). - -```shell -helm upgrade --install ferroehr oci://ghcr.io/ferrohealth/charts/ferroehr \ - --version 43.0.1 -n ferroehr --reuse-values \ - --set terminology.enabled=true -``` - -That renders a Deployment, a ClusterIP Service, its own ServiceAccount, a -ConfigMap holding the code systems, and a NetworkPolicy. It also writes three -two things into the CDR's `ferroehr.toml`: `config.terminology.on_error` from -`terminology.failOnError`, and `config.terminology.endpoint.url` at the -Service address. - -Because the chart writes those two, a values file that contradicts either is -refused at render rather than silently overwritten. Two shapes are refused -while `terminology.wireCdr` is on: - -- **`config.terminology.endpoint.url`** — two answers to "which server resolves a - binding" is how resolution ends up pointed somewhere nobody chose. -- **`config.terminology.on_error`** disagreeing with - `terminology.failOnError` — same reason, for the posture that decides whether - an unresolvable binding is a `422`. - -Set `terminology.wireCdr=false` to keep your own server and run FerroTERM -unwired. The CDR asks one terminology server, so a server of your own and the -in-cluster FerroTERM are an either-or. - -**No Ingress is rendered, and no value renders one.** The CDR is the only -caller, which is the posture the [hosted sandbox](https://sandbox.ferroehr.eu) -runs and what the SNOMED CT Affiliate Licence asks of a public deployment: -clause 2.2.4 permits a public system to serve SNOMED-encoded data provided users -cannot extract a substantial portion of the release and no fee is charged, and -clause 2.7 requires measures so the release cannot be downloaded except by -authorised users. A published FHIR terminology endpoint answers `$expand` and -`$lookup` to every client that reaches it, and FerroTERM has neither -authentication nor a rate limit of its own. Its NetworkPolicy is therefore the -one in this chart that narrows sources by default: ingress admits the CDR's pods -on the terminology port and nothing else, egress admits DNS. -`terminology.networkPolicy.extraIngressFrom` adds a peer you decide to admit. -**No boolean opens this port** the way `networkPolicy.ingressAllowAll` opens the -CDR's — and a peer you add is admitted exactly as written, which includes -admitting everything: a `namespaceSelector: {}` selects every namespace in the -cluster (networking/v1: "if present but empty, it selects all namespaces"). The -values schema therefore refuses an empty peer, and an empty `podSelector` or -`namespaceSelector` inside one, so reaching that state takes labels you chose -rather than a blank. - -**Out of the box it serves the shaped seed**, which is synthetic content under -the reserved `example.test` domain: two code systems and two value sets, the -same content the conformance lane binds to. The chart carries those files and -mounts them as a ConfigMap, so a fresh install from the registry serves -terminology with no repository checkout. -`terminology.codeSystems.existingConfigMap` swaps in a ConfigMap of your own FHIR -JSON. No licensed terminology ships with FerroEHR or FerroTERM. One caveat with -a ConfigMap of your own: the pod's rollout annotation hashes the chart's own seed -files and the NAME you gave, not the contents of an object the chart does not -own, so editing that ConfigMap updates the volume while the running pods keep -serving what they read at boot. Restart the workload after such an edit -(`kubectl rollout restart deployment/ferroehr-terminology`). - -**A real release is an index you build off-cluster.** Run -`ferroterm-build --rf2 --out ` on a machine that holds the -archive, put the output on a PersistentVolume, and name that claim in -`terminology.index.persistentVolumeClaim`. The chart mounts it **read-only** at -`terminology.index.mountPath` and sets `FERROTERM__TERMINOLOGY__INDEX`; with no claim named, -the variable is absent and the seed is served alone. The chart provisions no -storage and renders no build Job, for the same reason it provisions no database: -unpacking a licensed archive is a step whose licence terms are yours, not a step -a chart should start on its own. - -Naming a claim also switches this Deployment to `strategy: Recreate`. A rolling -update creates the replacement pod before the outgoing one goes away, and a -`ReadWriteOnce` volume can only be attached by one node, so the new pod would -sit Pending on the attachment while `kubectl` reported a progressing rollout. -Recreate stops the old pods first, which costs a short terminology outage at -every upgrade and finishes. If your index volume is `ReadOnlyMany`, override it -with `terminology.strategy={type: RollingUpdate}`. FerroTERM's -[loading page](https://ferroterm.eu/docs/operate/loading-snomed.html) covers the -other code systems and their build flags. Size the memory limit for the edition -before you mount it: `terminology.resources` ships a 1536Mi limit, and the same -FerroTERM page states the resident size of each edition, which the limit must -cover. - -**The fail posture is the CDR's shipped one.** `terminology.failOnError` -defaults to `false`, so a binding the server cannot resolve is accepted; `true` -turns an unreachable terminology server into a `422` refusal. The -[terminology page](../beyond-core/terminology.md#when-the-terminology-server-cannot-answer) -explains both. A code the server resolves as outside its value set is refused -with `422` under either posture. - -**FerroTERM's licence.** BUSL-1.1 from the same Licensor as FerroEHR: -non-commercial production use is free, any other production use needs a -commercial licence. Its README says which is which. The licence for whatever -code systems you load is separate and yours to hold; SNOMED CT needs an -Affiliate Licence (free in Member countries, see -[snomed.org/get-snomed](https://www.snomed.org/get-snomed)), and every surface -showing its content carries the notice clause 8.3.1 prescribes plus the release -version and date. - -**More than one replica needs two other keys.** `terminology.replicaCount` is a -throughput choice — each replica loads its own copy of the index, so watch the -memory limit — and above 1 the pods spread one per node by default, the same -soft constraint the CDR gets. Turn `terminology.podDisruptionBudget.enabled` on -with it: without a budget a node drain may take every terminology replica at -once, and the CDR's own budget does not cover these pods. It is off by default -because the shipped replica count is 1 and a budget over a single pod blocks the -drain it exists to survive. - -FerroTERM carries the same security context as the CDR and the viewer, and the -chart's render gate holds all three to the same Restricted profile. The -deployment probe harness reads this workload back off a running cluster too: its -applied runtime posture, the shaped seed reaching the process from the ConfigMap -volume, a refusal on the terminology port from a pod the policy does not name, -and the CDR resolving a bound code through the Service. Its image is -pinned by digest in `terminology.image.digest` and moves on FerroTERM's own -release line, so it does not follow `appVersion` the way the viewer image does. -Because that digest is set, `terminology.image.tag` alone deploys nothing: the -digest wins, and a tag pointing anywhere else is refused at render rather than -ignored. Clear the digest to deploy by tag. - -### FerroBRIDGE (the FHIR bridge, off by default) - -[FerroBRIDGE](https://github.com/FerroHEALTH/FerroBRIDGE) maps between FHIR R4 -and openEHR with FHIRconnect mappings and reaches FerroEHR over ITS-REST. -FerroEHR itself serves no FHIR API for clinical data, so FerroBRIDGE is the -component that does. `bridge.enabled` renders it as its own workload in the same -release: a Deployment, a ClusterIP Service, its own ServiceAccount, a ConfigMap -holding its configuration file, and a NetworkPolicy. - -The chart writes three sections of that file for you: - -- **`[cdr.endpoint]`:** `url` is this release's CDR Service with its REST base - path (`http://:`), and - `[cdr.endpoint.credentials.oauth]` names the client of `bridge.cdr.oauth` and - its secret, a file mounted from your Secret. -- **`[terminology]`:** with `terminology.enabled` on, `endpoint.url` is the - chart's FerroTERM Service at `/r4` and `wire_version` is `r4`. With it off the - section is absent, and you may set your own under `bridge.config`. -- **`[mappings]`:** `directory` is where the mapping files below are mounted. - -**FerroBRIDGE reaches the CDR as a machine.** It obtains and renews a token -with the OAuth 2.0 client credentials grant (RFC 6749 §4.4) from an issuer -the CDR trusts, and the CDR checks it as it checks every token. A Basic -user is a person and holds no `system/` scope, so the chart has no Basic mode. -Add the issuer to `config.auth.issuer`, name -FerroBRIDGE's client in `bridge.cdr.oauth`, and, when it commits what -`$toopenehr` maps, grant the client in the CDR: an `AGENT` carrying its -`client_id` and performing a `ROLE` that grants `commit_composition`, as -[A system client](../operational-policy.md#a-system-client) shows. The -render is refused when `bridge.cdr.oauth.issuer` is not an issuer of -`config.auth.issuer`. FerroBRIDGE reads the token endpoint from that issuer's -metadata; when the authorization server serves none there, set -`bridge.cdr.oauth.tokenEndpoint`, and `issuer` still names the issuer the CDR -trusts. - -```yaml -config: - auth: - issuer: - - issuer: https://idp.example.org/realms/machines - audience: [ferroehr-machines] -bridge: - cdr: - existingSecret: ferroehr-bridge-cdr - oauth: - issuer: https://idp.example.org/realms/machines - clientId: ferrobridge - scope: system/composition-*.cruds system/template-*.r system/aql-*.rs - audience: ferroehr-machines -``` - -**The client secret comes from a Secret you create.** The chart never takes it -as a value. The Secret carries the key `client_secret`, which is mounted as a -file and named by `client_secret_file`, so it is in neither the ConfigMap nor -the environment. - -```shell -kubectl -n ferroehr create secret generic ferroehr-bridge-cdr \ - --from-file=client_secret=./bridge-client-secret -``` - -**The mapping files come from a ConfigMap you create**, named in -`bridge.mappings.existingConfigMap`, with each key listed in -`bridge.mappings.files`. The chart mounts every key on its own: a whole -ConfigMap volume also carries the kubelet's `..data` snapshot directories, and -FerroBRIDGE reads those as a second and third copy of every file and -refuses the start with a duplicate mapping name. FerroBRIDGE fetches each -template a mapping context names from the CDR at boot, so upload the templates -first; a template the CDR does not hold stops the start. Without a mapping set -FerroBRIDGE still starts, and `$tofhir` and `$toopenehr` answer `503`. - -**A mapping set needs `[auth]`.** With mappings FerroBRIDGE serves its -FHIRconnect operations, and it refuses to start them until FerroBRIDGE's -`[auth]` keys `issuer` and `audience`, set under `bridge.config`, name the -authorization server whose tokens its callers present, or until its `enabled` -is `false`, which serves them to every caller the NetworkPolicy admits. The keys are FerroBRIDGE's own -([configuration reference](https://ferrobridge.eu/docs/operate/configuration.html)). - -```yaml -bridge: - enabled: true - cdr: - existingSecret: ferroehr-bridge-cdr - oauth: - issuer: https://idp.example.org/realms/machines - clientId: ferrobridge - mappings: - existingConfigMap: ferroehr-bridge-mappings - files: - - vital_signs.context.yml - - blood_pressure.yml - config: - auth: - issuer: - callers: - issuer: https://idp.example.org - audience: [https://bridge.example.org/fhir] - networkPolicy: - ingressFrom: - - podSelector: - matchLabels: - app.kubernetes.io/name: my-fhir-client -``` - -**It stays inside the cluster.** A caller FerroBRIDGE admits acts on the CDR -under the client above. So the chart -renders no Ingress for it and no value renders one, the Service is always -ClusterIP, and the NetworkPolicy admits only the peers you list in -`bridge.networkPolicy.ingressFrom`. An empty list is refused at render, and the -values schema refuses a peer that selects everything (an empty peer, or an empty -`podSelector` or `namespaceSelector` inside one). There is no key that admits -every source. Egress admits this release's CDR, FerroTERM when it runs, and -DNS; `bridge.networkPolicy.extraEgress` adds a rule for an upstream you name in -`bridge.config`. When you narrow the CDR's own `networkPolicy.ingressFrom`, the -chart adds FerroBRIDGE's pods to it, and FerroTERM's policy admits them too. - -**Anything else goes in `bridge.config`**, rendered into the same file with -the keys of FerroBRIDGE's -[configuration reference](https://ferrobridge.eu/docs/operate/configuration.html). -FerroBRIDGE refuses an unknown key at boot. The render refuses a key the chart -writes (`cdr.endpoint`, `server.listen`, `terminology` while -FerroTERM runs, `mappings.directory` while the chart mounts the mappings) and -any secret-shaped key, such as a password, a token or `cdm.url`: set its -`_file` sibling and mount the file with `bridge.extraVolumes` and -`bridge.extraVolumeMounts`. FerroBRIDGE's FHIR facade (`[facade]`) keeps its -identity map in a file it writes, and the root filesystem is read-only, so -turning the facade on also takes a PersistentVolumeClaim of yours mounted with -those two keys and named in `facade.identity_store`, with -`bridge.strategy={type: Recreate}` when the claim is ReadWriteOnce. Back that -volume up with the CDR's database. - -Probes use FerroBRIDGE's own endpoints: liveness `/health/liveness`, readiness -`/health/readiness`, which answers `503` while the CDR or FerroTERM is -unreachable. FerroBRIDGE carries the same security context as the other -workloads and the release-wide `hostUsers` setting, and the render gate holds -it to the same Restricted profile. Its image is pinned by digest in -`bridge.image.digest` and moves on FerroBRIDGE's own release line, never with -`appVersion`; a tag other than the pin is refused while the digest is set. The -deployment probe harness boots it on a cluster and reads back its runtime -posture, its admission, the credential being used for the template fetch, a -refusal on its port from a pod outside `ingressFrom`, and its readiness from a -pod inside it. FerroBRIDGE's own deployment documentation is at -. - -### Per-domain backups (one CronJob per domain, off by default) - -`backup.enabled` renders one CronJob per pseudonymisation domain: -`backup.clinical.schedule` dumps the clinical schemas, `backup.party.schedule` -dumps the identities, and each writes to its own existing claim -(`backup.clinical.persistentVolumeClaim`, `backup.party.persistentVolumeClaim`). -The image is `backup.image.repository`, which carries `pg_dump`. - -**A third job renders for the audit domain when `database.audit.existingSecret` -gives it a database of its own.** While the trail shares the clinical database -the clinical dump names its schema and nothing more is needed; once it is -somewhere else, that dump cannot reach it and nothing else would take it, so -`backup.audit.schedule`, `backup.audit.existingSecret` and -`backup.audit.persistentVolumeClaim` become required the same way the other -two are, and the clinical dump stops naming the `audit` schema. - -The chart refuses to render rather than let the separation collapse quietly: a -missing claim is an error naming the value, and naming the **same** claim for -any two domains is an error too, because one volume holding the clinical record -beside the identities is the state per-domain backups exist to prevent. - -Each job needs **its own backup credential**, named by -`backup.clinical.existingSecret`, `backup.party.existingSecret` and, when it -renders, -`backup.audit.existingSecret`, and -the render is refused without them. It cannot be the pool's credential: each -domain's runtime role is revoked from the other domains, so a dump taken through -one would be silently partial. Give each domain a read-only role on that -domain's schema alone. Every job reads its DSN from a mounted file, never an -environment variable. - -The chart provisions no storage. Create the claims yourself, and give them -different access control; that part no chart can do for you. The restore -procedure, and the `ferroehr db verify` gate that judges it, are on the -[Operating](../operations.md) page. - ## Staying available while things move Five defaults keep the API serving through the events that routinely interrupt @@ -1361,72 +556,3 @@ inter-zone cost, at the price of even load, so measure before setting it. And `autoscaling.behavior` passes scaling policies straight through; the documented defaults already scale up immediately and wait out a five-minute stabilization window before scaling down, so change it only to be *more* conservative. - -## Upgrades - -Migrations are **append-only** (a schema change is a new file, never an edit to -an applied one) so a rolling upgrade stays compatible with the previous schema -during the window where both versions run: additive DDL first, destructive -changes in a later release once all pods are on the new version. Keep -`replicaCount` at two or more (or `autoscaling.enabled`) and the default -PodDisruptionBudget so upgrades and node drains never fully interrupt the API; -the default `terminationGracePeriodSeconds` covers the binary's shutdown drain. -Roll back by re-pinning the prior image tag or digest. - -The step from v5 to v6 is the exception: v6 starts from a new migration -baseline and needs a new, empty database, so it is a new installation with the -records moved by archive dump and load -([Operations → Upgrading from v5 to v6](../operations.md#upgrading-from-v5-to-v6)). - -A change anywhere under `config`, `config.files` or `secrets` changes the -`checksum/config` pod annotation, so `helm upgrade` rolls the pods for a -configuration-only change too, including a rotated secret or an edited -mounted file, both of which are read at boot and would otherwise reach the volume while -every running pod kept using the old value. - -`helm uninstall` removes everything the chart created; the chart declares no -PersistentVolumeClaim, so nothing is left behind; your database, and the Secret -holding its DSN, are yours and survive. - -Preview an upgrade against what you have installed with -`helm diff`, or render the new chart version and read it: - -```shell -helm template ferroehr oci://ghcr.io/ferrohealth/charts/ferroehr --version 43.0.1 \ - -n ferroehr -f my-values.yaml | less -``` - -Working from a checkout instead, `deploy/helm/validate.sh` runs the chart's full -render gate: the helm-version pin, lint, YAML validity, the structural -Restricted-profile and selector-immutability gates, the secret-leak gate, the -values-schema probes, and the golden-render diff. It is the same gate CI runs on -every change to the chart, so a local run and a pull request agree by -construction. - -### Check your values before you deploy them - -A render that lints is not a deployment that boots. `validate.sh` never runs the -server, so it cannot see a configuration the server refuses: a missing -authentication mechanism, an `HS*` algorithm, a password hash that is not a -real Argon2id PHC string, SMART enabled without its public base URL. Every one of those renders perfectly and crash-loops the pod. The -script prints exactly which properties it does not check, on success as well as -on failure, so a green run is not mistaken for a working deployment. - -The check that closes that gap runs the image against your rendered -configuration: - -```shell -FERROEHR_IMAGE=ghcr.io/ferrohealth/ferroehr:5.7.1-rc1 \ - deploy/helm/ci/boot-check.sh my-values.yaml -``` - -It renders the chart, mounts the ConfigMap and the Secret exactly as the -Deployment does (with their real values, not placeholders) replays the -declared environment, and runs `ferroehr config check` inside the image. Point -`FERROEHR_IMAGE` at the tag you intend to deploy: the answer is specific to that -image, since a key your values carry may be newer than the server that has to -read it. - -It validates configuration only; it opens no socket, so it cannot tell you the -issuer resolves, the broker is reachable or the database accepts the DSN. CI -runs the same script over every values overlay the chart ships. diff --git a/website/book/src/installation/party-binding-migration.md b/website/book/src/installation/party-binding-migration.md index 84f5667a07..7f2f2f0c8a 100644 --- a/website/book/src/installation/party-binding-migration.md +++ b/website/book/src/installation/party-binding-migration.md @@ -5,7 +5,7 @@ login with no `PERSON` is refused (`403`, `refused-unbound`). This page takes a new deployment from an empty database to its first bound login, and takes an existing deployment, whose people were attributed by login alone, to binding. The configuration it names is in -[Authentication & access](config-auth.md#the-party-mapping), and the two +[Authentication & access](config-authz.md#the-party-mapping), and the two commands are in [CLI & production checklist](config-cli.md). No openEHR specification governs a deployment's migration or its @@ -175,9 +175,5 @@ committer rule. | Product | What it needs | Release | |---|---|---| -| FerroBRIDGE | Writes to the CDR under the facade caller's exchanged token (FerroHEALTH/FerroBRIDGE#1582) | FerroBRIDGE v0.0.23 | -| FerroFED | The gateway reaches the CDR under the caller (FerroHEALTH/FerroFED#1615) | none as of FerroFED v0.0.19; the issue's FerroFED milestone is v0.0.20 | - -No FerroFED release up to v0.0.19 reaches the CDR under the caller, so a -deployment with a FerroFED gateway adds its `persons` issuers only once a -FerroFED release carries that change (FerroHEALTH/FerroFED#1615). +| FerroBRIDGE | Writes to the CDR under the facade caller's exchanged token | FerroBRIDGE v0.0.23 or later | +| FerroFED | The gateway reaches the CDR under the caller | FerroFED v0.0.20 or later | diff --git a/website/book/src/introduction.md b/website/book/src/introduction.md index 08fe0bc369..d670d3a40a 100644 --- a/website/book/src/introduction.md +++ b/website/book/src/introduction.md @@ -1,100 +1,25 @@ # Introduction -FerroEHR is a pure-Rust [openEHR](https://www.openehr.org/) Clinical Data -Repository (CDR): a headless, API-first server that stores and queries -structured health records through a vendor-neutral REST API and the Archetype -Query Language. This book is the user-facing guide — how to run it, configure -it, talk to its API, query it, and load the templates that give your data -shape. If you build clinical applications, operate healthcare infrastructure, -or are evaluating an openEHR back end, you are in the right place. - -The name comes from *ferrum*, Latin for iron: Rust is iron oxide, so the -project went straight to the element. Say it "FER-ro-E-H-R". - -## What openEHR gives you - -openEHR separates *clinical knowledge* from *software*. The structure and -meaning of clinical data — a blood-pressure reading, a medication order, a -discharge summary — live in shared, computable models called archetypes and -templates, authored by clinicians and modellers rather than baked into -application code. Applications then store and retrieve that data through a -standard API, against a shared Reference Model, so the same record is portable -across every conformant system. - -FerroEHR implements that standard natively. It speaks the openEHR **REST API** -(ITS-REST Release-1.1.0), executes **Archetype Query Language (AQL 1.1)**, and -holds data as canonical openEHR compositions with full, indelible version -history. There is no proprietary data format in the middle: what you commit is -what you query and what you read back. - -## What makes this implementation different - -- **Conformance you can run yourself.** The openEHR conformance catalogue is - executed by a committed runner against a live server, over both canonical - JSON and canonical XML, and every row it judges cites the specification - text it reads. The run record lives in the repository, and every number - on the [Conformance](conformance.md) page is derived from them at build time, - never hand-typed. -- **The openEHR specifications, generated** directly from the official - machine-readable models: the Reference Model, the Archetype Model (1.4 and - 2.4), the serialization schemas, and the REST API contract (Release-1.1.0). - openEHR's own published terminology (3.1) ships embedded, byte-identical to - upstream. A specification update is a regeneration. -- **Two selectable specification generations.** One configuration key, - `spec_profile`, chooses the whole generation set the server runs: - `development` (Reference Model 1.2.0 with BASE 1.3.0, the default) or - `stable` (the latest *released* generations, Reference Model 1.1.0 with - BASE 1.2.0). See - [`spec_profile`](installation/configuration.md#deploymentspec_profile). -- **One self-contained binary.** No JVM, no language runtime, and a pure-Rust - TLS stack, so there is nothing to provision beside PostgreSQL. The container - image is shell-less and runs as non-root. -- **PostgreSQL 19-native storage.** Clinical documents are decomposed into an - indexed node model with time-bounded, versioned rows; canonical openEHR JSON - is stored verbatim so storage and API never disagree. - -## How the system is layered - -FerroEHR is built in two layers. A **specification layer** is generated -deterministically from openEHR's published models: the Reference Model types, -canonical JSON/XML serialization, the REST contract, and the AQL front end. On -top of it sits the **application**: the server, the PostgreSQL-native storage, -the AQL execution engine, validation, and security. The -[System architecture](concepts/architecture.md) chapter walks through this in -user terms; if you are new to openEHR itself, start with the -[openEHR primer](concepts/openehr-primer.md). - -## Where to go next - -- **Wondering why this exists?** [Why FerroEHR exists](why-ferroehr.md) is the - project's position: what openEHR is worth, what we commit to, what the - licence lets you do, how building a product on it works, and why - contributing back pays. -- **Just want to try it?** [Getting started](getting-started.md) takes you from - `docker compose up` to a stored composition and an AQL result in a few - minutes. -- **Deploying it?** [Installation](installation/index.md) covers Docker - Compose, Kubernetes/Helm, building from source, and the - [configuration reference](installation/configuration.md); - [Operations](operations.md) covers running it afterwards. -- **Integrating an application?** [Using the API](using-the-api/index.md) and - [Querying with AQL](querying-aql.md) are the core reference for client - developers. -- **Modelling clinical data?** [Templates & validation](templates-validation.md) - explains how templates drive what the server will accept. -- **Reviewing it for a deployment?** [Security](security.md) - and the [Threat model](threat-model.md) state what is enforced and what is - yours to enforce; the [FerroEHR Viewer](viewer/index.md) is the optional web - UI over the same public API. - -> [!NOTE] -> FerroEHR began as a fork of **EHRbase** (by vitasystems and the Peter L. -> Reichertz Institute) and records that lineage in the labelled import commit -> at the root of its history, but it is an -> independent, from-scratch Rust implementation with no EHRbase code in this -> tree, and it is not affiliated with or endorsed by the EHRbase project. -> FerroEHR's own code is source-available under the Business Source License -> 1.1; vendored openEHR material keeps its upstream terms: Apache-2.0 for the -> machine-readable artifacts, CC-BY-SA 3.0 for the specification text, and -> CC-BY-SA 3.0 and 4.0 for the clinical models (see -> [Licensing & legal](licensing.md)). +FerroEHR is an [openEHR](https://www.openehr.org/) Clinical Data Repository +(CDR) written in Rust. It is a headless server: it stores structured health +records in PostgreSQL and serves them through the openEHR REST API (ITS-REST +Release-1.1.0) and the Archetype Query Language (AQL 1.1). What you commit is +canonical openEHR, and every version is kept. + +The book has four kinds of page: tutorials to learn by doing, how-to guides for +one task each, reference to look things up, and explanation to understand how +the parts fit. Start from what you are here to do. + +| You are | Start with | Then | +|---|---|---| +| **An integrator** building on the API | [Getting started](getting-started.md), then [Your first integration](tutorials/first-integration.md) | [Using the API](using-the-api/index.md), [Querying with AQL](querying-aql.md), [Templates & validation](templates-validation.md), [Problem types](using-the-api/problems.md) | +| **A clinician-facing app builder** launching apps for patients and professionals | [SMART App Launch](smart-app-launch.md) | [How FerroEHR decides access](explanation/access-model.md), [Behind FerroSMART](behind-ferrosmart.md), [The xShare Yellow Button](xshare-yellow-button.md) | +| **An operator** running it in production | [Installation](installation/index.md) | [Configuration reference](installation/configuration.md), [Operations](operations.md), [Go-live checklist](security/go-live-checklist.md), [Operational policy](operational-policy.md) | +| **A decision maker** evaluating it | [Why FerroEHR exists](why-ferroehr.md) | [System architecture](concepts/architecture.md), [How FerroEHR decides access](explanation/access-model.md), [Conformance](conformance.md), [Compliance overview](compliance/index.md) | + +New to openEHR? Read the [openEHR primer](concepts/openehr-primer.md) first. +The [FerroEHR Viewer](viewer/index.md) is an optional web UI over the same +public API. Licensing, lineage and trademarks are on +[Licensing & legal](licensing.md). + +The name comes from *ferrum*, Latin for iron. Say it "FER-ro-E-H-R". diff --git a/website/book/src/licensing.md b/website/book/src/licensing.md index 4ad7344d37..fb201c0d57 100644 --- a/website/book/src/licensing.md +++ b/website/book/src/licensing.md @@ -76,7 +76,7 @@ only. `LICENSES/MIT.txt` reproduces that grant as those versions carry it, Ruben Talstra's copyright line included, because a published grant is a record of what was handed out and is not rewritten afterwards. -The conformance instrument is no longer part of this repository. It is +The conformance instrument is [Veredictum](https://github.com/Vernum-Projecten/Veredictum), an independent project under Apache-2.0, and the conformance pipeline here consumes it at a pinned version. The vendored test corpora this repository still carries keep @@ -129,12 +129,12 @@ used as test corpora. Each family keeps its upstream license: | The normative ADL, cADL, ODIN, BEL and Expression-Language ANTLR grammars | `openEHR/adl-antlr`, `openEHR/openEHR-antlr4` | [Apache-2.0](https://github.com/FerroHEALTH/FerroEHR/blob/main/LICENSES/Apache-2.0.txt) | | openEHR specification text (the conformance reference) | the openEHR `specifications-*` repositories | [CC-BY-SA 3.0](https://github.com/FerroHEALTH/FerroEHR/blob/main/LICENSES/CC-BY-SA-3.0.txt) | | The AQL grammar and the computable terminology assets (the terminology XML the server embeds, and its schemas) | `specifications-QUERY`, `specifications-TERM` | [CC-BY-SA 3.0](https://github.com/FerroHEALTH/FerroEHR/blob/main/LICENSES/CC-BY-SA-3.0.txt) | -| Clinical models (archetypes and templates) from the openEHR Clinical Knowledge Manager | ckm.openehr.org | per-file `licence` metadata — a **mix** of [CC-BY-SA 4.0](https://github.com/FerroHEALTH/FerroEHR/blob/main/LICENSES/CC-BY-SA-4.0.txt) and [CC-BY-SA 3.0](https://github.com/FerroHEALTH/FerroEHR/blob/main/LICENSES/CC-BY-SA-3.0.txt) | -| The ADL 2 archetype library, with its ADL 1.4 twins (the shared corpus) | `openEHR/adl-archetypes` | **no stated licence** — see below | +| Clinical models (archetypes and templates) from the openEHR Clinical Knowledge Manager | ckm.openehr.org | per-file `licence` metadata: a **mix** of [CC-BY-SA 4.0](https://github.com/FerroHEALTH/FerroEHR/blob/main/LICENSES/CC-BY-SA-4.0.txt) and [CC-BY-SA 3.0](https://github.com/FerroHEALTH/FerroEHR/blob/main/LICENSES/CC-BY-SA-3.0.txt) | +| The ADL 2 archetype library, with its ADL 1.4 twins (the shared corpus) | `openEHR/adl-archetypes` | **no stated licence**; see below | | The ADL 2 validator-regression library (the `openehr-adl` corpus) | `openEHR/adl-archetypes`, a different subtree | mixed: mostly **unstated**, else [CC-BY-SA 3.0](https://github.com/FerroHEALTH/FerroEHR/blob/main/LICENSES/CC-BY-SA-3.0.txt), [CC-BY 4.0](https://github.com/FerroHEALTH/FerroEHR/blob/main/LICENSES/CC-BY-4.0.txt) or [CC-BY 3.0](https://github.com/FerroHEALTH/FerroEHR/blob/main/LICENSES/CC-BY-3.0.txt) | | Test corpora (archie fixtures and reference models, Better `web-template-tests`, EHRbase SDK canonical-JSON data) | Nedap, Better Ltd, vitasystems | Apache-2.0 | -| Three ISO 13606 / rejected-extract BMM reference models inside the archie corpus | offered by their authors under MPL 1.1 / GPL 2.0 / LGPL 2.1 | taken under [MPL 1.1](https://github.com/FerroHEALTH/FerroEHR/blob/main/LICENSES/MPL-1.1.txt) — see the election below | -| One terminology schema file, `PropertyUnitData.xsd` | ADL Designer / ADL2-tools, via the openEHR TERM assets | [AGPL-3.0-only](https://github.com/FerroHEALTH/FerroEHR/blob/main/LICENSES/AGPL-3.0-only.txt) — see the contradiction below | +| Three ISO 13606 / rejected-extract BMM reference models inside the archie corpus | offered by their authors under MPL 1.1 / GPL 2.0 / LGPL 2.1 | taken under [MPL 1.1](https://github.com/FerroHEALTH/FerroEHR/blob/main/LICENSES/MPL-1.1.txt); see the election below | +| One terminology schema file, `PropertyUnitData.xsd` | ADL Designer / ADL2-tools, via the openEHR TERM assets | [AGPL-3.0-only](https://github.com/FerroHEALTH/FerroEHR/blob/main/LICENSES/AGPL-3.0-only.txt); see the contradiction below | | The self-hosted KaTeX stylesheet and fonts this documentation site renders maths with | KaTeX contributors | MIT | | The Mermaid bundle this documentation site draws its diagrams with, `website/book/theme/mermaid.min.js` | `mermaid-js/mermaid` 11.6.0, Knut Sveidqvist | [MIT](https://github.com/FerroHEALTH/FerroEHR/blob/main/LICENSES/MIT.txt) | | The diagram loader of the documentation site, `website/book/theme/mermaid-init.js` | `badboy/mdbook-mermaid`, Jan-Erik Rediger | [MPL 2.0](https://github.com/FerroHEALTH/FerroEHR/blob/main/LICENSES/MPL-2.0.txt) | @@ -200,7 +200,7 @@ material already survives being copied out of the repository. **The ADL 2 archetype library states no licence at all**, and this is the one tree here that carries no grant. Measured on 2026-09-10 over the vendored copy (`openEHR/adl-archetypes` at the pinned commit): of 652 archetypes, exactly one -states a licence — and it states CC-BY 4.0, not CC-BY-SA — while the other 651 +states a licence (and it states CC-BY 4.0, not CC-BY-SA) while the other 651 carry `copyright = <"© openEHR Foundation">` and nothing more. Upstream states nothing either: no `LICENSE` file at that commit, and a four-line `README.md`. @@ -255,7 +255,7 @@ So licensing is **also** published in the machine-readable form the - **[`LICENSES/`](https://github.com/FerroHEALTH/FerroEHR/tree/main/LICENSES)** holds the full text of every license any file in the tree is offered under, named by SPDX identifier: `BUSL-1.1`, `MIT`, `Apache-2.0`, `CC-BY-SA-3.0`, - `CC-BY-SA-4.0`, `CC-BY-4.0`, `CC-BY-3.0`, `MPL-1.1`, `MPL-2.0`, `AGPL-3.0-only` — plus + `CC-BY-SA-4.0`, `CC-BY-4.0`, `CC-BY-3.0`, `MPL-1.1`, `MPL-2.0`, `AGPL-3.0-only`, plus `LicenseRef-openEHR-unstated`, which is not a licence but the record that one tree carries none. - **[`REUSE.toml`](https://github.com/FerroHEALTH/FerroEHR/blob/main/REUSE.toml)** diff --git a/website/book/src/operational-policy.md b/website/book/src/operational-policy.md index 505b98ec82..7ed93dfb9d 100644 --- a/website/book/src/operational-policy.md +++ b/website/book/src/operational-policy.md @@ -14,7 +14,7 @@ federation partner and the privileges a professional holds beyond clinical access, is openEHR demographic data in the party store: the [policy parties](#the-policy-parties), managed through the Demographic API, with every change a version with its committer. Policy that has no home in -the openEHR demographic model is an [admin register](#the-admin-registers). +the openEHR demographic model is an [admin register](access-policy.md#the-admin-registers). FerroEHR stores, validates and protects the policy parties, and every request resolves its caller's grants from them before any check runs. The checks that decide on a grant are listed under @@ -223,11 +223,11 @@ own in it, which the change request does not propose. A `CAPABILITY` grants an o | `scim_provision` | Provision Users and Groups over SCIM, owning the binding keys of the grant's `binding_issuer` | | `hold_roles` | Hold, as a Basic user, the roles its `role` elements name | | `hold_scopes` | Hold, as a Basic user, the SMART scopes its `scope` elements name | -| `create_at_login` | Create a provisional `PERSON` at the first login of a person no party carries, under the admission conditions the grant names ([Just-in-time admission](#just-in-time-admission)) | +| `create_at_login` | Create a provisional `PERSON` at the first login of a person no party carries, under the admission conditions the grant names ([Just-in-time admission](policy-examples.md#just-in-time-admission)) | | `query_system_wide` | Count the client's `system/aql-*` scope, which reaches every query over every EHR (SMART on openEHR, master08 §Resource Scopes) | | `access_demographic` | Reach the DEMOGRAPHIC API, which no SMART on openEHR scope covers | | `write_care_relationship` | Write the membership (`member_of`) and `under_care_of` care relationships through the Demographic API, as a hospital's ADT system does ([The access control terminology](#the-access-control-terminology)) | -| `write_representation` | Write a representation (`represents`) through the Demographic API, for the providers its `provider` elements name ([Representatives](#representatives)) | +| `write_representation` | Write a representation (`represents`) through the Demographic API, for the providers its `provider` elements name ([Representatives](caller-facts.md#representatives)) | | `write_access_policy` | Write the controller's `ACCESS_POLICY` | The same terminology names the elements that qualify a grant, by the code @@ -257,8 +257,8 @@ in the element's `name`: | `provider` | On `write_care_relationship` and `write_representation`: a `DV_IDENTIFIER` (its `issuer` and `id`) naming a provider whose care relationships and memberships, or representations, the grant writes; none named means none written | | `target_kind` | On `write_care_relationship`: `PERSON`, `ROLE`, `GROUP` or `ORGANISATION`, a kind of care relationship target the grant writes; none named means none written | | `acts_for` | On a `PARTY_RELATIONSHIP`: the source acts for the target | -| `represents` | On a `PARTY_RELATIONSHIP`: the source represents the target, the subject, on the subject's own record ([Representatives](#representatives)); it makes no policy party | -| `role` | A `DV_TEXT`: a role a `hold_roles` grant gives, or a role code a `scim_provision` grant lets its client assign its Users ([SCIM roles](installation/config-auth.md#roles)) | +| `represents` | On a `PARTY_RELATIONSHIP`: the source represents the target, the subject, on the subject's own record ([Representatives](caller-facts.md#representatives)); it makes no policy party | +| `role` | A `DV_TEXT`: a role a `hold_roles` grant gives, or a role code a `scim_provision` grant lets its client assign its Users ([SCIM roles](installation/config-scim.md#roles)) | | `scope` | A `DV_TEXT`: a SMART scope a `hold_scopes` grant gives | | `login_issuer` | A text or `DV_URI`: a token issuer whose first logins a `create_at_login` grant admits | | `admit_idp` | A text: an identity provider an admitted login comes from | @@ -351,11 +351,11 @@ design. | `access caller kind` | `professional`, `access_service`, `datasubject` of `HL7_SecurityRoleType` (the subject), `representative`, `system` | `ACCESS_ACTOR_SCOPE.caller_kind`. An `access_service` caller is one holding the `access_service` grant | | `access operation` | `read`, `write`, `export`, `query` | `ACCESS_DIRECTIVE.operations`: the operation classes a directive applies to. No capability grants one | | `care relationship` | `member_of`, `under_care_of` | The `name` or `details` of a `PARTY_RELATIONSHIP`: with `member_of`, the source, a professional's `PERSON`, is a member of the target, a care-team `GROUP`, or the source, a provider `ORGANISATION`, is a member of the target `GROUP`; with `under_care_of`, the source, a patient's `PERSON`, is under the care of the target, a team `GROUP` or an organisational unit | -| `representation` | `represents` | The `name` of a `PARTY_RELATIONSHIP` of its own: the source represents the target, the subject ([Representatives](#representatives)) | +| `representation` | `represents` | The `name` of a `PARTY_RELATIONSHIP` of its own: the source represents the target, the subject ([Representatives](caller-facts.md#representatives)) | | `representation element` | `basis`, `provider`, `evidence` | The `name` of an `ELEMENT` in the `details` of a `represents` relationship | -| `kinship`, `kinship element` | `related_to`; `kinship` | The `name` or `details` of a `PARTY_RELATIONSHIP` of its own: its source and target, two `PERSON`s, are kin, and its `kinship` element codes how ([Exclusions and conflicts of interest](#exclusions-and-conflicts-of-interest)) | +| `kinship`, `kinship element` | `related_to`; `kinship` | The `name` or `details` of a `PARTY_RELATIONSHIP` of its own: its source and target, two `PERSON`s, are kin, and its `kinship` element codes how ([Exclusions and conflicts of interest](access-policy.md#exclusions-and-conflicts-of-interest)) | | `client identifier` | `client_id` | The `name` of an `ELEMENT` holding a `DV_IDENTIFIER` in an `ACTOR`'s `details` or `identities`: the identifier is the OAuth 2.0 client the actor is ([Who acts](#how-a-request-reads-its-grants)) | -| `group kind` | `care_team` | The `name` of a `GROUP`: the `GROUP` is a care team ([Care teams provisioned over SCIM](#care-teams-provisioned-over-scim)) | +| `group kind` | `care_team` | The `name` of a `GROUP`: the `GROUP` is a care team ([Care teams provisioned over SCIM](caller-facts.md#care-teams-provisioned-over-scim)) | | `access refusal` | `refused-opt-out`, `refused-restricted`, `refused-consent-denied`, `refused-policy-denied`, `refused-sensitivity`, `refused-confidentiality`, `refused-no-care-relationship`, `refused-outside-episode`, `refused-purpose-missing`, `refused-consent-required`, `refused-not-subject`, `refused-not-represented`, `refused-consent-reference-missing`, `refused-excluded`, `refused-conflict` | The access record of a refusal | | `access log withheld` | `accessor_party`, `accessor_provider`, `accessor_roles`, `accessor_groups` | `ACCESS_LOG_RESTRICTION.withheld`: the accessor members the access log's subject view withholds under EHDS Art. 9(3) | @@ -374,7 +374,7 @@ restriction or an opt-out is not visible to the caller (EHDS Art. 8). Every other refusal answers `403` and names its code. The access record of every refusal names its code, the step that refused and the directive or policy of that step, and the record of an admitted access names the grounds it rested -on ([The openEHR access-log entry](audit.md#the-openehr-access-log-entry)). +on ([The openEHR access-log entry](access-log.md#the-openehr-access-log-entry)). ### What the grants decide @@ -461,7 +461,7 @@ under its `commit_composition` grants and exports under its caller outside the administrator role that holds a `read_subject_audit` grant, for one subject at a time: the `patient` parameter names exactly one subject, and without it the call is `403` -([Audit trail](audit.md#retrieving-audit-records-iti-81)). +([Audit trail](audit-integrity.md#retrieving-audit-records-iti-81)). **Acting as an access service.** A caller with an `access_service` grant is an EHDS Art. 10 access service: an EHR whose person opted out reads as @@ -470,7 +470,7 @@ emergency justification of the access policy with a reason and acts for no person (Art. 10(2)). While `[authz.grants] allowed` does not allow `access_service`, recording an opt-out is refused with `422`, since it would hold for nobody -([Opt-out from the access services](security.md#opt-out-from-the-access-services-ehds-art-10)). +([Opt-out from the access services](access-control.md#opt-out-from-the-access-services-ehds-art-10)). A role a token names never grants any of these four: each comes from its grant alone, under the grant ceiling. The privileged role of @@ -720,7 +720,7 @@ or, with none, for the deployment's `[authz.party_binding] provider`. A `COMPOSI server never writes the facility. A composer that names an `ORGANISATION` is `422`: the composer is a person. -Which templates a client commits is a [controller rule](#controller-rules), +Which templates a client commits is a [controller rule](access-policy.md#controller-rules), as it is for every other caller: a deny rule whose `applies_to` names the client's `AGENT`, with a permit exception listing the templates it may write. @@ -851,788 +851,6 @@ credentials at `/capabilities[id6]/credentials[id8]`, and its `time_validity` th | `ROLE.privileged` | Kind (privilege) | `at10` subject audit, `at11` access service, `at13` import, `at14` compose for (`1.0.1`); `1.0.0` also lists `at12` identifier reader, which grants nothing | | | `ROLE.privileged` | Not before, not after, authorisation reference | `/capabilities[id6]/credentials[id8]/items[id9]`, `[id10]`, `[id11]` | `DV_DATE_TIME`, `DV_DATE_TIME`, `DV_TEXT` | -### Worked examples - -The examples use the base path `/ferroehr/rest/openehr/v1`, send -`Content-Type: application/json` and `Prefer: return=representation`, and -run as an administrator. The party ids are examples: use the ids your -server returns in the `Location` header and the body. - -The provider this instance acts for is an `ORGANISATION` named -`9d2f4a7e-3c1b-4e8a-9f60-2b7d5c8e1a40`, and the federation partner below is -the `ORGANISATION` `7c4e9a2b-1f6d-4b3e-9c8a-5d2e0f7b1a36`. The default set's -healthcare provider `ORGANISATION` (`openEHR-DEMOGRAPHIC-ORGANISATION.healthcare_provider.v1.0.0`, -on [Default demographic definitions](installation/default-demographic-definitions.md)) -records both, identified by their provider identifier. Neither is a policy -party, so any demographic writer may create them. - -#### A system client - -A laboratory relay commits laboratory results into EHRs at one facility. -First its `AGENT`, `POST /demographic/agent`: - - -```json -{ - "_type": "AGENT", - "archetype_node_id": "openEHR-DEMOGRAPHIC-AGENT.system.v1", - "archetype_details": { - "_type": "ARCHETYPED", - "archetype_id": { "_type": "ARCHETYPE_ID", "value": "openEHR-DEMOGRAPHIC-AGENT.system.v1" }, - "template_id": { "_type": "TEMPLATE_ID", "value": "openEHR-DEMOGRAPHIC-AGENT.system.v1.0.0" }, - "rm_version": "1.1.0" - }, - "name": { "_type": "DV_TEXT", "value": "System agent" }, - "details": { - "_type": "ITEM_TREE", "archetype_node_id": "id2", "name": { "_type": "DV_TEXT", "value": "Identifiers" }, - "items": [{ - "_type": "ELEMENT", "archetype_node_id": "id3", - "name": { - "_type": "DV_CODED_TEXT", "value": "client_id", - "defining_code": { - "_type": "CODE_PHRASE", - "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, - "code_string": "client_id" - } - }, - "value": { - "_type": "DV_IDENTIFIER", - "issuer": "https://login.example.org/machines", - "id": "lab-relay", - "type": "client_id" - } - }] - }, - "identities": [{ - "_type": "PARTY_IDENTITY", "archetype_node_id": "id4", "name": { "_type": "DV_TEXT", "value": "Name" }, - "details": { - "_type": "ITEM_TREE", "archetype_node_id": "id5", "name": { "_type": "DV_TEXT", "value": "Items" }, - "items": [{ - "_type": "ELEMENT", "archetype_node_id": "id6", "name": { "_type": "DV_TEXT", "value": "Name" }, - "value": { "_type": "DV_TEXT", "value": "Laboratory relay" } - }] - } - }] -} -``` - -Its grant is a `ROLE` it performs, `POST /demographic/role`, with the -`AGENT` `5b8e2c91-7d4a-4f3e-8a1c-6e9f0b2d4c73` the first call returned as -`performer`. Its capability grants `commit_composition` with the origin -`relay`, the template it writes and the facility it writes at, each element -named by its `openehr_access` code. A system that also registers -device measurements holds a second capability with the origin `device` and -its `device_identifier_issuer`. - - -```json -{ - "_type": "ROLE", - "archetype_node_id": "openEHR-DEMOGRAPHIC-ROLE.system_client.v1", - "archetype_details": { - "_type": "ARCHETYPED", - "archetype_id": { "_type": "ARCHETYPE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.system_client.v1" }, - "template_id": { "_type": "TEMPLATE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.system_client.v1.0.0" }, - "rm_version": "1.1.0" - }, - "name": { "_type": "DV_TEXT", "value": "System client" }, - "identities": [{ - "_type": "PARTY_IDENTITY", "archetype_node_id": "id2", "name": { "_type": "DV_TEXT", "value": "Role name" }, - "details": { - "_type": "ITEM_TREE", "archetype_node_id": "id3", "name": { "_type": "DV_TEXT", "value": "Name" }, - "items": [{ - "_type": "ELEMENT", "archetype_node_id": "id4", "name": { "_type": "DV_TEXT", "value": "Full name" }, - "value": { "_type": "DV_TEXT", "value": "Laboratory relay writes" } - }] - } - }], - "performer": { - "_type": "PARTY_REF", "namespace": "demographic", "type": "AGENT", - "id": { "_type": "HIER_OBJECT_ID", "value": "5b8e2c91-7d4a-4f3e-8a1c-6e9f0b2d4c73" } - }, - "time_validity": { - "_type": "DV_INTERVAL", - "lower": { "_type": "DV_DATE", "value": "2026-12-01" }, - "lower_unbounded": false, "upper_unbounded": true, - "lower_included": true, "upper_included": false - }, - "capabilities": [{ - "_type": "CAPABILITY", "archetype_node_id": "id6", "name": { "_type": "DV_TEXT", "value": "Relay" }, - "credentials": { - "_type": "ITEM_TREE", "archetype_node_id": "id8", "name": { "_type": "DV_TEXT", "value": "Grant" }, - "items": [ - { - "_type": "ELEMENT", "archetype_node_id": "id90", "name": { "_type": "DV_TEXT", "value": "Operation" }, - "value": { "_type": "DV_CODED_TEXT", "value": "Commit composition", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "commit_composition" } } - }, - { - "_type": "ELEMENT", "archetype_node_id": "id18", - "name": { "_type": "DV_CODED_TEXT", "value": "Origin", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "origin" } }, - "value": { "_type": "DV_CODED_TEXT", "value": "Relay", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "relay" } } - }, - { - "_type": "ELEMENT", "archetype_node_id": "id9", - "name": { "_type": "DV_CODED_TEXT", "value": "Template written", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "template" } }, - "value": { "_type": "DV_TEXT", "value": "openEHR-EHR-COMPOSITION.report-result.v1" } - }, - { - "_type": "CLUSTER", "archetype_node_id": "id10", - "name": { "_type": "DV_CODED_TEXT", "value": "Facility", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "facility" } }, - "items": [ - { - "_type": "ELEMENT", "archetype_node_id": "id11", - "name": { "_type": "DV_CODED_TEXT", "value": "Issuer", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "issuer" } }, - "value": { "_type": "DV_TEXT", "value": "urn:oid:2.16.528.1.1007.3.3" } - }, - { - "_type": "ELEMENT", "archetype_node_id": "id12", - "name": { "_type": "DV_CODED_TEXT", "value": "Identifier", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "identifier" } }, - "value": { "_type": "DV_TEXT", "value": "01234567" } - } - ] - } - ] - } - }] -} -``` - -Then a new version of the `AGENT`, `PUT /demographic/agent/{uid}` with the -`If-Match` of its version, that names the `ROLE` it performs and the -provider it acts for. A relationship is stored in its source party, and the -`AGENT`'s id exists only once the first call returns, so the acts-for -relationship goes in this second version. - - -```json -{ - "_type": "AGENT", - "archetype_node_id": "openEHR-DEMOGRAPHIC-AGENT.system.v1", - "archetype_details": { - "_type": "ARCHETYPED", - "archetype_id": { "_type": "ARCHETYPE_ID", "value": "openEHR-DEMOGRAPHIC-AGENT.system.v1" }, - "template_id": { "_type": "TEMPLATE_ID", "value": "openEHR-DEMOGRAPHIC-AGENT.system.v1.0.0" }, - "rm_version": "1.1.0" - }, - "name": { "_type": "DV_TEXT", "value": "System agent" }, - "details": { - "_type": "ITEM_TREE", "archetype_node_id": "id2", "name": { "_type": "DV_TEXT", "value": "Identifiers" }, - "items": [{ - "_type": "ELEMENT", "archetype_node_id": "id3", - "name": { - "_type": "DV_CODED_TEXT", "value": "client_id", - "defining_code": { - "_type": "CODE_PHRASE", - "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, - "code_string": "client_id" - } - }, - "value": { - "_type": "DV_IDENTIFIER", - "issuer": "https://login.example.org/machines", - "id": "lab-relay", - "type": "client_id" - } - }] - }, - "identities": [{ - "_type": "PARTY_IDENTITY", "archetype_node_id": "id4", "name": { "_type": "DV_TEXT", "value": "Name" }, - "details": { - "_type": "ITEM_TREE", "archetype_node_id": "id5", "name": { "_type": "DV_TEXT", "value": "Items" }, - "items": [{ - "_type": "ELEMENT", "archetype_node_id": "id6", "name": { "_type": "DV_TEXT", "value": "Name" }, - "value": { "_type": "DV_TEXT", "value": "Laboratory relay" } - }] - } - }], - "roles": [{ - "_type": "PARTY_REF", "namespace": "demographic", "type": "ROLE", - "id": { "_type": "HIER_OBJECT_ID", "value": "e41c7b2a-6d3f-4a9e-8b05-2f7d1c9e3a68" } - }], - "relationships": [{ - "_type": "PARTY_RELATIONSHIP", - "archetype_node_id": "openEHR-DEMOGRAPHIC-PARTY_RELATIONSHIP.acts_for.v1", - "name": { - "_type": "DV_CODED_TEXT", "value": "Acts for", - "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "local" }, "code_string": "at10" } - }, - "details": { - "_type": "ITEM_TREE", "archetype_node_id": "id3", "name": { "_type": "DV_TEXT", "value": "Details" }, - "items": [{ - "_type": "ELEMENT", "archetype_node_id": "id6", "name": { "_type": "DV_TEXT", "value": "Acts-for code" }, - "value": { - "_type": "DV_CODED_TEXT", "value": "Acts for", - "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "acts_for" } - } - }] - }, - "source": { - "_type": "PARTY_REF", "namespace": "demographic", "type": "AGENT", - "id": { "_type": "HIER_OBJECT_ID", "value": "5b8e2c91-7d4a-4f3e-8a1c-6e9f0b2d4c73" } - }, - "target": { - "_type": "PARTY_REF", "namespace": "demographic", "type": "ORGANISATION", - "id": { "_type": "HIER_OBJECT_ID", "value": "9d2f4a7e-3c1b-4e8a-9f60-2b7d5c8e1a40" } - } - }] -} -``` - -#### A backend client and a demographic client - -A reporting job queries every EHR with a `system/aql-*` scope, and a master -patient index reads and writes persons through the DEMOGRAPHIC API. Neither -is a key in `ferroehr.toml`: each is a grant of the client's `AGENT`, read on -every request. A `system/aql-*` scope "would grant access to all registered -and ad-hoc AQL queries system-wide" (SMART on openEHR, master08 §Resource -Scopes), so it counts only for a client granted `query_system_wide`; no -SMART on openEHR scope covers demographic data, so the DEMOGRAPHIC API admits -a client granted `access_demographic`, or a caller holding the -`[auth] product_scope`. - -Both operations reach beyond one system's own writes, so the ceiling admits -each by name: - -```toml -[authz.grants] -allowed = ["commit_composition", "query_system_wide", "access_demographic"] -``` - -The client's `AGENT` is written as above, and its grant is a `ROLE` it -performs, `POST /demographic/role`. One `ROLE` can carry both operations; a -deployment that runs the two as separate clients gives each its own `AGENT` -and `ROLE`. - - -```json -{ - "_type": "ROLE", - "archetype_node_id": "openEHR-DEMOGRAPHIC-ROLE.system_client.v1", - "archetype_details": { - "_type": "ARCHETYPED", - "archetype_id": { "_type": "ARCHETYPE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.system_client.v1" }, - "template_id": { "_type": "TEMPLATE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.system_client.v1.0.0" }, - "rm_version": "1.1.0" - }, - "name": { "_type": "DV_TEXT", "value": "System client" }, - "identities": [{ - "_type": "PARTY_IDENTITY", "archetype_node_id": "id2", "name": { "_type": "DV_TEXT", "value": "Role name" }, - "details": { - "_type": "ITEM_TREE", "archetype_node_id": "id3", "name": { "_type": "DV_TEXT", "value": "Name" }, - "items": [{ - "_type": "ELEMENT", "archetype_node_id": "id4", "name": { "_type": "DV_TEXT", "value": "Full name" }, - "value": { "_type": "DV_TEXT", "value": "Reporting and patient index" } - }] - } - }], - "performer": { - "_type": "PARTY_REF", "namespace": "demographic", "type": "AGENT", - "id": { "_type": "HIER_OBJECT_ID", "value": "5b8e2c91-7d4a-4f3e-8a1c-6e9f0b2d4c73" } - }, - "capabilities": [{ - "_type": "CAPABILITY", "archetype_node_id": "id6", "name": { "_type": "DV_TEXT", "value": "Reporting" }, - "credentials": { - "_type": "ITEM_TREE", "archetype_node_id": "id8", "name": { "_type": "DV_TEXT", "value": "Grant" }, - "items": [ - { - "_type": "ELEMENT", "archetype_node_id": "id90", "name": { "_type": "DV_TEXT", "value": "Operation" }, - "value": { - "_type": "DV_CODED_TEXT", "value": "Query system-wide", - "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "query_system_wide" } - } - }, - { - "_type": "ELEMENT", "archetype_node_id": "id90", "name": { "_type": "DV_TEXT", "value": "Operation" }, - "value": { - "_type": "DV_CODED_TEXT", "value": "Access demographic", - "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "access_demographic" } - } - } - ] - } - }] -} -``` - -The client's next request runs under the grant, on every replica, with no -restart. The grant counts for the client's own client credentials token, -whose `client_id` the `AGENT` carries. A person signed in -through the same client holds the person's own grants, never the client's. -To withdraw it, end the `ROLE`'s `time_validity` or delete the `ROLE` -([Ending a grant](#ending-a-grant)). - -#### A migration - -A migration is a system client like any other: its `AGENT` is written as -above, and its `ROLE` holds the import and export operations. Here a job -imports the EHRs of a legacy system and its extracts over one night, and may -export them again to check the result. The capability's `time_validity` -holds the migration to two days, `Not before` and `Not after` narrow it to -the night between them, and `subject_namespace` limits it to the legacy -system's patients. `[authz.grants] allowed` must admit `import_ehr`, -`import_ehr_extract` and `export_ehr_extract`. - - -```json -{ - "_type": "ROLE", - "archetype_node_id": "openEHR-DEMOGRAPHIC-ROLE.system_client.v1", - "archetype_details": { - "_type": "ARCHETYPED", - "archetype_id": { "_type": "ARCHETYPE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.system_client.v1" }, - "template_id": { "_type": "TEMPLATE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.system_client.v1.0.0" }, - "rm_version": "1.1.0" - }, - "name": { "_type": "DV_TEXT", "value": "System client" }, - "identities": [{ - "_type": "PARTY_IDENTITY", "archetype_node_id": "id2", "name": { "_type": "DV_TEXT", "value": "Role name" }, - "details": { - "_type": "ITEM_TREE", "archetype_node_id": "id3", "name": { "_type": "DV_TEXT", "value": "Name" }, - "items": [{ - "_type": "ELEMENT", "archetype_node_id": "id4", "name": { "_type": "DV_TEXT", "value": "Full name" }, - "value": { "_type": "DV_TEXT", "value": "Legacy HIS migration" } - }] - } - }], - "performer": { - "_type": "PARTY_REF", "namespace": "demographic", "type": "AGENT", - "id": { "_type": "HIER_OBJECT_ID", "value": "5b8e2c91-7d4a-4f3e-8a1c-6e9f0b2d4c73" } - }, - "capabilities": [{ - "_type": "CAPABILITY", "archetype_node_id": "id6", "name": { "_type": "DV_TEXT", "value": "Migration" }, - "time_validity": { - "_type": "DV_INTERVAL", - "lower": { "_type": "DV_DATE", "value": "2026-12-05" }, - "upper": { "_type": "DV_DATE", "value": "2026-12-06" }, - "lower_unbounded": false, "upper_unbounded": false, - "lower_included": true, "upper_included": true - }, - "credentials": { - "_type": "ITEM_TREE", "archetype_node_id": "id8", "name": { "_type": "DV_TEXT", "value": "Grant" }, - "items": [ - { - "_type": "ELEMENT", "archetype_node_id": "id90", "name": { "_type": "DV_TEXT", "value": "Operation" }, - "value": { "_type": "DV_CODED_TEXT", "value": "Import EHR", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "import_ehr" } } - }, - { - "_type": "ELEMENT", "archetype_node_id": "id90", "name": { "_type": "DV_TEXT", "value": "Operation" }, - "value": { "_type": "DV_CODED_TEXT", "value": "Import EHR extract", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "import_ehr_extract" } } - }, - { - "_type": "ELEMENT", "archetype_node_id": "id90", "name": { "_type": "DV_TEXT", "value": "Operation" }, - "value": { "_type": "DV_CODED_TEXT", "value": "Export EHR extract", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "export_ehr_extract" } } - }, - { - "_type": "ELEMENT", "archetype_node_id": "id19", - "name": { "_type": "DV_CODED_TEXT", "value": "Subject namespace", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "subject_namespace" } }, - "value": { "_type": "DV_TEXT", "value": "nl.legacy-his.patients" } - }, - { - "_type": "ELEMENT", "archetype_node_id": "id15", - "name": { "_type": "DV_CODED_TEXT", "value": "Not before", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "not_before" } }, - "value": { "_type": "DV_DATE_TIME", "value": "2026-12-05T22:00:00Z" } - }, - { - "_type": "ELEMENT", "archetype_node_id": "id16", - "name": { "_type": "DV_CODED_TEXT", "value": "Not after", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "not_after" } }, - "value": { "_type": "DV_DATE_TIME", "value": "2026-12-06T05:00:00Z" } - }, - { - "_type": "ELEMENT", "archetype_node_id": "id17", "name": { "_type": "DV_TEXT", "value": "Authorisation reference" }, - "value": { "_type": "DV_TEXT", "value": "CHG-2026-1182" } - } - ] - } - }] -} -``` - -The job then calls `POST /message/import` (`message_import_ehr`) and -`POST /message/import/{ehr_id}` (`message_import_ehr_extract`) with its own -token, and `POST /message/export` to read the result back. Each -import is committed under the job's `ACTOR` and is an access record that names -it and the provider it acts for. The versions of an extract keep their legacy -committers when a `creating_system` element of the grant names the legacy -system's `creating_system_id`; otherwise an extract naming a local party is -refused. -When the night ends the grant holds no longer, with no change to anything. - -#### A federation partner - -A partner organisation's professionals read patient summaries under a -data-sharing agreement. The partner is an `ORGANISATION` that carries a -client identifier for each client its `federation` issuer issues tokens to: -an `ELEMENT` in its `details` named `openehr_access::client_id` whose value -is, for example, `{ "_type": "DV_IDENTIFIER", "issuer": -"https://federation.example", "id": "remote-portal" }`. Committing it is an -administrator's write, because the element makes it a policy party. The agreement is a `ROLE` of the -federation partner template the partner performs, with one capability per -accessor, here `person`. Each term is an element whose `name` is its -`openehr_access` code, which is how FerroEHR reads it in any archetype -(see [Federation agreements](#federation-agreements)). - - -```json -{ - "_type": "ROLE", - "archetype_node_id": "openEHR-DEMOGRAPHIC-ROLE.federation_partner.v1", - "archetype_details": { - "_type": "ARCHETYPED", - "archetype_id": { "_type": "ARCHETYPE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.federation_partner.v1" }, - "template_id": { "_type": "TEMPLATE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.federation_partner.v1.0.0" }, - "rm_version": "1.1.0" - }, - "name": { "_type": "DV_TEXT", "value": "Federation partner" }, - "identities": [{ - "_type": "PARTY_IDENTITY", "archetype_node_id": "id2", "name": { "_type": "DV_TEXT", "value": "Role name" }, - "details": { - "_type": "ITEM_TREE", "archetype_node_id": "id3", "name": { "_type": "DV_TEXT", "value": "Name" }, - "items": [{ - "_type": "ELEMENT", "archetype_node_id": "id4", "name": { "_type": "DV_TEXT", "value": "Full name" }, - "value": { "_type": "DV_TEXT", "value": "Regional care network" } - }] - } - }], - "performer": { - "_type": "PARTY_REF", "namespace": "demographic", "type": "ORGANISATION", - "id": { "_type": "HIER_OBJECT_ID", "value": "7c4e9a2b-1f6d-4b3e-9c8a-5d2e0f7b1a36" } - }, - "time_validity": { - "_type": "DV_INTERVAL", - "lower": { "_type": "DV_DATE", "value": "2026-01-01" }, - "upper": { "_type": "DV_DATE", "value": "2036-12-31" }, - "lower_unbounded": false, "upper_unbounded": false, - "lower_included": true, "upper_included": true - }, - "capabilities": [{ - "_type": "CAPABILITY", "archetype_node_id": "id6", - "name": { - "_type": "DV_CODED_TEXT", "value": "Person", - "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "local" }, "code_string": "at10" } - }, - "credentials": { - "_type": "ITEM_TREE", "archetype_node_id": "id8", "name": { "_type": "DV_TEXT", "value": "Grant" }, - "items": [ - { - "_type": "ELEMENT", "archetype_node_id": "id90", "name": { "_type": "DV_TEXT", "value": "Operation" }, - "value": { "_type": "DV_CODED_TEXT", "value": "Federated person access", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "federated_person_access" } } - }, - { - "_type": "ELEMENT", "archetype_node_id": "id9", - "name": { "_type": "DV_CODED_TEXT", "value": "Agreement name", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "agreement_name" } }, - "value": { "_type": "DV_TEXT", "value": "Regional care network exchange" } - }, - { - "_type": "ELEMENT", "archetype_node_id": "id10", - "name": { "_type": "DV_CODED_TEXT", "value": "Agreement version", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "agreement_version" } }, - "value": { "_type": "DV_TEXT", "value": "2.1" } - }, - { - "_type": "ELEMENT", "archetype_node_id": "id12", - "name": { "_type": "DV_CODED_TEXT", "value": "Exchange", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "exchange" } }, - "value": { "_type": "DV_TEXT", "value": "patient summary" } - }, - { - "_type": "ELEMENT", "archetype_node_id": "id13", - "name": { "_type": "DV_CODED_TEXT", "value": "Purpose", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "purpose" } }, - "value": { "_type": "DV_CODED_TEXT", "value": "treatment", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "HL7_ActReason" }, "code_string": "TREAT" } } - }, - { - "_type": "CLUSTER", "archetype_node_id": "id14", "name": { "_type": "DV_TEXT", "value": "Legal ground" }, - "items": [ - { - "_type": "ELEMENT", "archetype_node_id": "id15", - "name": { "_type": "DV_CODED_TEXT", "value": "GDPR Article 6(1) point", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "gdpr_art_6_1" } }, - "value": { "_type": "DV_TEXT", "value": "e" } - }, - { - "_type": "ELEMENT", "archetype_node_id": "id16", - "name": { "_type": "DV_CODED_TEXT", "value": "GDPR Article 9(2) point", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "gdpr_art_9_2" } }, - "value": { "_type": "DV_TEXT", "value": "h" } - }, - { - "_type": "ELEMENT", "archetype_node_id": "id17", - "name": { "_type": "DV_CODED_TEXT", "value": "National provision", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "national_provision" } }, - "value": { "_type": "DV_TEXT", "value": "the provision the agreement names" } - } - ] - }, - { - "_type": "ELEMENT", "archetype_node_id": "id18", - "name": { "_type": "DV_CODED_TEXT", "value": "Consent source", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "consent" } }, - "value": { "_type": "DV_CODED_TEXT", "value": "Local", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "local" } } - }, - { - "_type": "ELEMENT", "archetype_node_id": "id19", - "name": { "_type": "DV_CODED_TEXT", "value": "Read scope", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "read_scope" } }, - "value": { "_type": "DV_TEXT", "value": "patient/composition-openEHR-EHR-COMPOSITION.patient_summary.v1.r" } - }, - { - "_type": "CLUSTER", "archetype_node_id": "id24", "name": { "_type": "DV_TEXT", "value": "Caller rate" }, - "items": [ - { - "_type": "ELEMENT", "archetype_node_id": "id25", - "name": { "_type": "DV_CODED_TEXT", "value": "Requests per second", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "requests_per_second" } }, - "value": { "_type": "DV_COUNT", "magnitude": 5 } - }, - { - "_type": "ELEMENT", "archetype_node_id": "id26", - "name": { "_type": "DV_CODED_TEXT", "value": "Burst", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "burst" } }, - "value": { "_type": "DV_COUNT", "magnitude": 20 } - } - ] - } - ] - } - }] -} -``` - -#### A privileged role - -A professional covers a colleague's access-log reviews for one week. The -grant is a `ROLE` of the privileged template performed by the professional's -`PERSON` `3e7a1d5c-9b2f-4c8e-a6d0-1f4b8e2c7a95`, with one capability per -privilege, here `subject audit`. The privileged role never grants the -administrator role or emergency access: the identity provider and the -configuration grant those. - - -```json -{ - "_type": "ROLE", - "archetype_node_id": "openEHR-DEMOGRAPHIC-ROLE.privileged.v1", - "archetype_details": { - "_type": "ARCHETYPED", - "archetype_id": { "_type": "ARCHETYPE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.privileged.v1" }, - "template_id": { "_type": "TEMPLATE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.privileged.v1.0.0" }, - "rm_version": "1.1.0" - }, - "name": { "_type": "DV_TEXT", "value": "Privileged role" }, - "identities": [{ - "_type": "PARTY_IDENTITY", "archetype_node_id": "id2", "name": { "_type": "DV_TEXT", "value": "Role name" }, - "details": { - "_type": "ITEM_TREE", "archetype_node_id": "id3", "name": { "_type": "DV_TEXT", "value": "Name" }, - "items": [{ - "_type": "ELEMENT", "archetype_node_id": "id4", "name": { "_type": "DV_TEXT", "value": "Full name" }, - "value": { "_type": "DV_TEXT", "value": "Access log review cover" } - }] - } - }], - "performer": { - "_type": "PARTY_REF", "namespace": "demographic", "type": "PERSON", - "id": { "_type": "HIER_OBJECT_ID", "value": "3e7a1d5c-9b2f-4c8e-a6d0-1f4b8e2c7a95" } - }, - "capabilities": [{ - "_type": "CAPABILITY", "archetype_node_id": "id6", - "name": { - "_type": "DV_CODED_TEXT", "value": "Subject audit", - "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "local" }, "code_string": "at10" } - }, - "time_validity": { - "_type": "DV_INTERVAL", - "lower": { "_type": "DV_DATE", "value": "2026-12-07" }, - "upper": { "_type": "DV_DATE", "value": "2026-12-13" }, - "lower_unbounded": false, "upper_unbounded": false, - "lower_included": true, "upper_included": true - }, - "credentials": { - "_type": "ITEM_TREE", "archetype_node_id": "id8", "name": { "_type": "DV_TEXT", "value": "Grant" }, - "items": [ - { - "_type": "ELEMENT", "archetype_node_id": "id90", "name": { "_type": "DV_TEXT", "value": "Operation" }, - "value": { - "_type": "DV_CODED_TEXT", "value": "Read subject audit", - "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "read_subject_audit" } - } - }, - { - "_type": "ELEMENT", "archetype_node_id": "id11", "name": { "_type": "DV_TEXT", "value": "Authorisation reference" }, - "value": { "_type": "DV_TEXT", "value": "Cover for the privacy officer, approved by the CMIO" } - }] - } - }] -} -``` - -#### A scribe composing for physicians - -A scribe records the notes the physicians of the same provider dictate. The -grant is a `ROLE` of the privileged template, version `1.0.1`, whose kind -`at14` is `Compose for`, performed by the scribe's `PERSON` -`3e7a1d5c-9b2f-4c8e-a6d0-1f4b8e2c7a95`. Each `COMPOSITION` the scribe -commits names the physician as its composer, and the committer is the scribe. - - -```json -{ - "_type": "ROLE", - "archetype_node_id": "openEHR-DEMOGRAPHIC-ROLE.privileged.v1", - "archetype_details": { - "_type": "ARCHETYPED", - "archetype_id": { "_type": "ARCHETYPE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.privileged.v1" }, - "template_id": { "_type": "TEMPLATE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.privileged.v1.0.1" }, - "rm_version": "1.1.0" - }, - "name": { "_type": "DV_TEXT", "value": "Privileged role" }, - "identities": [{ - "_type": "PARTY_IDENTITY", "archetype_node_id": "id2", "name": { "_type": "DV_TEXT", "value": "Role name" }, - "details": { - "_type": "ITEM_TREE", "archetype_node_id": "id3", "name": { "_type": "DV_TEXT", "value": "Name" }, - "items": [{ - "_type": "ELEMENT", "archetype_node_id": "id4", "name": { "_type": "DV_TEXT", "value": "Full name" }, - "value": { "_type": "DV_TEXT", "value": "Medical scribe" } - }] - } - }], - "performer": { - "_type": "PARTY_REF", "namespace": "demographic", "type": "PERSON", - "id": { "_type": "HIER_OBJECT_ID", "value": "3e7a1d5c-9b2f-4c8e-a6d0-1f4b8e2c7a95" } - }, - "capabilities": [{ - "_type": "CAPABILITY", "archetype_node_id": "id6", - "name": { - "_type": "DV_CODED_TEXT", "value": "Compose for", - "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "local" }, "code_string": "at14" } - }, - "credentials": { - "_type": "ITEM_TREE", "archetype_node_id": "id8", "name": { "_type": "DV_TEXT", "value": "Grant" }, - "items": [{ - "_type": "ELEMENT", "archetype_node_id": "id90", "name": { "_type": "DV_TEXT", "value": "Operation" }, - "value": { - "_type": "DV_CODED_TEXT", "value": "Compose for", - "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "compose_for" } - } - }] - } - }] -} -``` - -Allow the operation by name: `[authz.grants] allowed = ["commit_composition", "compose_for"]`. - -#### Just-in-time admission - -A first login of a person no party carries creates a provisional `PERSON` -only when a `create_at_login` grant admits it. The grant is a `ROLE` like -any other, and FerroEHR reads it on every first login, whoever performs the -`ROLE`: here the provider `ORGANISATION` performs it, which reads as "the -hospital admits its own staff". Its capability names the issuer by -`login_issuer` and declares the admission conditions: - -- `admit_idp`: the identity providers whose logins are created, read from - the issuer's `[[authz.party_binding.issuer]] idp_claim` (`idp` by - default); -- `admit_group`: the groups, read from the `group_claim` of the issuer's - party table, one of which an admitted login holds; -- `admit_role`: the roles, read from `[auth] role_claims`, one of which an - admitted login holds; -- `admit_assurance`: the lowest `[authz.assurance]` level an admitted login - carries. - -A login is admitted when it meets every condition the grant declares; each -list admits any one of its values. Several grants in force admit a login -when any one of them does. A grant names at least one `login_issuer` and -at least one of `admit_idp`, `admit_group`, `admit_role` and -`admit_assurance`, so no grant admits every login of an issuer: a grant -without a condition is refused with `422`, as is an element whose value -does not read. `[authz.grants] allowed` must list `create_at_login`, which -the default does not. - -The provider admits the logins of its Microsoft Entra tenant from members of -one group at assurance substantial or above, from 1 December 2026, -`POST /demographic/role`: - - -```json -{ - "_type": "ROLE", - "archetype_node_id": "openEHR-DEMOGRAPHIC-ROLE.login_admission.v1", - "archetype_details": { - "_type": "ARCHETYPED", - "archetype_id": { "_type": "ARCHETYPE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.login_admission.v1" }, - "rm_version": "1.1.0" - }, - "name": { "_type": "DV_TEXT", "value": "Login admission" }, - "identities": [{ - "_type": "PARTY_IDENTITY", "archetype_node_id": "at0001", "name": { "_type": "DV_TEXT", "value": "Role name" }, - "details": { - "_type": "ITEM_TREE", "archetype_node_id": "at0002", "name": { "_type": "DV_TEXT", "value": "Name" }, - "items": [{ - "_type": "ELEMENT", "archetype_node_id": "at0003", "name": { "_type": "DV_TEXT", "value": "Full name" }, - "value": { "_type": "DV_TEXT", "value": "Staff first login" } - }] - } - }], - "performer": { - "_type": "PARTY_REF", "namespace": "demographic", "type": "ORGANISATION", - "id": { "_type": "HIER_OBJECT_ID", "value": "9d2f4a7e-3c1b-4e8a-9f60-2b7d5c8e1a40" } - }, - "time_validity": { - "_type": "DV_INTERVAL", - "lower": { "_type": "DV_DATE", "value": "2026-12-01" }, - "lower_unbounded": false, "upper_unbounded": true, - "lower_included": true, "upper_included": false - }, - "capabilities": [{ - "_type": "CAPABILITY", "archetype_node_id": "at0010", "name": { "_type": "DV_TEXT", "value": "Admission" }, - "credentials": { - "_type": "ITEM_TREE", "archetype_node_id": "at0011", "name": { "_type": "DV_TEXT", "value": "Terms" }, - "items": [ - { - "_type": "ELEMENT", "archetype_node_id": "at0012", "name": { "_type": "DV_TEXT", "value": "Operation" }, - "value": { - "_type": "DV_CODED_TEXT", "value": "Create at login", - "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "create_at_login" } - } - }, - { - "_type": "ELEMENT", "archetype_node_id": "at0013", - "name": { - "_type": "DV_CODED_TEXT", "value": "Login issuer", - "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "login_issuer" } - }, - "value": { "_type": "DV_URI", "value": "https://login.microsoftonline.com/0f1e2d3c-4b5a-4968-8776-655443322110/v2.0" } - }, - { - "_type": "ELEMENT", "archetype_node_id": "at0014", - "name": { - "_type": "DV_CODED_TEXT", "value": "Admitted group", - "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "admit_group" } - }, - "value": { "_type": "DV_TEXT", "value": "5f2a9c1e-0000-4000-8000-00000000c11a" } - }, - { - "_type": "ELEMENT", "archetype_node_id": "at0015", - "name": { - "_type": "DV_CODED_TEXT", "value": "Admitted assurance", - "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "admit_assurance" } - }, - "value": { "_type": "DV_TEXT", "value": "substantial" } - } - ] - } - }] -} -``` - -The `ROLE` is a policy party, so only an administrator writes or reads it. -The next first login of that tenant that meets both conditions creates its -`PERSON`, on every replica and with no restart. To stop creating, end the -`ROLE` as below; a `PERSON` already created stays. The configuration keeps -only how the issuer's tokens are read -([Just-in-time creation](installation/config-auth.md#just-in-time-creation)). - -#### Ending a grant - -To end a grant, an administrator commits a new version of the `ROLE` whose -`time_validity` ends before today (an upper bound of yesterday, or of today -with `upper_included` false), with `PUT /demographic/role/{uid}` and the -`If-Match` of its current version, or deletes it with -`DELETE /demographic/role/{uid}`. Both are versions with their committer, so -the revision history keeps the grant and who ended it, and the change decides -the caller's next request. - ### Own design No openEHR specification governs these points; each is FerroEHR's own @@ -1677,978 +895,3 @@ design: - **A federation agreement is a grant on the partner**, keyed by its client identifiers, and its rules are judged when it is written. - -## Caller facts: roles and care relationships - -What FerroEHR stores and decides on, and what it leaves to your applications -and your deployment, is listed in -[What the CDR leaves to the application](application-boundary.md). - -Beside its grants, a caller carries the facts the access evaluator reads: -the roles it performs, the care teams it belongs to and the providers it -acts for. A patient carries its care relationships. FerroEHR reads them in -any archetype (a membership by `openehr_access` `member_of`, care by -`under_care_of`), never by an archetype id, and holds them -on every replica beside the grants, so a request reads them with no -transaction of its own. - -**Roles.** A `ROLE` whose `name` is a `DV_CODED_TEXT` of the terminology -your jurisdiction names, such as a national professional role code, is a -role its `performer` holds while the `ROLE` is in force: its `time_validity` -holds the date of the request and it is not deleted. The role's type is its -name (RM Demographic IM, `PARTY.type()`), so a nurse is one `ROLE` per nurse, -each named by the nurse code. A [controller rule](#controller-rules) names a -role in an `applies_to` entry, compared by terminology and code. A `ROLE` -named in text, or by a code of `openehr_access`, names no role. A -token's role claims never count for a rule: they decide only the coarse RBAC -class gate ([Security](security.md)). The one exception is a caller admitted -under a [federation agreement](#federation-agreements): the professional -roles its token attests in `professional.hp_professional_role` are its roles, -each a code of the system the value names, because no `ROLE` of this store -describes a partner's professional. Which sensitivities a caller may read -and which purposes it may declare are rules of the access policy too, never -elements of a capability. A SCIM client writes these `ROLE`s from a User's -`roles`, within the roles its grant admits -([SCIM roles](installation/config-auth.md#roles)), so your identity -provider assigns roles and the access policy says what each may do. - -**Organisation types.** An `ORGANISATION` whose `name` is a `DV_CODED_TEXT` -of the terminology your jurisdiction names, such as a national care -provider type, is of that type, read as a `ROLE`'s name is. A system client -acting for that provider acts for an organisation of that type, and a -caller admitted under a federation agreement acts for one of each type its -token attests in `provider.facility_type`. A [controller -rule](#controller-rules) names them in an `applies_to` entry's -`organisation_type`, compared by terminology and code. - -**Memberships.** A `PARTY_RELATIONSHIP` in a `PERSON`'s `relationships` -whose `name` or `details` carry `member_of` of `openehr_access` makes the -professional a member of the care team or unit its `target` names, for as -long as its `time_validity` holds. A membership of a party other than a -`PERSON` or an `ORGANISATION`, and one whose target is no party of this -store, is refused `422`. - -**Care relationships.** A care relationship is a `PARTY_RELATIONSHIP` of -its own, written at `/demographic/party_relationship`, each versioned with -its own audit details (draft access control package, Care Relationships and -The Relationship Store). Its `name` is the code `under_care_of` of -`openehr_access`, its `source` is the patient's `PERSON`, and its `target` -is the carer: a professional's `PERSON`, a `ROLE` a professional performs, a -care team's `GROUP` or an `ORGANISATION` unit. Its `details` hold elements -named by codes of `openehr_access`: - -| Element | Occurrences | Value | -| --- | --- | --- | -| `care_role` | 1..1 | A `DV_CODED_TEXT`: the part the carer plays in the patient's care, of the value set the access policy binds for `care_role`, or of `HL7_ParticipationType` when it binds none, such as `RESP`, `ATND` or `PART` when the role is not stated | -| `provider` | 1..1 | A `DV_IDENTIFIER` of type `ORGANISATION`: the healthcare provider in whose care the relationship is, by the namespace of its reference and its id, or by the issuer and id of its identifier | -| `covers_for` | 0..1 | A `DV_IDENTIFIER` in the provider's form: the carer the target replaces, its `issuer` the namespace of the carer's reference, its `id` the carer's container and its `type` the carer's kind (`PERSON`, `ROLE`, `GROUP` or `ORGANISATION`), never the target itself | -| `episode` | 0..1 | A `DV_IDENTIFIER`: the episode of care the relationship is scoped to, by the `issuer` and `id` the care delivery environment gives it | -| `basis` | 0..1 | `assigned` (the default); `self_declared` where the policy sets `self_declared_care` ([Writing a care relationship](#writing-a-care-relationship)) | - -A caller holds a live care relationship when the relationship's `target` -names its `PERSON` or a `ROLE` it performs (the `direct` path), or a care -team or unit it is a member of (the `team` path), or, for a `self_declared` -relationship, its own `PERSON` (the `self_declared` path), the access -declares no purpose or one of the policy's `care_purposes`, and it acts for -the relationship's `provider`: a bound professional acts for the provider the party binding -names (`[authz.party_binding.provider]`, or the table of its tenant when the -binding names one per tenant), and a system client for the `ORGANISATION` -its `AGENT` acts for, matched by that organisation's own reference (its -namespace and id) or by its identifier (issuer and id), and for the -`GROUP`s that provider is a member of. Its `time_validity` is the period of the care: the end is the -upper bound, and the relationship stays, so the evaluator can apply a grace -period after it. A relationship without a `care_role` or a `provider`, with a -role outside its value set, or with a target of another kind is refused -`422`, as is one whose `provider` names no `ORGANISATION` of the store by -the identifier it carries, or whose `covers_for` names no party of its -`type`, names the target, or lacks its issuer, container id or type. A care relationship held in a `PERSON`'s `relationships` is refused -`422`, naming `/demographic/party_relationship`. The default definitions ship -`openEHR-DEMOGRAPHIC-PARTY_RELATIONSHIP.member_of.v1.0.1` and -`openEHR-DEMOGRAPHIC-PARTY_RELATIONSHIP.under_care_of.v2.0.0` as examples -([Default demographic definitions](installation/default-demographic-definitions.md)). - -**Placing a composition in an episode of care.** A COMPOSITION names the -episodes of care it belongs to with an `ELEMENT` anywhere in its -`context.other_context` whose `name` is the code `episode` of -`openehr_access` and whose value is the episode's `DV_IDENTIFIER` (`issuer` -and `id`), as the care delivery environment identifies it. FerroEHR keeps -the episodes of each composition's current version. A directive, a rule of -your access policy, a classification or a delegation names an episode's -data with `episodes` in its `ACCESS_DATA_SCOPE`, each a `DV_IDENTIFIER` -compared by `issuer` and `id`: a patient's restriction of one episode hides -that episode's compositions and nothing else, and data placed in no episode -match no entry. A persistent composition (`openehr::431`) that names an -episode, and an `episode` element without a `DV_IDENTIFIER` carrying an -issuer and an id, are refused `422` on a commit, a CONTRIBUTION, an EHR -Extract import and an archive load. So is a composition placed in an episode -that no care relationship of its EHR's subject names, live or ended: write -the relationship with its `episode` before the data placed in it. An import -is judged against the relationships this CDR holds and those in the -extract's demographics chapter, an archive load against those it holds and -those in the archive. Your template must admit the element, for example in -a CLUSTER of an `other_context` slot. - -A `relationship_validity` entry of the access policy with -`episode_required` set refuses `422` a care relationship of the roles and -provider types it covers that names no `episode`. - -**Care scoped to an episode.** A care relationship that names an `episode` -admits on care only the data of that episode, the data placed in no -episode and the data your access policy's `episode_shared` names. A -relationship that names no episode covers the whole record, as before. A -patient admitted to cardiology and seen by dermatology has two episodes: a -cardiologist whose one live relationship names the cardiology episode reads -the cardiology data and the unplaced data, is refused the dermatology data -with `refused-outside-episode` (`403`, step 7 of the access record), and no -query, count or page shows it. An access service caller also reads the data -of the EHDS priority categories (Art. 14(1)) through the category map. An -emergency, the patient, a permit directive and a gate-keeper decide as they -do without episodes. A query can narrow your caseload further to named -episodes with `caseload_episodes` ([Narrowing a query to your -caseload](querying-aql.md#narrowing-a-query-to-your-caseload)). - -**Group memberships of a provider.** A `PARTY_RELATIONSHIP` in an -`ORGANISATION`'s `relationships` carrying `member_of` makes that provider a -member of the `GROUP` its `target` names, such as the providers of a -regional health network, for as long as its `time_validity` holds. A system -client acting for the `ORGANISATION` then acts for the `GROUP` too, so a -consent permit naming the regional `GROUP`, such as one copied from the -region's IHE BPPC opt-in policy, admits it. FerroEHR resolves one level: a -`GROUP` that is itself a member of another `GROUP` adds nothing. An -`ORGANISATION` carrying `under_care_of` is refused `422`. The same -`write_care_relationship` rule guards a change of an `ORGANISATION`'s -memberships. - -**Who writes them.** The care delivery environment does, as openEHR's -security overview asks: "the evaluation of a role category such as 'care -deliverer' into particular identities ... must be done in each care -delivery environment, not in the EHR" (BASE Architecture Overview, §The -Problem of Roles). A care relationship, its change or its deletion, and a -version of a `PERSON` that adds, changes or removes a membership, commits -only for a caller holding a `write_care_relationship` grant that covers it, -such as your hospital's ADT system, or for an administrator; anyone else is -refused `403`. A version that leaves the memberships as they were needs no -grant. The grant covers what its elements name (draft access control -decision procedure, Writing Relationships): - -- **A care relationship** is covered when one `provider` element names its - `provider` and one `target_kind` element names the RM type of its target. -- **A membership** is covered when one `provider` element names a provider - of the `ORGANISATION` it targets, or of the `ORGANISATION` the `GROUP` it - targets belongs to. A `GROUP` belongs to an `ORGANISATION` by its own - `member_of` relationship to it; a `GROUP` that belongs to none, such as a - region, takes memberships from an administrator alone. - -A grant with no `provider` or no `target_kind` element writes nothing it -would need them for. The operator grants one with typed flags: - -```sh -ferroehr party-binding grant --issuer https://machines.example --client-id adt \ - --operation write_care_relationship \ - --provider-issuer urn:oid:2.999.7 --provider-id sint-example \ - --element target_kind=GROUP --element target_kind=PERSON -``` - -**A writer never admits itself.** Each caller fact and each row of the care -projection names the party that wrote it: the `PERSON` of a professional or -the client `ACTOR` of a system, as the commit audit's committer names it in -`external_ref`. A caller is never admitted on a care relationship or a -membership that it, or a party among its principals, wrote, so a -professional who rosters themselves onto a ward reads nothing through it. -The one exception is a `self_declared` care relationship where the policy -allows it ([Writing a care relationship](#writing-a-care-relationship)). -FerroEHR compares what each relationship says (its code, target, role, -provider and validity), never its position in `relationships`, so removing -another relationship before it changes none. - -The care delivery environment reaches FerroEHR on two channels, and a -deployment uses either or both: - -- **The ADT or rostering system** writes memberships (`member_of`) and `under_care_of` - through the Demographic API. On the `PERSON` of a SCIM User, which the - party binding protects, a version whose only change is to its care - relationships commits under the grant; any other change it makes stays - `403`, so the ADT system rosters a professional and touches nothing the - identity provider owns. It reads the `PERSON` to write it, so it sees the - professional's binding key and SCIM attributes. -- **The identity provider** marks a SCIM Group as a care team - ([Care teams provisioned over SCIM](#care-teams-provisioned-over-scim)). - -The two never undo each other: a SCIM Group change touches only -memberships of the membership archetype, and the ADT system's relationships -are of its own archetype. - -**When a change applies.** An admission, a transfer and a discharge decide -the next request on every replica. The commit stamps the patient whose facts -changed, and each replica reads only the facts of the parties stamped since -its copy, in one indexed read. - -No openEHR specification gives a role or a relationship an access meaning: -reading a `ROLE`'s coded name as the role a rule names, reading -relationships as care relationships and group memberships, the -`write_care_relationship` rule, and holding them in memory are FerroEHR's -own design. - -### The care relationship resources - -These resources are an extension of the openEHR REST API: ITS-REST 1.1.0 -has no resource for a relationship, so FerroEHR serves them under the -extensions root (`/ferroehr/rest/extensions/v1`), after the draft access -control package (ITS-REST Resources, Care Relationships). Each is the -`under_care_of` `PARTY_RELATIONSHIP` above in a narrower form, so a write -needs the same `write_care_relationship` grant and commits a version with its -audit details in a contribution. - -| Resource | What it does | -| --- | --- | -| `GET /care_relationship?subject_id=&subject_namespace=` | The care relationships of the subject that reference names, live ones by default; `at=YYYY-MM-DD` the day they are live on, `all=true` ended ones too | -| `GET /demographic/person/{uid_based_id}/care_relationship` | The same, for the subject this `PERSON` is | -| `POST` on either | Adds a relationship whose `source` is that subject's `PERSON`: `201` with `ETag` and `Location`; `422` for a body that is no care relationship of that subject | -| `GET /care_relationship/{relationship_uid}` | One relationship, its current version or the version the uid names; `204` once it is deleted | -| `PUT /care_relationship/{relationship_uid}` | Changes the role or the period, with `If-Match` naming the current version (`400` without it, `412` with `ETag` naming the current one when it is stale); closing `time_validity` ends it | -| `DELETE /care_relationship/{relationship_uid}` | Removes one written in error, with `If-Match`; its earlier versions keep it | -| `GET /versioned_care_relationship/{relationship_uid}`, `.../revision_history`, `.../version/{version_uid}` | The versioned object, its revision history with the audit details of each version, and one version | -| `GET /care_relationship?carer={uid}` | The relationships that reach a carer's party, `role=terminology_id\|code` and `path=direct` or `team` to narrow them, `at` as above, paged by `offset` and `fetch` (100 by default, at most 1000) | - -That a person is under the care of a given professional or service is data -concerning health (GDPR Art 4(15), Art 9), so every read is decided per -subject it reveals. A relationship is served only to a caller who may read -the subject's record, judged as a read of each of the subject's EHRs, or to a -caller who writes care relationships for the relationship's provider (an -administrator, or a `write_care_relationship` grant naming that provider). A -list leaves every other relationship out, and a read of one answers `404`, so -its role and context never reach that caller. A subject with no EHR has no -record to read, so only a writer for the provider sees its relationships. -Each read writes one access record per subject it reveals: an access-log -entry on the subject's EHR, or, for a subject with no EHR, an access record -naming its `PERSON`. The resources carry the Demographic API's SMART -requirement: a client granted `access_demographic`, or the product scope. - -```sh -curl "$BASE/ferroehr/rest/extensions/v1/demographic/person/$PATIENT/care_relationship" \ - -H "Authorization: Bearer $ADT_TOKEN" -``` - -The resources, the per-subject decision and the writer's exception are -FerroEHR's own design over its draft access control package; no openEHR -specification defines them. - -### Care teams provisioned over SCIM - -A SCIM Group is a care team when its client creates it with -`careTeam = true` in FerroEHR's Group extension -`urn:ietf:params:scim:schemas:extension:ferrohealth:2.0:Group`. RFC 7643 -§4.2 leaves what a Group means to the service provider, and the openEHR -Demographic IM names "the specialist care team, e.g. cardiology team" as -the typical `GROUP`, so this reading is FerroEHR's own design. The Demographic -IM makes a party's type its name (`PARTY.type()`, invariant -`Type_valid: type = name`, and `PARTY_RELATIONSHIP.type()` likewise), so its -`GROUP` is named by the coded `care_team` and each member's membership by the -coded `member_of`, and the evaluator counts the member in the team's care on -the next request. FerroEHR reads the kind by that code, never by the template -or a path. `careTeam` is immutable (RFC 7643 §2.2): a -Group never changes kind with its members in it. - -Creating a care-team Group, and every membership change of one, needs the -client's `write_care_relationship` grant in the CDR beside its -`scim_provision` grant; without it the request is refused `403` naming the -grant. The Group belongs to the provider the client acts for: its `GROUP` -carries a `member_of` relationship to the client's `acts_for` `ORGANISATION`, -written when the Group is created, so the grant's `provider` element names -that provider's identifier. A client that acts for no provider creates no -care-team Group (`403`). A membership from SCIM has no `time_validity`, since RFC 7643 has -none: it holds until the client removes the member or the Group. Plain -Groups, with `careTeam` left out or `false`, carry no care relationship and -need no grant. - -### Deprovisioning a team member - -A SCIM client deactivates or deletes a professional who holds care -relationships without the `write_care_relationship` grant. Revoking access -is never blocked: removing a leaver's access rights is a control that has to -work at once (ISO/IEC 27001:2022 Annex A 5.18), and neither request changes -what the care relationships say. - -- **Deactivation** (`active = false`, RFC 7643 §4.1.1) writes an `inactive` - version of the `PERSON` that keeps every care relationship, whoever wrote - it: the ADT system's rosters and the memberships of care-team Groups. Plain - Group memberships are dropped ([Groups](installation/config-auth.md#groups)). - **Reactivation** (`active = true`) restores the login, and the care - relationships are as they were. -- **Deletion** writes a logical `deleted` version of the `PERSON` and its - professional `ROLE`s (RM common §Logical Deletion). The earlier versions - stay, with the teams the professional belonged to, so the record still - answers "was this nurse on Ward 3 on that date". The User answers `404` - from then on (RFC 7644 §3.6). SCIM never erases the identity; only the - erasure process does, under the exemptions of GDPR Art. 17(3). - -The care check compares what each care relationship says (its kind, target -and `time_validity`), and each record subject the `PERSON` declares, in the -new version with the last version that holds a body. A lifecycle state is no relationship content, and a deletion holds no -body, so neither needs the grant. - -The login is refused on its next request on every replica, because each -request reads the binding with no cache: an inactive `PERSON` with -`refused-inactive`, and a login whose key only a deleted `PERSON` carried -with `refused-deprovisioned`. The access evaluator never sees the caller, so -the care relationships it would read do not matter. - -The ADT system writes no version of a deactivated `PERSON`: an `inactive` -version takes no update (RM common master06 §Version Lifecycle: editing -resumes only through `reactivate` or `retrieve`), and a roster cannot change -the lifecycle state, so such a write is refused `403` and the `PERSON` stays -`inactive`. That costs nothing: a deactivated person's memberships decide no -access, since the login is refused at binding. A leaver's roster is cleaned -up by the SCIM deletion, a logical `deleted` version that ends every -relationship while the earlier versions keep the history (master06 -§Logical Deletion), or by the ADT system after the User is reactivated. -Apart from the cited lifecycle rules, this section is FerroEHR's own design. - -## Representatives - -A parent, a guardian or a proxy the patient chose reads the patient's record -through an app as the patient's representative. Regulation (EU) -2025/327 Art. 4(2) asks for proxy services that let natural persons -authorise others to access their personal electronic health data on their -behalf, and let legal representatives access the data of the persons whose -affairs they administer, "in accordance with national law"; Member States -set the rules for both. Who represents whom, and until when, is therefore -data the deployment keeps in the CDR. FerroEHR builds in no country's rules. - -### The representation - -A representation is a `PARTY_RELATIONSHIP` of its own, written at -`POST /demographic/party_relationship` (FerroEHR's extension), from the -representative's `PERSON`, its source, to the subject's `PERSON`, its -target. Its `name` is `openehr_access::represents`, and its `details` hold -the elements of the `representation element` group, each named by its code: - -| Element | Occurrences | Value | -|---|---|---| -| `basis` | 1..1 | `DV_CODED_TEXT`: why the representative may act for the subject, a code of the value set the access policy binds for `representation_basis`, or of `HL7_RoleCode` (such as `GUARD`, `RESPRSN`, `DELEGATEE`) when it binds none | -| `provider` | 1..1 | `DV_IDENTIFIER` of type `ORGANISATION` with an `issuer` and an `id`: the healthcare provider for which the representation is recorded | -| `evidence` | 0..1 | `DV_IDENTIFIER`: the court order, register entry or written authorisation | - -Any archetype may model it; FerroEHR reads the codes, never the archetype -id. It may also name how the two are related with a `DV_CODED_TEXT` of the -openEHR `subject_relationship` group (`254|parent|`, `264|guardian|`), which -the committer and the access log carry. The shipped -`openEHR-DEMOGRAPHIC-PARTY_RELATIONSHIP.representation.v2` is an example. -A representation held in a `PERSON`'s `relationships` is refused `422`, -naming the resource to write it at, and so is one without a readable -`basis` or `provider`, or with a `basis` outside its value set. Each -representation is versioned on its own, with the commit audit of whoever -wrote it, and is ended by closing its `time_validity`. - -It holds while its `time_validity` covers today's date in UTC. These -callers write one: - -- an administrator; -- a caller holding a `write_representation` grant whose `provider` - elements name the representation's provider, before and after the write; - a grant that names no provider writes none; -- the patient it represents, on the basis `HL7_RoleCode::DELEGATEE` alone: - the patient authorises a proxy of their choice (EHDS Art. 4(2)). Any other - basis, such as a parent's or a court-appointed guardian's, is written by an - administrator or a `write_representation` holder. - -FerroEHR admits a representative only on a representation that is live on -the day of the request, whose `provider` is the provider the deployment acts -for (`[authz.party_binding.provider]`), and that the representative did not -write itself. A representative with no such representation is refused `403` -with `refused-representation-unrecorded`. The access record of -every admitted request names the representation's container, which the -access log's `representation` authorisation carries as its reference. - -The representative's `PERSON` is of a template -`[[authz.party_binding.person.template]]` maps and carries a binding key: a -`DV_IDENTIFIER` whose `issuer` is the `identifier_issuer` of the party table -of the issuer they sign in at, and whose `id` is their login there (their -`sub`). An administrator or an identity feed writes it through the -Demographic API; SCIM provisions a workforce only. The `PERSON` carries the -representative marker once it is the source of a representation, and no -professional `ROLE`. EHDS Art. 4(2) gives the authorisation to the patient -(a) and to the legal representative under national law (b), so the patient, -an administrator or a `write_representation` holder records it. - -### Legal capacity - -How old a minor must be before their parents no longer see their record, and -when someone may act for an adult, is national law. It reaches FerroEHR as -the representations the deployment records and the `time_validity` it gives -them: the deployment, or the national identity or authorisation service it -follows, ends a parent's representation on the date the child decides -alone, and ends or adds a representation when a court or the patient changes -who may act. FerroEHR checks only that a live representation for its -provider covers today, so a change is effective on the next request, and -holds no age band, no capacity rule, no country table and no archetype id of -its own (draft access control package, The Representation as a Stored -Fact). - -### Signing in - -A representative signs in at a trusted issuer one of two ways: - -- **As a `RelatedPerson`.** Their token's `fhirUser` is a `RelatedPerson` - (SMART App Launch 2.2.0, Scopes and Launch Context, `fhirUser`), and its - launch context names the patient's EHR (`ehrId`). -- **As a user whose `PERSON` is a representative's alone.** Their token - names no `RelatedPerson`, and their login binds a `PERSON` carrying the - representative marker and no professional `ROLE`. - -Either way FerroEHR binds the login, by the token's `sub` under its -issuer's party table, to the `PERSON` whose binding key it is, and admits -the request while that `PERSON` holds a live representation of the subject: -the subject of the launch EHR, else of the EHR the request names, else the -`PERSON` an EHR lookup by subject names. The request is confined to that -subject's EHRs, or to the launch EHR when the token names one. The -representation is read from the CDR, never from the token (EHDS Art. 4(2)). -A representative with no representation yet, one whose representation ended -or was deleted, and one who represents someone else are refused `403` with -`refused-representation-unrecorded`, so a former representative never becomes -the patient. A representative reaching their own record reaches it as the -person themself (EHDS Art. 3). The patient themself is the one whose login -is a binding key of the `PERSON` the EHR's subject names: the party binding -is the one source of own access, and the token's claims are never trusted on -their own. This is FerroEHR's own design. - -Each access is recorded bound to the representative's `PERSON`, naming the -subject they represent and the relationship (EHDS Annex II 3.2), and a commit -records the representative as a `PARTY_RELATED` committer. - -### The patient authorises a proxy - -The patient authorises a proxy with a `PARTY_RELATIONSHIP` of its own, from -the proxy's `PERSON` to their own: - -```sh -curl -X POST "$BASE/ferroehr/rest/extensions/v1/demographic/party_relationship" \ - -H "Authorization: Bearer $PATIENT_TOKEN" \ - -H 'Content-Type: application/json' \ - -d '{ - "_type": "PARTY_RELATIONSHIP", - "archetype_node_id": "openEHR-DEMOGRAPHIC-PARTY_RELATIONSHIP.representation.v1", - "archetype_details": { "_type": "ARCHETYPED", "rm_version": "1.1.0", - "archetype_id": { "_type": "ARCHETYPE_ID", "value": "openEHR-DEMOGRAPHIC-PARTY_RELATIONSHIP.representation.v1" } }, - "name": { "_type": "DV_CODED_TEXT", "value": "Authorised proxy", - "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "local" }, "code_string": "at12" } }, - "details": { "_type": "ITEM_TREE", "archetype_node_id": "id3", - "name": { "_type": "DV_TEXT", "value": "Details" }, - "items": [ - { "_type": "ELEMENT", "archetype_node_id": "id4", "name": { "_type": "DV_TEXT", "value": "Representation code" }, - "value": { "_type": "DV_CODED_TEXT", "value": "represents", - "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "represents" } } }, - { "_type": "ELEMENT", "archetype_node_id": "id6", "name": { "_type": "DV_TEXT", "value": "Relationship" }, - "value": { "_type": "DV_CODED_TEXT", "value": "unknown", - "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr" }, "code_string": "253" } } } ] }, - "time_validity": { "_type": "DV_INTERVAL", "lower": { "_type": "DV_DATE", "value": "2026-11-13" }, - "lower_unbounded": false, "upper_unbounded": true, "lower_included": true, "upper_included": false }, - "source": { "_type": "PARTY_REF", "namespace": "demographic", "type": "PERSON", - "id": { "_type": "HIER_OBJECT_ID", "value": "" } }, - "target": { "_type": "PARTY_REF", "namespace": "demographic", "type": "PERSON", - "id": { "_type": "HIER_OBJECT_ID", "value": "" } } - }' -``` - -The patient's own credential reaches the writes of -`/demographic/party_relationship`, and FerroEHR admits only a representation -whose target is the subject of the patient's launch EHR, before and after -the write. The committer is the patient, a `PARTY_IDENTIFIED` naming their -`PERSON`. The patient revokes the authorisation with -`DELETE /demographic/party_relationship/{uid}`, or ends it with a `PUT` whose -`time_validity` ends; the proxy's next request is refused. The patient -changes only a representation they inserted themself: one an administrator -recorded, such as a court-appointed guardian's, is the administrator's -(EHDS Art. 5). - -### Where this is our own design - -No openEHR specification governs these points; each is FerroEHR's own -design: - -- **A representation is recognised by its code**, as the acts-for - relationship is, so a deployment models it in any archetype. -- **Legal capacity is the recorded representations and their validity.** - The rules are national law (EHDS Art. 4(2)), so FerroEHR holds no rule of - its own. -- **A login binds by the token issuer.** The representative's binding key - is a `DV_IDENTIFIER` under the identifier issuer of the party table of the - issuer that signs their login. -- **A patient writes the representation of themselves**, and the party - protection holds them to it. - -## The admin registers - -Two kinds of operational policy have no home in the openEHR demographic -model, so each is an admin register: - -| Register | What it holds | Default, before anyone writes it | -|---|---|---| -| `audit-categories` | The EHDS category map every access is classified through ([the audit category register](installation/config-audit.md#the-audit-category-register)) | The category map FerroEHR ships | -| `access-delay` | The EHDS Art. 3(3) delay of the person's own access ([the access-delay register](installation/config-auth.md#the-access-delay-register)) | Off | - -You read and write them under `{ext}/admin/registers/{register}` with a token -or Basic user holding `admin_role`, with `[api] admin = true`; the routes are -on [Admin & messaging APIs](operations-admin-apis.md#operational-policy-registers). - -- **Versioned.** Every write appends a version that names its committer and - when it was committed, and never overwrites one; the history route lists - them all. Version 0 is the default no one committed. -- **Whole, over a version.** A write replaces the whole document and names the - version it replaces in `If-Match`. A write over a version that is no longer - the newest is refused with `412`, so two operators never overwrite each - other's change unseen. -- **Checked when written.** A document that does not hold is refused whole with - `400` and never reaches a request: a category map that does not compile or - a delay with an unusable limit. - The register keeps its version in force. -- **Effective without a restart.** Each replica keeps the registers in - memory and is told of every write through PostgreSQL `LISTEN`/`NOTIFY` when - the write commits; its next request after that reads the new version. The - replica that took the write applies it to its own next request. While a - replica's listener is not connected, that replica reads the registers on - every request, so it never serves an outdated policy. A database that cannot - answer that read fails the request with `503`; it is never served under a - guess. -- **Audited.** Every read and write of a register is an access record. - -A deployment provides its registers once the server runs, through the admin -API; neither has a key in `ferroehr.toml`. - -### A worked example: turning the access delay on - -Read the register, then write the new document over the version it answered: - -```sh -curl -s -u admin:… https://cdr.example/ferroehr/rest/extensions/v1/admin/registers/access-delay -# ETag: "0" -# {"register":"access-delay","version":0,"committer":null,"committed_at":null, -# "document":{"enabled":false,"categories":[],"max_delay":null}} - -curl -s -u admin:… -X PUT \ - -H 'Content-Type: application/json' -H 'If-Match: "0"' \ - -d '{"enabled": true, "categories": ["Laboratory-Reports"], "max_delay": "72h"}' \ - https://cdr.example/ferroehr/rest/extensions/v1/admin/registers/access-delay -# ETag: "1" -``` - -The next laboratory report committed on any replica is held from the person -for up to 72 hours. - -### The security floor that stays in `ferroehr.toml` - -A floor that must hold before a register can be read stays configuration. With -`deployment.profile = "production"` and auditing on, the audit category -register refuses a map that classifies nothing (no template, no archetype and -`shipped_map = false`) as the `no_category_map` gap, unless -`deployment.accepts` names it. - -## The access policy - -The controller's access policy states what holds for every EHR this FerroEHR -keeps: which kinds of data carry which sensitivity (`classifications`), -whether a professional's clinical access needs a care relationship -(`care_relationship_required`, with a `relationship_grace`) and a declared -purpose (`purpose_required`), the controller's own `rules` on which callers -may do what with which kinds of data (each an `ACCESS_DIRECTIVE` of kind -`controller_rule`, EHDS Art. 11(3)), the `catalogue` of named directives a -patient can accept by reference, such as an IHE BPPC policy, and the -`log_restrictions` of the access log's subject view your Member State's law -lays down under EHDS Art. 9(3) ([Audit](audit.md#restricting-the-subject-view-ehds-art-93)). -It is an `ACCESS_POLICY` of FerroEHR's draft access control package, written -against the default archetype `openEHR-EHR-ACCESS_POLICY.controller.v1`, -which every boot stores, or against one of your own. The default floor -(`[authz.rbac] ehr_access_default`) stays in `ferroehr.toml`, and the policy -can only tighten it. Emergency access is one of the policy's -`justifications`. Until you write -one, nothing is tightened. - -- **Versioned.** Every write is a new version in its own contribution, with - you as committer; the history route lists them all. -- **Whole, over a version.** Name the version you replace in `If-Match`, or - create the first with `If-None-Match: *`. A stale condition is `412`. -- **Checked when written.** A body that is no canonical-JSON `ACCESS_POLICY` - is refused whole with `400`. A policy that reads but breaks a rule is - refused whole with `422`, naming the rule or the attribute: an invariant - of the draft model, a rule of another kind than `controller_rule`, a - catalogue entry of that kind, a rule naming a role, purpose, sensitivity, - category or legal ground in `openehr_access`, the template its - `archetype_details.template_id` names, or a code outside a value set it - binds. -- **Effective without a restart**, as the registers above. -- **Read by the access evaluator** on every request: `purpose_required` is - step 4, checked before any rule, the rules are step 5, a classification - gives the data it covers its sensitivities (step 6), and - `care_relationship_required` is step 7 of the - [decision procedure](security.md#access-directives). - A `relationship_grace` that is no ISO 8601 duration admits nothing after a - care relationship ends. - -The routes are on -[Admin & messaging APIs](operations-admin-apis.md#the-access-policy). A write -needs `admin_role` and a policy grant of `write_access_policy`. - -### Care relationship facts - -The policy also states how care relationships are read. Each attribute you -leave out reads as its strictest default, so a policy that sets none admits -least. - -| Attribute | What it says | Left out | -| --- | --- | --- | -| `self_declared_care` | The longest period of a care relationship a professional states for themself | no self-declared relationship | -| `attested_care` | The agreements under which a caller's verified credential may attest a care relationship | no attested relationship | -| `caseload` | Whether a query may be narrowed to the caller's [caseload](care-relationships.md#the-caseload) | `true` | -| `episode_shared` | The data every live care relationship covers whatever episode it or the data name, such as the patient summary, each an `ACCESS_DATA_SCOPE` ([Care relationships and episodes of care](care-relationships.md#episodes-of-care)) | none | -| `conflict_rules` | The conflicts of interest (`self`, `related`, with the kinships) allowed through the professional path, and for whom | none: a professional who is the patient, or is related to them, is refused | -| `concealed_confidentialities` | The `HL7_Confidentiality` levels whose refused records answer as absent | every refused record answers as forbidden | -| `value_sets` | The value set on your terminology server that each coded attribute (`care_role`, `representation_basis`, `kinship`, `organisation_type`, `care_purpose`, `emergency_purpose`) is bound to | the package's default code system | -| `relationship_validity` | The default and maximum period of a care relationship, by its `care_role` and the type of its provider | every care relationship is written with an end | -| `relationship_writers` | The writers that may write a care relationship to a record marked `R` or `V` | none | -| `team_targets` | The `ORGANISATION` units a care relationship may name as its target | none: a care team is a `GROUP` | - -FerroEHR ships no value set and no country content. A code of a bound -attribute is checked against its value set on the -[terminology server](templates-validation.md) when you write the policy; -with no terminology server configured, a policy that binds a value set the -check needs is refused. An unbound kinship is a code of the openEHR -`subject relationship` group. An organisation type has no default code -system, so a rule, an exception or a conflict rule that names an -`organisation_type` is refused `422`, naming it, until the policy binds an -`organisation_type` value set. A template of the default archetype that -fixes some of these attributes for many controllers is a profile: write the -policy with its `template_id`, and FerroEHR validates it against the -template. - -Two more attributes say when a relationship is a ground at all: - -| Attribute | What it says | Left out | -| --- | --- | --- | -| `care_purposes` | The purposes of use for which a care relationship is a ground: an access declaring another purpose, such as research, rests on no relationship and matches no rule scope naming `care` | `TREAT`, `ETREAT` and `CAREMGT` of `HL7_ActReason` | -| `time_zone` | The IANA time zone in which the dates of a relationship's `time_validity` are read, such as `Europe/Amsterdam`; a name the zone database does not hold is refused `422` | UTC | - -#### The attested care path - -A caller from another organisation, admitted under a -[federation agreement](#federation-agreements), can hold a care -relationship that is never stored: its verified credential attests a -treatment context for the patient. This is how a national contact point or a -national infrastructure reaches the record for cross-border care. The path is -off until `attested_care` names the agreement: - -```json -"attested_care": [ - { "_type": "DV_IDENTIFIER", - "issuer": "https://federation.example", - "id": "0190b3a2-5a3e-7c1d-9e2f-3b4c5d6e7f99" } -] -``` - -- `id` is the container uid of the agreement `ROLE` (the part of its - version uid before `::`), so a new version of the agreement keeps the - reference. -- `issuer`, when you set it, must be the federation issuer the partner's - client identifiers are held under. A policy that names another issuer, or - names under an issuer an id that is no agreement `ROLE`, is refused `422`, - naming `/attested_care//issuer`. - -Which claims carry the treatment context is your data, in the issuer's -`[auth.issuer..federation]` table. FerroEHR reads these fields: - -| Field | What it carries | -| --- | --- | -| `patient.id` | The patient, as `system\|value`: the identifier an EHR's subject names | -| `trc.id` | The id of the assertion that attests the treatment context | -| `trc.not_on_or_after` | The end of its window, in seconds since the epoch | -| `trc.not_before` | The start of its window, when the credential states one | -| `assertion.issuer` | The issuer of the assertion, when the credential states one | -| `trc.care_role` | The care role the treatment relationship attests for the professional, one code with its code system | - -A credential that lacks `patient.id`, `trc.id` or `trc.not_on_or_after` -attests nothing. On every access FerroEHR checks that the policy names the -agreement, that the window holds the moment of the access, and that the -record's subject is the attested patient. The caller then holds a live care -relationship for the care step, the default disposition and any rule whose -actor scope names `relationship: care`. The relationship is never stored and -never in a caseload. The access log names it as a `treatment relationship` -ground whose `reference` is the assertion (`id` and `issuer`) and whose -`name` and `version` are the agreement's. - -The attested relationship holds the role `PART` unless the credential -attests a role in `trc.care_role` of the `care_role` value set the policy -binds (unbound, a code of `HL7_ParticipationType`). The code system of the -attested role is the terminology its code is read in, so a credential whose -role carries the system `HL7_ParticipationType` names a code of that -terminology, and a field mapped as `{ constant = "ATND", system = -"HL7_ParticipationType" }` attests that role for every credential of the -issuer. A role outside that value set, or one no terminology server could -check, counts as no role, and the relationship keeps `PART`. -`ferrohealth-smart` refuses a token whose `trc.care_role` is not one code -with its system. - -A rule limits attested callers like any other: give its actor scope -`relationship: care` with `care_path: attested`. A deny rule's `data` keeps -attested callers from the templates or categories it names, and on a record -the controller marks `R` or `V` an attested caller is refused -`refused-confidentiality` until a permit rule for that path names the level -in its `data` `confidentialities`: - -```json -{ "_type": "ACCESS_DIRECTIVE", "kind": "controller_rule", "effect": "permit", - "applies_to": [ { "_type": "ACCESS_ACTOR_SCOPE", - "relationship": "care", "care_path": "attested" } ], - "data": [ { "_type": "ACCESS_DATA_SCOPE", "confidentialities": [ "R" ] } ] } -``` - -The codes are shown short here; write each as a `DV_CODED_TEXT`. A permit -that names `R` clears `R` and nothing above it, and one written for the -`direct` path clears no attested caller. - -#### Writing a care relationship - -FerroEHR checks each care relationship against the policy when it is -written, and refuses one that breaks a bound with `422`, naming -`/time_validity` or `/target`: - -- **Validity.** A relationship written without an end takes the - `default_period` of the first `relationship_validity` entry that covers its - role and its provider's type, counted from its start (or from the day of - the write when it names no start). One longer than that entry's - `max_period` is refused. One that no entry covers, or whose entry has a - `max_period` and no `default_period`, must be written with an end. An entry - with neither period lets the relationship stay open. -- **Target.** An `ORGANISATION` target must be a unit `team_targets` names, - and is never the controller or the relationship's own provider. -- **Writers.** The level is the highest marking of the subject's records: - every EHR whose subject reference names the relationship's source - `PERSON`, directly or through a record subject the `PERSON` declares. - FerroEHR reads those markings exactly before the commit takes its - connection. At `N` every writer the `write_care_relationship` grant - admits writes. At `R` or `V` only a writer a `relationship_writers` entry - names for that level writes, and its access-log record is flagged for - review with the level: the `review` detail (`id40`) of the entry's - [details](audit.md), the `review` column of `audit.access_trail`, and a - `review` detail on the object of the BALP `AuditEvent` and the DICOM - audit message. Every other write is refused `403`, naming the level and - the missing entry. The administrator is no exception: a - policy that wants the administrator to write such relationships names the - administrator's `PERSON` (or a role it performs) for the level. An entry - for `V` does not cover `R`; name each level the writer may write. -- **Self-declared.** A relationship whose `basis` is `self_declared` is - refused `422` unless the policy sets `self_declared_care`. Its target is - the writer's own `PERSON` (`403` otherwise), and it ends within that period - of its start, by its own end or the one `default_period` gives it. While - the policy sets `self_declared_care`, it admits the professional who wrote - it; once the policy no longer sets it, it admits no one. - -For example, this `relationship_writers` lets the admission system's role -write relationships to records at `R`, and the administrator's `PERSON` -write them at `R` and `V` (the role code and the identifiers are your own): - -```json -"relationship_writers": [ - { "_type": "ACCESS_RELATIONSHIP_WRITER", - "applies_to": [{ "_type": "ACCESS_ACTOR_SCOPE", - "role": { "_type": "DV_CODED_TEXT", "value": "admission system", - "defining_code": { "terminology_id": { "value": "urn:example:roles" }, - "code_string": "adt" } } }], - "confidentialities": [ - { "_type": "DV_CODED_TEXT", "value": "restricted", - "defining_code": { "terminology_id": { "value": "HL7_Confidentiality" }, - "code_string": "R" } }] }, - { "_type": "ACCESS_RELATIONSHIP_WRITER", - "applies_to": [{ "_type": "ACCESS_ACTOR_SCOPE", - "party": { "_type": "PARTY_REF", "namespace": "demographic", "type": "PERSON", - "id": { "_type": "HIER_OBJECT_ID", "value": "" } } }], - "confidentialities": [ - { "_type": "DV_CODED_TEXT", "value": "restricted", - "defining_code": { "terminology_id": { "value": "HL7_Confidentiality" }, - "code_string": "R" } }, - { "_type": "DV_CODED_TEXT", "value": "very restricted", - "defining_code": { "terminology_id": { "value": "HL7_Confidentiality" }, - "code_string": "V" } }] } -] -``` - -The end a relationship takes from `default_period` is never written into the -relationship: the version you committed stays exactly as you sent it, with -its digest and signature. FerroEHR computes the end once, in the commit's -transaction, from the policy version the write read, and keeps it beside the -relationship with the uid of that policy version. Every access decision and -query reads that end. A later policy version does not move it: a changed -period applies to the relationships written after the change. To change the -end of a relationship, write a new version of it. - -Each write reads the newest policy version from the store before it takes -its connection to the demographic store, because the policy lives in the -clinical store. A policy version committed between that read and the commit -applies from the next write; the kept end names the version it came from. - -An archive load (`load_ehrs`) carries no kept ends, so it checks each care -relationship it loads against the policy in force on the server it loads -into, counting a missing start from the day the loaded version was -committed. A relationship the policy refuses is reported in the load's -failure report and is not loaded; the rest of the archive loads. Put the -access policy in place before you load an archive that holds open care -relationships. - -### Exclusions and conflicts of interest - -**An exclusion keeps a named person out of one record.** It is a deny of -kind `exclusion` in the `exclusions` of the EHR's `EHR_ACCESS` settings, -naming the parties it keeps out by `applies_to` (a party, or the -`representative` relationship), with an optional data scope, validity and -legal grounds. It is decided before step 1: it binds a professional, a -representative and a gate-keeper, never the person, and no permit of the -person or a representative lifts it. A declared emergency lifts it only -where its `emergency_override` holds and the caller is no representative. -The caller is answered `403 refused-excluded`, and the answer names neither -the exclusion nor its reason; the access log names the exclusion and the -`EHR_ACCESS` version. A law that lets a provider decline to treat a person -as a representative, for example in a case of abuse, is carried by one. - -Only the controller (a caller holding `admin_role`) reads and writes the -exclusions. Every read of an `EHR_ACCESS` by anyone else, the person and a -gate-keeper included, leaves them out; a version envelope, a contribution -or an AQL row that would carry them reads as absent to such a caller, and -an EHR Extract for the person carries no `EHR_ACCESS` that ever held one. A -version a gate-keeper or the person commits carries the current exclusions -forward unchanged, and one that names other exclusions is refused `403`. - -**A restriction binds a representative it names.** A `restriction` the -person gives binds a representative whose `applies_to` names it by party or -by the `representative` relationship, answered as absent, as it is for a -professional. A controller rule over a label that names representatives -refuses them at step 5. - -**A conflict of interest refuses the professional path.** A professional is -in conflict with the person when it performs a professional `ROLE` and is -bound to the person's `PERSON` (a staff member on their own record), or -when a `related_to` relationship in force joins its `PERSON` to the -person's. It is refused `403 refused-conflict` at step 5, in a read and in a -query, unless an entry of the policy's `conflict_rules` for that conflict -names it (and, for `related`, the kinship); an access such an entry admits -is marked in the access log with a `conflict allowance` ground. A staff -member reads their own record. Kinship refuses -and never grants: a relative passes the other steps as anyone else. - -A kinship is a `PARTY_RELATIONSHIP` of its own named `related_to`, written at -`/demographic/party_relationship` under the `write_care_relationship` grant -or by an administrator, whose source and target are two `PERSON`s and whose -`kinship` element is a code of the value set bound for `kinship` (by default -the openEHR `subject relationship` group). Your demographic service or -master patient index decides who is kin; FerroEHR stores the fact and -decides on it. A query leaves out the EHRs of every person the caller is in -conflict with; a conflict rule that names the `care` relationship admits a -conflict in a direct read of a record the caller cares for, and in a query -reads as not admitting it. - -### Controller rules - -Regulation (EU) 2025/327 Art. 11(3) asks each Member State to lay down -which categories of health data different categories of health -professionals may reach. The access policy's `rules` hold those rules for -every EHR you keep. Each rule is an `ACCESS_DIRECTIVE` of kind -`controller_rule`, with the `applies_to`, `operations`, `purposes`, `data`, -`time_validity`, `emergency_override`, `exceptions` and `legal_grounds` a -directive has. The `ROLE` parties say who holds a role; the rules say what -the role may do. - -- **A deny rule refuses** what it covers with `403 refused-policy-denied`, - whatever the patient's directives permit (step 5). It binds every caller - but the patient on their own record, representatives included. -- **A permit rule clears** the callers it names for the sensitivities its - `data` names (step 6) and decides nothing else. -- **A rule's `purposes` match only a declared purpose.** A request that - declares none is outside every rule that names purposes. Set - `purpose_required` to refuse such a request: it is refused - `refused-purpose-missing` before any rule is read, whatever rules you - hold. -- **A deny rule with a permit exception says "only"**: the exception carves - what it covers out of the deny. -- **A scope naming `care` can name care roles and a path.** With - `relationship` `care`, an actor scope's `care_roles` lists the roles a - caller's live care relationship must have, compared by terminology and - code, and `care_path` says how it must reach the caller: `direct`, `team`, - `self_declared` or `attested`. Left out, any role and the paths the policy - turns on. No role implies another: - `RESP` does not cover `ATND`. The same scope decides a read and narrows a - query inside its one statement, so a `COUNT` agrees with the reads. -- **For a write**, the data are the version being committed: its template, - root archetype, origins and the sensitivities your classifications give it. - -Four rules, as you write them in the policy body (a role code of -`urn:example:roles` stands for your jurisdiction's role terminology): - -```json -"rules": [ - { "_type": "ACCESS_DIRECTIVE", "name": { "_type": "DV_TEXT", "value": "Nurses do not record diagnoses" }, - "archetype_node_id": "id15", - "kind": { "_type": "DV_CODED_TEXT", "value": "controller_rule", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "controller_rule" } }, - "effect": { "_type": "DV_CODED_TEXT", "value": "deny", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "HL7_ConsentProvisionType" }, "code_string": "deny" } }, - "applies_to": [{ "_type": "ACCESS_ACTOR_SCOPE", "role": { "_type": "DV_CODED_TEXT", "value": "Nurse", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "urn:example:roles" }, "code_string": "NURSE" } } }], - "operations": [{ "_type": "DV_CODED_TEXT", "value": "write", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "write" } }], - "data": [{ "_type": "ACCESS_DATA_SCOPE", "templates": ["Diagnosis"] }], - "emergency_override": false } -] -``` - -- **A nurse may not record a diagnosis:** the rule above. -- **Only psychiatry reads mental-health notes:** classify the mental-health - templates `PSY` (HL7 v3 `ActCode`), and write a `permit` rule whose - `applies_to` names the psychiatrist role and whose `data` names the - sensitivity `PSY`. A patient's consent permit naming their GP clears the - GP in the same step; everyone else is refused `refused-sensitivity`. -- **Professionals may declare only treatment or emergency treatment:** a - `deny` rule whose `applies_to` names the caller kind `professional`, with - one `permit` exception whose `purposes` are `TREAT` and `ETREAT`. A request - declaring another purpose is refused `refused-policy-denied`. A request - declaring none is refused `refused-purpose-missing` where the policy sets - `purpose_required`, and otherwise `refused-policy-denied`, since the - exception names no request without a purpose. -- **Only the responsible practitioner, directly, signs the discharge - summary:** a `deny` rule on `write` whose `data` names the discharge - summary template, with one `permit` exception whose `applies_to` is - `relationship` `care`, `care_roles` `[RESP]` and `care_path` `direct`. A - second in chain (`SPRF`), a consultant (`CON`) and a team member are - refused `refused-policy-denied`; a professional covering for the - responsible one holds a `RESP` relationship of their own for the period - and is admitted. -- **A system client writes only its laboratory templates:** a `deny` rule on - `write` whose `applies_to` names the client's `AGENT` by `party`, with one - `permit` exception whose `data` lists the templates. -- **Only care providers reach records through the exchange:** a `deny` rule - whose `applies_to` names the caller kind `access_service`, with one - `permit` exception whose `applies_to` lists one `organisation_type` per - care provider type, and the provision in its `legal_grounds`. A partner's - professional whose token attests an insurer's facility type, or none, is - refused `refused-policy-denied`. A second `deny` rule naming a `role`, such - as an occupational physician, or `purposes`, such as a medical - examination, keeps those out too. A rule naming `purposes` refuses only a - request that declares one of them, so set `purpose_required` to refuse a - request that declares none. Wabvpz Art. 15f is a rule of this kind: you commit it, - FerroEHR holds no copy of it. - -A rule whose `emergency_override` is true is lifted for a caller that -invokes an emergency -[justification](security.md#justified-access-outside-the-care-relationships) -with a reason, and the access record names the rule. The access record of a refusal names the -rule by its uid, its first identifier or its position in `rules`, and a -`legal obligation` ground carrying the rule's `legal_grounds`. The `403` -problem body carries them in its `legal_grounds` member beside `refusal`, -each with its `terminology`, `code` and `value`, under -`Prefer: return=representation`. - -**A federation agreement and the rules.** A federation agreement is the -contract with a partner: its `template` elements say what the partner's -persons may send. The rules are your own limits, and they hold for a -partner's persons too: a deny rule refuses a template the agreement allows, -because a deny overrides. - -No openEHR specification has a controller rule: the rules, their place as -step 5 after the purpose check, matching a rule's purposes only on a -declared purpose, reading a role from the coded name of a `ROLE` and an organisation -type from the coded name of an `ORGANISATION`, reading a partner's attested -roles and facility types as the same facts, and naming a refusing rule's -legal grounds as a `legal obligation` ground are FerroEHR's own design, -proposed in the draft access control specification. diff --git a/website/book/src/operations-access-path.md b/website/book/src/operations-access-path.md index 4426cc1f27..e9a32119e3 100644 --- a/website/book/src/operations-access-path.md +++ b/website/book/src/operations-access-path.md @@ -102,7 +102,7 @@ store holds. The `ehr_access` copy holds at most 4096 EHRs' settings, and beside them the settings classes a query is judged over -([the bound](security.md#per-ehr-access-control-ehr_access)). The `copy` label is `ehr` or `classes`. +([the bound](access-control.md#per-ehr-access-control-ehr_access)). The `copy` label is `ehr` or `classes`. The care relationships of the EHRs' subjects sit beside the grants, in two caches with fixed defaults: the care relationships of at most 4096 subjects, @@ -326,7 +326,7 @@ recording while you investigate. and `ferroehr access-log verify --checkpoint ` with the newest checkpoint published outside the database. 3. Compare the findings with a checkpoint kept outside the database - ([Seals, checkpoints and the transfer of a log](audit.md#seals-checkpoints-and-the-transfer-of-a-log)). + ([Seals, checkpoints and the transfer of a log](audit-integrity.md#seals-checkpoints-and-the-transfer-of-a-log)). A record changed or deleted outside retention is a security incident: follow [complaints, incidents and vulnerabilities](compliance/post-market.md). @@ -421,4 +421,4 @@ recording while you investigate. in batches of 500 and folds tombstones in batches of 5000, each in its own transaction. 3. Size the audit store for the access rate - ([Storage sizing](operations.md#storage-sizing)). + ([Storage sizing](storage-sizing.md)). diff --git a/website/book/src/operations-admin-apis.md b/website/book/src/operations-admin-apis.md index c34715bc26..2aeda0a63a 100644 --- a/website/book/src/operations-admin-apis.md +++ b/website/book/src/operations-admin-apis.md @@ -5,7 +5,8 @@ clinical clients: the **admin API**, which physically deletes, reports on, and moves repository content, and the **messaging API**, which exports and imports whole records as openEHR EHR Extracts. This page is the operator's reference for both: every path, what gates it, what it accepts, and every status code it -answers. +answers. Storage integrity, dump and load and the EHR Extract routes are on +[Storage integrity, dump and load](storage-admin-apis.md). @@ -215,7 +216,7 @@ Two consequences to plan for: Three routes behind the same switch, for `admin_role` only, carry the operational policy that is data rather than configuration: the audit category map and the EHDS Art. 3(3) access delay. What each -register holds is on [Operational policy](operational-policy.md#the-admin-registers). +register holds is on [Operational policy](access-policy.md#the-admin-registers). | Route | Body or header | Success | |---|---|---| @@ -234,7 +235,7 @@ record of its own. Four routes behind the same switch, for `admin_role` only, carry the controller's access policy. What it holds is on -[Operational policy](operational-policy.md#the-access-policy). +[Operational policy](access-policy.md#the-access-policy). | Route | Body or header | Success | |---|---|---| @@ -271,11 +272,11 @@ anything. | `GET {ext}/admin/access-delay` | `?ehr_id=…` | **200**: the access-delay register, newest hold first, each with its `basis` (`category` or `professional`), its end and its release | | `POST {ext}/admin/access-delay/release` | `{"ehr_id": "…", "vo_id": "…"}` | **204**: every hold of the composition still in force is released, and the person reads it | | `POST {ext}/ehr/{ehr_id}/versioned_composition/{versioned_object_uid}/access-delay/release` | none | **204**: the treating professional's release from the clinical surface, with the checks of a write to that EHR; **403** to a request that may be the person's | -| `POST {ext}/admin/access-log/erase` | `{"uid": "…", "grounds": [DV_CODED_TEXT, …]}` | **200**: the `ACCESS_LOG_TOMBSTONE` that replaced the access-log entry, for an erasure a law orders before the entry's retention ends; it keeps the entry's uid, `system_id`, `time_recorded` and chain link and names these grounds ([Retention, and who chooses it](audit.md#retention-and-who-chooses-it)); **409** for a tombstone or while the local audit store is off | -| `GET {ext}/admin/access-log` | `?ehr_id=…&from=…&to=…&outcome=…&offset=…&fetch=…` and the other filters | **200**: the access log's records across EHRs, newest first, in the full view ([Reading the access log over ITS-REST](audit.md#reading-the-access-log-over-its-rest)); the read writes its own access-log entry | +| `POST {ext}/admin/access-log/erase` | `{"uid": "…", "grounds": [DV_CODED_TEXT, …]}` | **200**: the `ACCESS_LOG_TOMBSTONE` that replaced the access-log entry, for an erasure a law orders before the entry's retention ends; it keeps the entry's uid, `system_id`, `time_recorded` and chain link and names these grounds ([Retention, and who chooses it](ehds-logging.md#retention-and-who-chooses-it)); **409** for a tombstone or while the local audit store is off | +| `GET {ext}/admin/access-log` | `?ehr_id=…&from=…&to=…&outcome=…&offset=…&fetch=…` and the other filters | **200**: the access log's records across EHRs, newest first, in the full view ([Reading the access log over ITS-REST](access-log.md#reading-the-access-log-over-its-rest)); the read writes its own access-log entry | | `GET {ext}/admin/access-log/seals` | `?from_id=…&to_id=…` | **200**: `seals`, each window that covers an entry id of the span, less than 10000 apart, with its `window_no`, `first_id`, `last_id`, `entries`, `previous_digest`, `digest` and `folded`; **400** for a span of 10000 or longer | | `GET {ext}/admin/access-log/checkpoint` | `?sequence=…`? | **200**: the newest stored `ACCESS_LOG_CHECKPOINT`, or the one at `sequence`; **404** when none is stored there | -| `POST {ext}/admin/ehr-access` | `{"ehr_id": "…", "preceding_version_uid": "…", "settings": {…} or null}` | **200** `{"ehr_id", "version_uid"}`: the `EHR_ACCESS` settings are committed on the person's instruction as a new version over `preceding_version_uid`; they hold the EHDS Art. 8 restriction and the Art. 10 opt-out as `restriction` and `opt_out` directives ([Security](security.md#restriction-of-access-by-health-professionals-ehds-art-8)); **400** for settings that do not parse; **422** for settings that break an invariant of the draft model, a restricted object id that names no versioned object, or an `opt_out` directive while `[authz.grants] allowed` does not allow `access_service`; **412** when `preceding_version_uid` is not the current version | +| `POST {ext}/admin/ehr-access` | `{"ehr_id": "…", "preceding_version_uid": "…", "settings": {…} or null}` | **200** `{"ehr_id", "version_uid"}`: the `EHR_ACCESS` settings are committed on the person's instruction as a new version over `preceding_version_uid`; they hold the EHDS Art. 8 restriction and the Art. 10 opt-out as `restriction` and `opt_out` directives ([Security](access-control.md#restriction-of-access-by-health-professionals-ehds-art-8)); **400** for settings that do not parse; **422** for settings that break an invariant of the draft model, a restricted object id that names no versioned object, or an `opt_out` directive while `[authz.grants] allowed` does not allow `access_service`; **412** when `preceding_version_uid` is not the current version | | `GET {ext}/admin/ehr-access` | `?ehr_id=…` | **200** `{"ehr_id", "versions": [{"version_uid", "settings"}]}`: every `EHR_ACCESS` version, newest first, so the person's lifted restrictions and reversed opt-outs stay readable | | `POST {ext}/admin/ehr-access/repair` | `{"ehr_id": "…", "settings": {…}}` | **200** `{"ehr_id", "version_uid"}`: the `EHR_ACCESS` of an EHR held closed by settings that do not parse is committed again with these settings, which must parse; **409** for an EHR that is not held | @@ -314,11 +315,11 @@ objection](compliance/retention.md). An access restriction is not a restriction of processing: it limits what a health professional reaches and nothing else, and it is invisible to them. What it changes is on [restriction of access by health -professionals](security.md#restriction-of-access-by-health-professionals-ehds-art-8). +professionals](access-control.md#restriction-of-access-by-health-professionals-ehds-art-8). An access delay is the opposite direction: it withholds a composition from the person, never from a professional. What it changes is on [delayed access -by the person](security.md#delayed-access-by-the-person-ehds-art-33). +by the person](access-control.md#delayed-access-by-the-person-ehds-art-33). ## Re-keying a professional's binding key @@ -338,371 +339,9 @@ binding in the same commit, and one access record carries both keys. The route answers **403** when the new key is the requesting administrator's own login, **409** when the `PERSON` carries no key of that issuer or the new key is already bound to another party, and **404** for an unknown or -deleted `PERSON`. The [party mapping](installation/config-auth.md#the-party-mapping) +deleted `PERSON`. The [party mapping](installation/config-authz.md#the-party-mapping) says which parties are protected. -## Storage integrity - -Two routes that check the stored data against itself and repair what they -find, behind the same switch and role. FerroEHR stores every version's content twice: once as the -materialized document a point read serves, and once as the decomposed rows the -AQL engine queries. A commit writes both in the same transaction, so they -always agree; anything that changes one of them behind the server's back -breaks that agreement. - -| Route | **200** body | -|---|---| -| `POST {ext}/admin/integrity/verify` | the sweep report | -| `POST {ext}/admin/integrity/rebuild-nodes` | the rebuild report | - -The sweep covers **both pseudonymisation domains**, clinical and demographic, -in one pass. Every finding names the domain it came from, so a report can never -describe half the store while looking like it described all of it. It re-derives -every stored version from its decomposed rows and compares the result with the -stored document, then decomposes that document again and compares the rows it -would write, which is what catches rows an older release left in a shape this -one no longer produces. It reads the archived tier as well, takes -no lock, and runs outside the request path of any clinical call, so it is safe -to run on a live server. It is also a full scan of what it covers, so schedule -it rather than calling it per request. - -Four optional query parameters narrow the scan, and they compose. Both routes -take the same set: - -| Parameter | Effect | -|---|---| -| `ehr_id` | cover only versions belonging to that EHR | -| `vo_id` | cover only versions of that versioned object | -| `sys_version` | cover only that version of it; the ordinal is per-object, so it needs `vo_id` and is a **400** on its own | -| `committed_since` | cover only versions whose validity begins at or after that RFC 3339 instant | - -Use them. Verifying one record after a support incident, or everything written -since a known point, costs a fraction of a full repository scan. - -### Verifying a whole large repository - -By default the route computes the whole report before it answers, so it has to -finish inside the server's 30-second request timeout. Send -`Accept: application/x-ndjson` and it streams the same sweep instead, writing -each finding as it is made. Nothing bounds that response, so this is how you -verify a repository too large to scope: - -```bash -curl -sN -X POST \ - -H 'Accept: application/x-ndjson' \ - "$BASE/admin/integrity/verify" -``` - -The body is one JSON object per line, each carrying a `type`: - -| `type` | When | Carries | -|---|---|---| -| `mismatch` | as each disagreement is found | the same five fields the report's `mismatches` entries carry, `domain` included | -| `progress` | once per page of versions read | the counts so far | -| `summary` | once, at the end | the final counts and `elapsed_ms` | -| `error` | instead of `summary`, if the sweep failed part-way | a short message; the detail is in the server log | - -Two consequences are worth planning around. The status code is sent before the -work is done, so a sweep that fails half-way still answered `200`: read to the -end and check that the last line is a `summary`, not an `error`. And the stream -carries no reporting cap, so every mismatch reaches you rather than the first -thousand. - -The stream has to be asked for by name. A request sending `*/*`, or no `Accept` -at all, gets the aggregated document below, unchanged. - -```json -{ - "versions_checked": 128, - "versions_with_body": 126, - "versions_without_body": 2, - "mismatch_count": 1, - "mismatches": [ - { - "domain": "clinical", - "vo_id": "8849182c-82ad-4088-a07f-48ead4180515", - "sys_version": 2, - "kind": "COMPOSITION", - "defect": "content_differs" - } - ], - "truncated": false, - "elapsed_ms": 431 -} -``` - -`domain` is `clinical` or `demographic`, naming the schema the damaged version -lives in. It is also what the repair below uses to reach it. - -`defect` is one of five values: - -- `content_differs`: both copies exist and hold different content. -- `nodes_missing`: the version has a stored document but no decomposed rows. -- `nodes_unreadable`: the decomposed rows exist but no longer form one tree. -- `unexpected_nodes`: the version is a logical delete, which stores no - document, yet decomposed rows exist for it. -- `stale_decomposition`: the rows hold exactly the stored document, but not in - the shape this version of the server decomposes it into. An older release - wrote them. The content is intact and every read serves it correctly; what is - stale is the index over it, so a query that depends on the current shape does - not reach this version until the repair below rewrites its rows. -- `orphan_nodes`: decomposed rows exist that no stored version reads, because - their version is gone or lives in the other storage tier. `kind` names the - class of the rows' root. The sweep reports them once it has read every - version of a domain, and a sweep scoped by `committed_since` leaves them out, - since rows without a version have no commit time. - -`mismatch_count` is the full count. `mismatches` is capped at 1000 entries and -`truncated` says whether the cap was reached; every mismatch is logged at -`warn` level with its identifiers whatever the cap does, so a truncated report -never loses a finding. The log line and the response carry identifiers only, -never content. - -A finding is **not** a request failure: the sweep ran and is telling you what -it saw, so the status stays **200** and the report is the body. Check -`mismatch_count`, not the status code. - -> [!NOTE] -> This is the companion check to [digest signing](signing/digest.md). A stored -> digest covers the document a point read serves; it says nothing about the -> decomposed rows, which no read-path check recomputes. Together the two cover -> both copies. - -### Repairing what the sweep found - -The sweep is the diagnosis. `POST {ext}/admin/integrity/rebuild-nodes` is the -repair: it re-derives the decomposed rows of every damaged version from that -version's stored document, one transaction per version. - -```bash -curl -s -X POST "$BASE/admin/integrity/rebuild-nodes?ehr_id=$EHR_ID" -``` - -It runs the same sweep first and writes only the versions that sweep reports -damaged, so a run over healthy data writes nothing at all. The scope -parameters are the same four, so a repair can be as narrow as one version: - -```bash -curl -s -X POST \ - "$BASE/admin/integrity/rebuild-nodes?vo_id=$VO_ID&sys_version=2" -``` - -Which copy wins is not a choice the route makes. The stored document is the -version's canonical serialized form, the bytes a point read serves and the -bytes a digest was taken over; the decomposed rows are an index derived from -it. So the repair only ever runs in that direction, and a version whose -**document** is the damaged copy is refused rather than having the damage -copied into the index. - -Each version is repaired inside one transaction: the document is read under a -row lock, decomposed, the old rows deleted, the new set inserted, and the -version re-derived from what was just written and compared with the document -before the commit. Anything that fails rolls that transaction back, so the -version's rows are left exactly as they were. One refusal never stops the run -that found it. - -An archived object is thawed for the repair and re-archived in the same -transaction, marker and all, because a write to a versioned object always -happens in the primary tier. - -A logically deleted version stores no document, so it rebuilds to no rows, -which is the repair for `unexpected_nodes`. Rows reported `orphan_nodes` have no -document to rebuild from, so the rebuild deletes them. - -The same route is the upgrade step after a release that changes how content is -decomposed. Rows written by the older release hold the right content, so -nothing is damaged, but they are the wrong shape for the new one and the sweep -reports them `stale_decomposition`. Rebuilding writes them again from the -stored document, which is all the upgrade is. Run it unscoped once and the next -sweep is clean: - -```bash -curl -s -X POST "$BASE/admin/integrity/rebuild-nodes" -``` - -The changelog names the affected object type at each such release. - -```json -{ - "versions_checked": 128, - "versions_damaged": 2, - "versions_rebuilt": 1, - "versions_refused": 1, - "records": [ - { - "domain": "clinical", - "vo_id": "8849182c-82ad-4088-a07f-48ead4180515", - "sys_version": 2, - "kind": "COMPOSITION", - "defect": "content_differs", - "outcome": "rebuilt", - "node_rows": 41 - }, - { - "domain": "demographic", - "vo_id": "1f0b7d64-6b2a-4a1f-9f0e-6b1d2a3c4d5e", - "sys_version": 1, - "kind": "PERSON", - "defect": "content_differs", - "outcome": "refused", - "reason": "the stored body does not decompose: ..." - } - ], - "truncated": false, - "elapsed_ms": 812 -} -``` - -`defect` is the sweep verdict that selected the version, from the five values -above. `outcome` is `rebuilt`, carrying the `node_rows` the version now has, or -`refused`, carrying the `reason`. `records` is capped at 1000 entries with -`truncated` saying whether the cap was reached; every record is logged at -`info` level with its identifiers whatever the cap does. - -A refusal is **not** a request failure, so the status stays **200**. Check -`versions_refused`: anything above zero means a stored document is itself -damaged, and that is a restore-from-backup question rather than a rebuild one. - -Unlike the sweep, this route writes, so a server in read-only mode refuses it. - -## Dump and load - -Two routes that move the whole repository to and from an archive on the -**server's** file system, behind the same switch and role. Both answer **200** -with a JSON array of per-entity failure reports; an **empty** array means -everything succeeded. - -### `POST {ext}/admin/dump` - -Writes an archive of every EHR **and of every standalone demographic -container**: the parties and party relationships that live outside any EHR. -The body is `{"file_sys_loc": "…"}` plus the optional export settings: - -| Field | Values | Default | -|---|---|---| -| `logical_format` | `openehr_canonical_json` or `openehr_canonical_xml` | canonical JSON | -| `compression_format` | `zip` or `7z` (omit for loose files) | uncompressed | -| `segment_split_size` | segment size in kb (a positive integer) | `1024` | - -`logical_format` chooses how the clinical **content** is serialized, not how -the archive is packaged: - -- `openehr_canonical_json` (the default) keeps each version's content inline - in the segment files, exactly as this server stores it. -- `openehr_canonical_xml` writes each version to its own - `versions/.xml` entry instead: a complete `ORIGINAL_VERSION` - document under the openEHR-published `` root, ready to hand to any - tool that reads canonical openEHR XML. - -The archive is a directory holding a `manifest.json`, one or more -`segment-NNNN.json` files, and a `blobs/` subdirectory for any externalized -multimedia. When the repository holds standalone demographic containers, the -archive additionally carries a `demographic-commons.json` (their shared -audits and contributions) and one or more `demographic-NNNN.json` segments, -one record per party or relationship, in the same version-record shape the -EHR segments use. With `compression_format` set, those same entries are -packed into a single `archive.zip` or `archive.7z` inside the location -instead. The -archive's own bookkeeping (the manifest and the segment skeleton) stays JSON -in both logical formats, because openEHR publishes no XML document form for -it. - -### `POST {ext}/admin/load` - -Populates the repository from an archive. It takes the location and nothing -else: the container (loose files, a single `archive.zip`, or a single -`archive.7z`) is detected from what the location holds, and the logical format -is read from the archive's own manifest, so a load never has to be told how -the dump was written. Archives written before the demographic wave existed -simply carry no demographic entries and load unchanged. - -The repository being loaded into **need not be empty**. An EHR whose id is -already present is reported and skipped rather than failing the load, so the -response array names each one; and a standalone demographic container that -already exists is reported the same way, under its own kind (`PERSON`, -`ORGANISATION`, `GROUP`, `AGENT`, `ROLE`, or `PARTY_RELATIONSHIP`) as the -`entity_type`: - -```json -[ { "entity_type": "EHR", - "entity_id": "7d44b88c-4199-4bad-97dc-d78268e01398", - "dump_status": false, - "error": "an EHR with this id already exists" } ] -``` - -Both directions are lossless: a dump and a load reproduce every record, -whichever format and container you choose. - -### Refusals - -| Status | When | -|---|---| -| **400** | a missing or blank `file_sys_loc`; a format value outside the lists above; a non-positive `segment_split_size`; an `encoding` field (the openEHR service model declares that enumeration with no members, so no value a client could send names one); on load, an archive carrying externalized multimedia this server has no store for, and a malformed archive (a mangled or truncated container, manifest, segment or blob entry, or a manifest naming no known format), the [`archive-invalid`](using-the-api/problems.md#archive-invalid) problem, which names the entry. Nothing is loaded | -| **415** | the request `Content-Type` is not `application/json` | -| **500** | a location that holds **no** archive, or one the server's filesystem refuses to read: the service model's `file_not_writable` error for these operations. Nothing is loaded. On dump, the same status covers a location, segment, payload entry or manifest that could not be created or written | - -A single unreadable `versions/*.xml` entry is *not* in that family: it belongs -to one EHR, so that EHR is reported in the response array and skipped whole -while the rest of the archive loads. - -> [!NOTE] -> The activity report, the archive routes and the dump/load pair are FerroEHR -> extensions: the openEHR *service model* defines these operations, but the -> released REST API surfaces no endpoint for them, so their URLs are our own. -> The two `…/restore` routes go one step further: the service model declares -> the archive calls and no un-archive counterpart, so both the operation and its -> URL are ours. They gate no openEHR conformance claim; see -> [Conformance](conformance.md). - -## EHR Extract export and import - -Four routes under `{ext}/message` that move whole records between systems. -Unlike the admin extensions above, these are **not** admin-gated; see -[the gate table](#where-these-routes-live-and-what-gates-them). - -- `GET {ext}/message/export/{ehr_id}`: export one whole EHR. **200** with a - JSON array holding one `EXTRACT` that carries every versioned object of the - EHR, latest versions only. **400** if `ehr_id` is not a well-formed - identifier, which is refused before any lookup; **404** if the EHR does not - exist; **406** if `Accept` cannot be satisfied (the extract list is JSON - only). -- `POST {ext}/message/export` with an `EXTRACT_SPEC` body — export by - specification. **200** with one `EXTRACT` per manifest entity, in manifest - order. The manifest must name at least one entity, and each entity must - name its record by `ehr_id` or `subject_id`, otherwise **400**; an - identifier that names nothing is **404**. `extract_type` must be one of the - extract-content-type codes the openEHR Reference Model names - (`openehr-ehr`, `openehr-demographic`, `openehr-synchronisation`, - `openehr-generic`, `generic-emr`) or the catch-all `other`; anything else - is **400**, as is a selection this service does not support (search - criteria, an unsupported commit-time interval). This route is classified as - a **read**: it selects over held versions and commits nothing, exactly like - the ad-hoc AQL `POST`. -- `POST {ext}/message/import` with an `EXTRACT` body — clone a whole EHR. Add - `?ehr_id=` to fix the identifier the clone lands under; leave it off - and the source identifier the extract carries is re-used. **201** with - `{"uid": ""}`, so a caller that supplied no id still learns what was - created. The extract must carry an `EHR_STATUS` (**400**), and the target - must not already exist: **409**, which also covers an imported `EHR_STATUS` - naming a subject another EHR already holds. -- `POST {ext}/message/import/{ehr_id}` with an `EXTRACT` body — add the - extract's content to an **existing** EHR as new versions. **204**. **404** - if the EHR does not exist; **409** if the EHR already holds an `EHR_STATUS` - or `EHR_ACCESS` under a different object id, or the imported status names - another EHR's subject; **422** if a version in the extract is semantically - invalid (template, RM-invariant or terminology validation). - -All four accept either `application/json` or `application/xml` bodies; any -other `Content-Type` is **415**. - -> [!NOTE] -> The whole `{ext}/message` group is a FerroEHR extension: the openEHR service -> model defines a Message component, but the released REST API publishes no -> message or extract endpoint at all. These URLs are our own and gate no -> openEHR conformance claim; see [Conformance](conformance.md). For the -> workflow-level view (what an extract is good for and how to drive an -> import) see [EHR Extract & messaging](beyond-core/messaging.md). - ## Other routes under `{base}/admin` The outbox feed shares the `/admin` path prefix but **not** the diff --git a/website/book/src/operations-decommissioning.md b/website/book/src/operations-decommissioning.md index 44d1c1ffbf..1cd39615b1 100644 --- a/website/book/src/operations-decommissioning.md +++ b/website/book/src/operations-decommissioning.md @@ -25,7 +25,7 @@ command: years after the last treatment or after death. If the records must survive the instance, move them first: export each EHR over the API, or take a full dump through `/ferroehr/rest/extensions/v1/admin/dump` - ([dump and load](operations-admin-apis.md#dump-and-load)), and check the + ([dump and load](storage-admin-apis.md#dump-and-load)), and check the copy in its new home before you erase. The retention marks and what is already due are described in [Retention, restriction and objection](compliance/retention.md). @@ -34,7 +34,7 @@ command: in Switzerland ([Audit](installation/config-audit.md)). The erase deletes the `audit` schema. Take a dump of it first and keep that dump for the longest period that applies to you - ([Backup and point-in-time recovery](operations.md#backup-and-point-in-time-recovery)). + ([Backup and point-in-time recovery](database-operations.md#backup-and-point-in-time-recovery)). A dump kept for this reason is still personal data and needs the same protection as the instance had. - **Data subjects and processors.** If the instance served other organisations @@ -149,7 +149,7 @@ DROP DATABASE ferroehr WITH (FORCE); ``` Run it as the owner or a superuser, connected to another database -([DROP DATABASE](https://www.postgresql.org/docs/18/sql-dropdatabase.html)). +([DROP DATABASE](https://www.postgresql.org/docs/19/sql-dropdatabase.html)). Repeat it for every database `[database.party]` or `[database.audit]` names. The roles are cluster-wide, so neither command removes them: the migrations @@ -162,7 +162,7 @@ DROP ROLE ferroehr_clinical, ferroehr_clinical_reader, ferroehr_party, ferroehr_party_reader, ferroehr_migrator; ``` -[DROP ROLE](https://www.postgresql.org/docs/18/sql-droprole.html) refuses a +[DROP ROLE](https://www.postgresql.org/docs/19/sql-droprole.html) refuses a role that still owns objects or holds privileges in any database of the cluster. diff --git a/website/book/src/operations-reset.md b/website/book/src/operations-reset.md index 5c1d4713b4..f19a25b69d 100644 --- a/website/book/src/operations-reset.md +++ b/website/book/src/operations-reset.md @@ -18,7 +18,7 @@ the next boot starts as a fresh install. > EU Member State, five in the Netherlands, one in Switzerland; see > [Audit](installation/config-audit.md)), and your duty to keep it does not end > when the instance does. Take a backup of every domain first, the audit trail -> included ([Backup and point-in-time recovery](operations.md#backup-and-point-in-time-recovery)), +> included ([Backup and point-in-time recovery](database-operations.md#backup-and-point-in-time-recovery)), > and keep it for that horizon. A reset does not reach anything outside the instance. Your logical dumps, WAL @@ -35,7 +35,7 @@ The reset has two halves, and you need both: state is the release's own file and no overrides. - **Database:** drop the database and let the release's migrations build it again. Drop the whole database, never single schemas - ([Recovering a partially wiped database](operations.md#recovering-a-partially-wiped-database) + ([Recovering a partially wiped database](database-operations.md#recovering-a-partially-wiped-database) explains why). The `deployment.profile` the release ships is `sandbox`, so a reset instance @@ -108,7 +108,7 @@ The chart deploys no database, so the two halves are separate operations. ``` `WITH (FORCE)` terminates the sessions still connected - ([DROP DATABASE](https://www.postgresql.org/docs/18/sql-dropdatabase.html)). + ([DROP DATABASE](https://www.postgresql.org/docs/19/sql-dropdatabase.html)). Use the owner your deployment provisioned the database with. If `[database.party]` or `[database.audit]` name databases of their own, drop and recreate each of those too. The domain roles are diff --git a/website/book/src/operations.md b/website/book/src/operations.md index 95de6153e8..1ee0f4e4ad 100644 --- a/website/book/src/operations.md +++ b/website/book/src/operations.md @@ -3,387 +3,15 @@ Running a clinical data repository in production means more than starting the binary: the database must be backed up and least-privileged, traffic must be encrypted, upgrades must be safe while the service stays up, and you need to -see what the system is doing. This chapter is a production checklist (database -roles, TLS, backup and point-in-time recovery, upgrades and migrations, -observability, the health probes, and the management surface) drawn from how -the container image and Helm chart are built to run. The -operator-facing HTTP surfaces have their own page: -[Admin & messaging APIs](operations-admin-apis.md). +see what the system is doing. This chapter covers TLS, the container image, +observability, the health probes and the management surface. The database +has its own page, [Database roles, migrations and +backup](database-operations.md), and so do [Storage sizing](storage-sizing.md), +[Upgrades](upgrades.md) and the [Admin & messaging +APIs](operations-admin-apis.md). -## Database roles and least privilege - -FerroEHR connects to an **external** PostgreSQL 19: a managed service or an -operator-run cluster, never a chart-side sidecar, because a database holding -PHI must be independently backed up and recoverable. The server carries only a -connection string, ideally sourced from a secret. - -The database never runs as a superuser at runtime. Two roles cover -provisioning and migration: - -| Role | Purpose | Used by | -|---|---|---| -| owner | owns the database | provisioning only | -| `ferroehr_migrator` | runs the schema migrations; owns the helper functions | the migration step | - -and four cover serving, split by **pseudonymisation domain**, the clinical -record and the identity of its subject: - -| Role | Reads and writes | Barred from | -|---|---|---| -| `ferroehr_clinical` | `clinical`, archival tier included | `party` | -| `ferroehr_party` | `party`, archival tier included | `clinical` | -| `ferroehr_clinical_reader` | read-only over `clinical` | `party` | -| `ferroehr_party_reader` | read-only over `party` | `clinical` | - -The migrations create these roles idempotently, apply the per-schema grants, -**and revoke every other domain explicitly in both directions**, and revoke the -ability to create objects in the public schema. All four are `NOINHERIT` and -none is a member of another, so a boundary cannot be crossed by picking up a -membership. GDPR Art. 4(5) defines pseudonymisation as processing where -attribution to a person needs additional information "kept separately and -subject to technical and organisational measures", and Art. 32(1)(a) names it a -security measure for health data -(); EDPB Guidelines 01/2025 -require that separation to hold against internal actors, operators with -database access included. - -Each serving role holds `SELECT`/`INSERT`/`UPDATE`/`DELETE` on its own domain's -tables, `EXECUTE` on the `ext` helper functions, and `MAINTAIN` on its store's -partitioned tables (and `ehr`, for `ferroehr_clinical`), and nothing else: it is not -a superuser, does not bypass row-level security, and cannot create, alter or -drop a table, index, schema or role. On the audit trail it is narrower still: -it may record an event and stamp it forwarded, and it holds no privilege that -can rewrite or remove one (see [Audit](audit.md)). - -`MAINTAIN` is there so the server can keep those tables' planner statistics -(see [Planner statistics of the partitioned tables](#planner-statistics-of-the-partitioned-tables)). -It also allows `VACUUM`, `CLUSTER`, `REINDEX` and `LOCK TABLE` on exactly -those tables. The role can already write every row of them, so what it adds -is the locks and index rebuilds those commands take. The reader roles do not -hold it. - -### Turning the schema split into a role split - -The **schema** separation is unconditional: the server always reads and writes -parties in `party`, whatever it authenticates as, and each of the three pools -carries only its own schema on its `search_path`. The **role** separation is a -deployment choice, and it is one configuration table per domain: - -```toml -[database.party] -url = "postgres://ferroehr_party:***@pg:5432/ferroehr" -``` - -(or `url_file`, for a mounted secret). With a domain's `url` set the server -opens that pool on that credential, and a flaw that reaches one of them reaches -one domain. Left unset, the domain uses `[database].url` and the separation is -schema-only. Set both domains and no credential the server uses can join a -party to its EHR in SQL; the crossing happens in the application, over -two connections, and is recorded as an access event (see [Security → Resolving -across the boundary](security.md#resolving-across-the-boundary)). - -A DSN that names another host moves the domain to a **database or cluster of its -own**, which is the separation a schema cannot make: a base backup, WAL -archiving and physical replication carry every schema of a database together -([PostgreSQL 18, Backup and -Restore](https://www.postgresql.org/docs/18/backup-dump.html)). - -Two boot checks make the posture honest. Two domains configured on **different** -DSNs that authenticate as the **same** database role are refused — a separation -that exists only in the configuration reads as one that holds, which is worse -than none. And a domain role that does not exist is a warning under -`deployment.profile = "sandbox"` and a refusal under `production`: absent roles -mean absent grants, and the boundary check would otherwise pass by having -nothing to measure. - -### Which credential prepares the schema - -**None of the domain credentials.** Preparing a database spans every schema in -it at once: the DDL of each resident migration set under `[database] migrations = "apply"`, -and their `_sqlx_migrations` bookkeeping tables under `"verify"` — a read, but a -read across the whole database. Each runtime role holds exactly one domain, so -none can do it, and `verify` is not the exception: a role that is a member of -`ferroehr_clinical` and nothing else is refused on the very first set: it -cannot read the `ext`, `party` or `audit` bookkeeping. - -So the credential that prepares the schema is named separately, and the server -uses it for that one boot step: - -```toml -[database] -url = "postgres://ferroehr_clinical:***@pg:5432/ferroehr" -migrate_url = "postgres://ferroehr_migrator:***@pg:5432/ferroehr" - -[database.party] -url = "postgres://ferroehr_party:***@pg:5432/ferroehr" -``` - -`migrate_url` prepares every domain that reaches the same DATABASE it does, -which is all of them in the posture above: three credentials, one database. A -domain whose DSN reaches a DIFFERENT database is prepared there on that -database's own migrator, `[database.]` migrate_url`, because -`migrate_url` names one database and a relocated domain is not in it; unset, it -falls back to the domain's own DSN, which a DML-only role cannot use. Which case a domain is in is read from the server itself -(`pg_control_system()` and `current_database()`), never from the DSN text — two -DSNs that differ only in their credential reach the same database. - -(or `migrate_url_file`, for a mounted secret). The connection is opened for -preparation and closed again: no pool is held on it, and no request is ever -served through it. Left unset it falls back to `url`, which is exactly what a -single-credential deployment has always run — its behaviour is unchanged by -this key existing. - -A credential that cannot read a set is told which schema and which role, so -the fix is visible from the message: - -```text -database role `app_ehr` cannot read the migration state of schema -`ext`: … point `[database] migrate_url` (or `migrate_url_file`) at the credential -that prepares the schema — unset, it falls back to `[database] url` — and, for a -domain in a database of its own, `[database.]` migrate_url` at that -database's migration credential -``` - -Either way the server **refuses to boot** when the grants themselves are wrong: -a self-check enumerates every table, view, sequence and function in each -domain and fails, naming the role and the object, if either runtime role can -read across the boundary. `ferroehr db verify` runs the same check. When the -four roles do not exist at all (the development, compose and test-harness case, -where the migrator holds no `CREATEROLE`) the check warns rather than inventing -a failure — under `deployment.profile = "production"` it refuses, because absent -roles mean absent grants and there is then nothing to measure. - -On Kubernetes the same choice is chart values, mounted as files the same way -the clinical DSN is, so no credential enters the pod's environment: - -```yaml -database: - existingSecret: ferroehr-db # postgres://ferroehr_clinical:… - party: - existingSecret: ferroehr-db-party # postgres://ferroehr_party:… - audit: - existingSecret: ferroehr-db-audit # the audit repository's own DSN - migrateExistingSecret: ferroehr-db-migrator # postgres://ferroehr_migrator:… -``` - -Leave a domain's block unset and that pool uses the shared DSN, which is the -schema-only posture. - -Provisioning the four roles is yours in both cases. The migrations create them -only when the migrator holds `CREATEROLE` and skip them with a `NOTICE` -otherwise, so on a managed database — where the migrator usually does not — -create them before the first deploy: - -```sql -CREATE ROLE ferroehr_clinical NOLOGIN NOINHERIT; -CREATE ROLE ferroehr_party NOLOGIN NOINHERIT; -CREATE ROLE ferroehr_clinical_reader NOLOGIN NOINHERIT; -CREATE ROLE ferroehr_party_reader NOLOGIN NOINHERIT; -``` - -then give each login role membership of exactly one of them. -`ferroehr db verify` tells you whether the boundary holds afterwards. - -The local Audit Record Repository is written on its own pool -(`[database.audit]`), and the `audit` schema is granted to `ferroehr_clinical` -(record an event, stamp it forwarded, run the retention reaper, verify the -chain) and to `ferroehr_clinical_reader` (read it and verify the chain). A -clinical login role that is a member of `ferroehr_clinical` alone writes its own -access log; no extra membership is needed. The audit trail is not a -pseudonymisation domain, so this grant adds no reach into `party`. - -The compose stacks create the four domain roles and grant the clinical and party domains to -the single dev login role, which owns the database. That -demonstrates the schema separation and exercises the boot self-check; it is -deliberately **not** the credential separation, because one container with one -DSN cannot show that half honestly. - -### Which of these postures is exercised, and which is not - -A recommendation nothing runs is a guess. This is what the suites cover. - -Exercised against a real PostgreSQL 19: - -- Two runtime credentials serving both domains through the assembled router, - each of the server's own pools refused every relation of the other domain - (`app/ferroehr-rest/tests/it/credential_separation.rs`), and the single-DSN - fallback still serving both. -- All four domain roles refused every relation in the domain they do not own, - enumerated from `information_schema` rather than from a written list - (`app/ferroehr/tests/it/pseudonymisation_boundary.rs`). -- The boot sequence on separated credentials with `[database] migrate_url`, under - both `verify` and `apply`, and the single-DSN fallback under both - (`app/ferroehr/tests/it/schema_preparation_credential.rs`). -- The party domain relocated to a second database, prepared and verified - there on `[database.party]`, and the - refusal when the domain's two DSNs reach different databases - (`app/ferroehr/tests/it/relocated_domain_preparation.rs`). -- The chart's production overlay on three PostgreSQL clusters, one per domain, - prepared by the migration Job and booting under `production` - (`scripts/deploy-probe-k8s.sh --production-only`, probes P-K8S-PROD-BOOT and - P-K8S-PROD-SHARED). -- The compose stack's grant boundary read back from the running database by - `scripts/deploy-probe.sh`, which also records that the stack is - single-credential by design. - -Not exercised by anything, and stated rather than left to inference: - -- **A real deployment on separated DSNs**: a container booting with the DSN - files mounted, and the chart wiring them through - `database.party.existingSecret` and `database.migrateExistingSecret`. What is covered is the in-process half. -- **Role provisioning on a managed database** where the migrator holds no - `CREATEROLE` and the roles are created by the manual step above. - -Which posture you actually get depends on `[database] migrations`, because the server's -embedded migrations are DDL: a self-migrating deployment necessarily runs as a -role that can execute DDL. The single-container quickstart takes that path: its -DSN authenticates as a non-superuser role that owns the database and is a member -of `ferroehr_migrator`, `ferroehr_clinical` and `ferroehr_party`. - -## Applying migrations - -`[database] migrations` decides who runs the schema: - -- **`apply`** (the default): the server applies its embedded migrations at - boot. This is what makes a fresh checkout and an empty database work with no - configuration at all, and it is the right choice for development and for - small single-tenant deployments. The runtime DSN must be a member of - `ferroehr_migrator`, so the serving process holds DDL rights for its whole - life. Least isolation. -- **`verify`:** the server issues **no DDL at all**. At boot it checks that the - database carries exactly this build's migrations and refuses to start - otherwise, naming the schema and what is wrong with it. The pools can then - hold no schema rights at all, which is the least-privilege production - posture: an application-level SQL flaw can reach rows, never the schema. The - check itself still reads every schema's bookkeeping, so it runs on - `[database] migrate_url` — see [which credential prepares the - schema](#which-credential-prepares-the-schema), and set that key whenever - `database.url` is a role that holds one domain. - -Migrations are **append-only** within a major release line: a released -migration is never edited, because sqlx records a checksum of each applied file -and refuses a database whose recorded checksum no longer matches, so a -corrected schema arrives as a new migration rather than as a change to an old -one. A CI guard fails any pull request that modifies, renames or deletes a -migration a release carries. v6.0.0 starts the line again from one baseline per -schema, so a v5 database is not upgraded in place; see -[Upgrading from v5 to v6](#upgrading-from-v5-to-v6). - -With `verify`, something else has to run the migrations first. Use the binary's -own subcommand under the migrator DSN: a CI/CD stage, a one-shot job, or the -Helm chart's `migrations.job.enabled` pre-install/pre-upgrade hook Job, which -Helm waits on so a failed migration fails the release (it takes its own -`migrations.job.existingSecret` holding the migrator DSN, deliberately a -different credential from the runtime one, and rendering fails without it): - -```shell -FERROEHR__DATABASE__URL='postgres://ferroehr_migrator:***@pg:5432/ferroehr' \ - ferroehr db migrate # applies; exits when done -FERROEHR__DATABASE__URL='postgres://ferroehr_clinical:***@pg:5432/ferroehr' \ -FERROEHR__DATABASE__MIGRATE_URL='postgres://ferroehr_migrator:***@pg:5432/ferroehr' \ - ferroehr db verify # read-only check; exit 0 iff the schema is current -``` - -`db verify` splits the same way the boot sequence does, and for the same -reason: the schema state is read on `migrate_url`, while the pseudonymisation -boundary is measured on the runtime DSNs — asking the migrator credential -whether it can reach every domain would answer yes by design and tell you -nothing about the roles that serve requests. - -Gate the rollout on the migration step so two server versions never race the -schema. Note the difference in failure shape: a `verify` server refuses to boot -against an unmigrated database (loud, immediate), while an `apply` server that -loses its schema later stays up and reports readiness `DOWN`, the warning -below. - -> [!WARNING] -> **Migration is a boot step, and nothing re-runs it.** A running instance whose -> database is replaced, wiped, or reachable-but-empty does not migrate. It reports -> -> ```json -> {"state":"down","phase":"serving","indicators":[{"name":"db","state":"up"}, -> {"name":"migrations","state":"down"}]} -> ``` -> -> on `/health/readiness` (`503`), with the detail `core schema tables missing -> (migrations not applied)` on `/management/health`, leaves the load balancer's rotation, and keeps -> passing liveness (correctly, since the process is healthy) so nothing restarts -> it. Under Kubernetes that is a Deployment sitting at `0/N` ready with no error -> after the first one. -> -> The readiness check re-tests the schema on **every probe**, so recovery does not -> require a restart *of that instance*: it goes back to `UP` within one probe -> interval of the schema existing, whoever created it. What needs a restart is the -> case where the only thing that would migrate is the instance itself: then -> `kubectl rollout restart deploy/ferroehr` (or a migration job) is the remedy. -> -> For the out-of-band flow this means: the migration step must **complete before** -> the first instance starts, or that instance sits unready until the schema -> appears, harmless but confusing, and it delays the rollout rather than failing -> it. Gate the rollout on the migration job. - -### Planner statistics of the partitioned tables - -`node`, `version` and `vo_attestation` are partitioned by storage tier in both -stores, and PostgreSQL estimates a join over them from the statistics of the -partitioned table itself. Autovacuum analyzes the partitions and never the -partitioned table (PostgreSQL 18, §24.1.3 Updating Planner Statistics), so -FerroEHR runs `ANALYZE ONLY` on the partitioned tables itself, and on `ehr` -while autovacuum has never analyzed it: - -- after it applies the migrations, as the migration credential; -- after `load_ehrs` loads an archive; -- at boot and then every hour, as each store's serving role. - -Without these statistics an AQL `CONTAINS` can read every COMPOSITION's -nodes. `ANALYZE` needs the `MAINTAIN` privilege on the table, and the -migrations grant it to `ferroehr_clinical` on `clinical.node`, -`clinical.version`, `clinical.vo_attestation` and `clinical.ehr`, and to -`ferroehr_party` on the three partitioned tables of `party`. When a serving -role still lacks it, for example because the roles were absent when the -migrations ran, the hourly refresh logs a warning naming the tables it could -not analyze. Grant the role `MAINTAIN` on those tables, or run the same -`ANALYZE ONLY` from a scheduled job as the migration role. - -### Recovering a partially wiped database - -A wipe that removes *some* of the server's schemas is not a fresh start, and the -server cannot tell it from one. - -The server owns four schemas: `ext`, `clinical`, `party` and `audit`. -A fresh start drops all four. Each domain's cold archival tier is a **partition** -of the relation it archives, inside that domain's own schema, so a -`DROP SCHEMA clinical CASCADE` takes the archived rows with the live ones. There -is no separate mirror schema left to survive a wipe of the tier it mirrors. - -Dropping some of the schemas is not a supported reset, because they are not -independent. `ext` holds the helper functions the `clinical` and `party` -relations depend on, so `DROP SCHEMA ext CASCADE` drops them with it, and those -sets, still recorded as applied, never recreate them. The next boot rebuilds -the dropped schemas, and its -migration check reads each set's bookkeeping only, so it passes over a database -that has lost those guarantees. - -A database written by a release before the storage rewrite is refused outright: - -```text -this database predates the storage rewrite: schema `ehr` carries its own -migration bookkeeping, which only a release before the rewrite wrote. -``` - -The new migration sets replace the old ones rather than upgrading them, so there -is no in-place path. Dump anything worth keeping, recreate the database, and -start the server against it. - -> [!TIP] -> When you wipe a FerroEHR database deliberately, drop the **database**, not a -> schema. `DROP DATABASE` cannot leave half a repository behind, and it is the -> only wipe with no partial-state failure mode. `ferroehr db erase` drops all -> four schemas of a database in one transaction, for taking an instance out of -> service ([Decommissioning](operations-decommissioning.md)). - ## TLS and database security These are database-side settings that belong to whoever provisions PostgreSQL; @@ -400,347 +28,6 @@ the deployment references them but cannot enforce them: the stored clinical JSON with pgcrypto: it would break AQL's ability to query inside the data. -## Backup and point-in-time recovery - -Enable WAL archiving and point-in-time recovery from day one (pgBackRest or a -managed PITR), because a CDR's data is not reconstructible. Clinical and audit -tables are never `UNLOGGED`. Test your restore, not just your backup. - -### Dump each domain separately - -A logical backup is where the two pseudonymisation domains are easiest to -re-join by accident. One `pg_dump` of the whole database produces a single file -holding the pseudonymised clinical record beside the identities of its -subjects, and whoever can read that file can re-identify every record in it, -which is the separation the schema split and the database roles exist to -maintain. **Two domains, two dumps**, into targets with different access -control. - -**How many dumps, by DSN layout.** The number of dumps follows the domains, not -the databases: co-located, the three domains share one database and are dumped -`--schema` by `--schema` as below; relocated, each database is dumped for the -domains that live in it. What never changes is that the clinical record and the -identities land in two different artefacts with two different audiences. `ferroehr config check` prints the resolved layout, which is the -list a backup runbook is written from. The audit repository travels with the -clinical dump while it shares that database (`--schema=audit` below) and needs a -dump of its own once `[database.audit]` names another one. On Kubernetes that -third dump is not yours to schedule: the chart renders a `backup.audit` -CronJob as soon as `database.audit` carries a Secret of its own, and drops -`--schema=audit` from the clinical job in the same render. - -```bash -# The clinical domain -pg_dump --dbname="$CLINICAL_DSN" --format=custom --no-owner \ - --schema=clinical --schema=ext --schema=audit \ - --file=/backups/clinical/clinical-$(date -u +%Y%m%dT%H%M%SZ).dump - -# The identities, into a different directory, owned by a different group -pg_dump --dbname="$PARTY_DSN" --format=custom --no-owner \ - --schema=party \ - --file=/backups/party/party-$(date -u +%Y%m%dT%H%M%SZ).dump - -# The audit trail, ONLY when [database.audit] names a database of its own — -# co-located it is in the clinical dump above, and dumping it twice is a second -# copy of who read what -pg_dump --dbname="$AUDIT_DSN" --format=custom --no-owner \ - --schema=audit \ - --file=/backups/audit/audit-$(date -u +%Y%m%dT%H%M%SZ).dump -``` - -Which EHR belongs to which subject is the EHR's own `EHR_STATUS.subject`, so -it travels in the clinical dump. - -The clinical and party examples ship. In Compose they are the opt-in `backup` -profile: - -```bash -docker compose --profile backup run --rm ferroehr-backup-clinical -docker compose --profile backup run --rm ferroehr-backup-party -``` - -Set `FERROEHR_BACKUP_CLINICAL_DIR` and `FERROEHR_BACKUP_PARTY_DIR` to the two -targets; they default to `./backups/clinical` and `./backups/party`. -Run it as yourself — `FERROEHR_BACKUP_USER="$(id -u):$(id -g)"` — and the dump -lands owned by you. Left unset, the job runs as root inside the container and -keeps one capability, `DAC_OVERRIDE`, because that is what writing a directory -it does not own actually requires: the container drops every other capability, -and without this one uid 0 is just another user against your directory's -permission bits. Everything else stays off — no privilege escalation, read-only -root filesystem. -Under Kubernetes the chart renders one `CronJob` per domain — see the chart's -`backup` values. - -> [!WARNING] -> **A backup credential is not the application role.** Each domain's runtime -> role is revoked from the other domains, which is the pseudonymisation -> boundary doing its job — so a dump taken through one of them is silently -> partial rather than refused. Give each backup job its own role, read-only on -> its own domain and nothing else. - -Two further properties are yours to arrange, because no configuration file can -enforce them: the two targets carry **different** access control, and the -credential each job uses reaches **one** domain. Give the demographic job the demographic -DSN once you run two ([Deploying](installation/kubernetes.md)); with a single -credential you have separated the artefacts but not the authority to produce -them. - -> [!NOTE] -> Point-in-time recovery stays instance-wide. All the domains live in one -> cluster, so a WAL archive covers them together and a recovery target restores -> them together. The separation this section is about is the logical dump. - -### Restoring - -A restore is not finished when `pg_restore` exits. The grants are the -boundary — a database whose roles came back wrong is a database where the -clinical role can read the identities — so re-apply the role grants before the -server starts, then let the server check them: - -```bash -createdb ferroehr_restored -pg_restore --dbname=ferroehr_restored --no-owner clinical-….dump -pg_restore --dbname=ferroehr_restored --no-owner demographic-….dump -# then, before anything serves traffic: -ferroehr db verify -``` - -Restore the clinical dump first. It is the one carrying the `ext` schema, whose -helper functions the other domains' relations depend on. - -`ferroehr db verify` issues no DDL. It checks that the database carries exactly -this build's migrations, **all four sets**, so a restore that skipped a domain -is refused by name, and that no runtime role can read across the domain -boundary, exiting non-zero when either is untrue. It is the same check the -server runs at boot, which is why a server pointed at a badly restored database -refuses to start rather than serving from it. - -What it does **not** read is a constraint. `pg_restore` ignores a failed -statement unless you pass `--exit-on-error`, so a table can come back with its -rows and without a key while every check above stays green. Read the restore's -own output. - -Restoring only one domain is a supported outcome, not a mistake: a demographic -dump restored on its own gives a database with identities and no clinical -record, which is what a rehearsal of the identity domain's recovery looks like. -Such a database is not one the server will serve from — `ferroehr db verify` -refuses it for the domains that are missing, which is the correct answer for a -rehearsal target. - -## Storage sizing - -The database grows with two things: the composition versions you commit and -the requests the access log records. Size a deployment from the figures below, -then check it against your own data with the query at the end of this section. -No openEHR specification governs storage layout or sizing: these are -measurements of our own design. - -### What the figures were measured on - -FerroEHR 5.6.0-rc5 from the quickstart (`docker-compose.yml` with -`FERROEHR_EHR_INDEX=local` and the usage report off), PostgreSQL 18.6 with -`shared_buffers=1GB`, `max_wal_size=4GB`, `wal_compression=lz4` and default -autovacuum, in a Podman VM with 8 CPUs and 16 gibibytes of memory. A client with 8 workers ran -each workload over ITS-REST in five phases, and the size of every relation -(`pg_relation_size`, the TOAST relation's `pg_total_relation_size` and -`pg_indexes_size`) and the WAL position (`pg_current_wal_lsn()`) were read -after each phase: - -1. create 1 000 EHRs; -2. commit 20 000 compositions, 20 per EHR; -3. update 5 000 of them (`PUT` with `If-Match`); -4. delete 2 000 versions; -5. read 40 000 compositions. - -The compositions are the vendored CKM examples for the vital signs template -(10 769 bytes of canonical JSON without whitespace, 43 RM nodes) and, in a -smaller run of 200 EHRs and 2 000 compositions, the International Patient -Summary (87 133 bytes, 395 RM nodes). The vital signs workload ran twice: once -on fresh volumes and once appending to the same database. The two runs grew -the database by 608.0 MiB and 607.8 MiB, so the growth is linear in the work -and does not depend on how much the database already holds. - -The node rows, the clinical totals and the WAL below were measured again after -a node row below the root started to keep its archetype header, language and -encoding in columns: the same driver, PostgreSQL image and settings, against a -server built from the source, with 500 EHRs and 5 000 vital signs -compositions and 100 EHRs and 500 International Patient Summaries. That change -took a vital signs version from 21.6 KB to 17.1 KB and an International -Patient Summary from 159 KB to 131 KB. They were measured once more, with -the same driver and settings (300 EHRs, 3 000 vital signs compositions, 750 -updates, 300 deletes and 6 000 reads; 100 EHRs and 500 International Patient -Summaries), after storage generation 5 let a node row store a plain -`DV_DATE_TIME` origin or time as its value string, leave out a bare -`PARTY_SELF` subject, and leave the root's uid and archetype header with the -version row: a vital signs version went from 17.1 KB to 15.5 KB and an -International Patient Summary from 131 KB to 128 KB. - -### Measuring your own figures - -`scripts/perf/storage-sizing.sh` in the repository runs the same phases -against a running FerroEHR and reports the bytes per create, update, delete -and read, per relation, and the node rows with their heap and index bytes per -row. Start the server on a fresh database, so the run is all the database -holds, then: - -```sh -scripts/perf/storage-sizing.sh run sizing-out -``` - -It reads the sizes through `psql` as the database superuser, by default in the -quickstart's `ferroehr-postgres` container (`SIZING_PSQL` names another -command), and writes `sizing-out/report.json`. -`SIZING_TEMPLATE=international-patient-summary` measures the larger -composition, and `SIZING_EHRS`, `SIZING_PER_EHR`, `SIZING_UPDATES`, -`SIZING_DELETES` and `SIZING_READS` set the counts; the script's header lists -every setting. With the defaults (300 EHRs, 3 000 vital signs creates, 750 -updates, 300 deletes and 6 000 reads) it reproduces the figures below within -a few percent. Its WAL figures include the full-page images each phase's -`CHECKPOINT` forces, so they are higher than a steady state. - -### Bytes per composition version - -| Per committed version | Vital signs (10.8 KB of JSON) | International Patient Summary (87 KB of JSON) | -|---|---|---| -| Node rows | 43 rows of 201 B heap and 83 B of index, 12.2 KB | 395 rows of 199 B heap and 92 B of index, 115 KB | -| `version` row, with the body compressed (lz4) | 2.5 KB, in the row | 10.9 KB, in TOAST | -| `commit_audit`, `contribution` and `vo_head` | 0.7 KB | 0.7 KB | -| **Clinical storage per create or update** | **14.6 to 15.5 KB (1.4 × the JSON)** | **128 to 138 KB (1.5 to 1.6 × the JSON)** | -| A delete (a version with no body and no nodes) | 1.4 KB | 2.5 KB | -| WAL written per create | 30 KB | 242 KB | - -The node rows hold about 80 % of the clinical bytes, so the size of a version -follows the number of RM nodes in the composition more closely than the -length of its JSON. An update writes a complete version again (its body and -all its node rows), so it costs the same as a create. A new EHR takes about -8 KB, its `EHR_STATUS` version and the audit record included. - -### Bytes per audit record - -With `[audit.store]` on (the default) every audited request writes one record, -reads included. A record of a composition read takes about 1.0 KB in -`audit.audit_event` (heap and indexes, no TOAST), and a record of a -composition create about 1.05 KB. The request id and the version uid are -searched through the record's own columns, so a record adds no row to -`audit.audit_search_token` beyond the first record about a patient or a -resource kind. For a read-heavy workload the access log can outgrow the -clinical data: 40 000 composition reads add about 38 MiB, as much as about -1 800 new vital signs versions. - -### A sizing estimate - -Add up, for the period you size for: - -- the composition versions you expect, times the bytes per version of your - own templates (15 KB for one like vital signs, 0.3 to 0.4 KB per RM node - as a first estimate); -- the audited requests, times about 1.0 KB, for as long as the - [audit retention](audit.md#retention-and-who-chooses-it) keeps them; -- `pg_wal`, up to `max_wal_size` (below); -- your backups and WAL archive, which this database does not hold. - -One million vital-signs-sized versions take about 15 GB, and ten million -audited requests about 10 GB. - -### Audit retention - -An access policy with no `log_retention`, the default, keeps every audit -record forever, so the access log grows with every request for the life of -the database. A period (`ACCESS_POLICY.log_retention.period`, in years or -days) makes the reaper delete each record on or after its end date, hourly, -and the `audit_event` table then levels off at roughly the period times the -request rate. The space of a deleted row is not returned to the operating system: -`VACUUM` marks it free and later records reuse it (PostgreSQL 18 docs, -[Routine Vacuuming, Recovering Disk Space][pg-vacuum]). -The reaper also deletes the search tokens no remaining record names. The -period is the controller's legal choice, within the floors and ceilings it -declares, set out on the audit page. -The openEHR access log levels off too: each entry is kept for its own period, -its tombstone as long again, and then a run of tombstones folds into one gap -row ([steady-state size](audit.md#the-access-log-at-steady-state)). - -### `pg_wal` - -PostgreSQL keeps the write-ahead log of the last checkpoints in `pg_wal`, up -to about `max_wal_size` (4 GB in the quickstart), on the same volume as the -data unless you move it. `max_wal_size` is a soft limit: a failing -`archive_command`, `wal_keep_size` or a replication slot whose standby falls -behind holds more (PostgreSQL 18 docs, -[WAL Configuration](https://www.postgresql.org/docs/18/wal-configuration.html)). -Budget it as a fixed amount beside the database, not as growth. A commit -writes about twice its stored size to the WAL (30 KB for a 15.5 KB vital signs -version), which is what a WAL archive for point-in-time recovery receives. - -Set `wal_compression = lz4`. The first change to a page after a checkpoint -writes the whole page to the WAL, and lz4 compresses those images at a CPU -cost far below the flush it saves: a composition commit wrote about 52 KB of -WAL without it and about 24 KB with it. Since PostgreSQL 19, `on` picks -the first of zstd, lz4 and pglz the server was built with, where it always -meant pglz before (PostgreSQL 19 docs, -[WAL Configuration](https://www.postgresql.org/docs/19/runtime-config-wal.html#GUC-WAL-COMPRESSION)); -naming `lz4` keeps the measured method. The quickstart and the capacity -harness both run with it. - -### Vacuum and fillfactor - -The clinical write path is insert-only: a composition update or delete adds a -version and never updates or deletes an existing `version` or node row. After -the measured runs `pgstattuple_approx` found no dead tuples in -`clinical.node_hot`, `clinical.version_hot` or `audit.audit_event`, and under -1 % free space in `node_hot`. Changing autovacuum or fillfactor settings does -not change the volume. Autovacuum still has to run, for the planner -statistics and to freeze old rows before transaction ID wraparound. - -### Index maintenance - -The node table's primary key, `clinical.node_hot_pkey`, takes inserts from -concurrent commits at many places in the index, so its pages split and stay -partly empty. After the measured runs its leaves were 72 % full, and a rebuild -took it from 186 MiB to 149 MiB (20 % smaller) with 90 % full leaves. Rebuild -it after heavy write periods, without blocking reads or writes: - -```sql --- leaf density before; pgstattuple ships with PostgreSQL -CREATE EXTENSION IF NOT EXISTS pgstattuple; -SELECT avg_leaf_density FROM pgstatindex('clinical.node_hot_pkey'); - -REINDEX INDEX CONCURRENTLY clinical.node_hot_pkey; -``` - -Run it as the database owner or a role holding `MAINTAIN` on -`clinical.node_hot`. `REINDEX CONCURRENTLY` needs room for a second copy of -the index while it runs, and it waits for every transaction older than -itself to finish, so one long-running query or an idle open transaction holds -it up (PostgreSQL 18 docs, -[REINDEX, Rebuilding Indexes Concurrently][pg-reindex]). -The audit indexes on `recorded_at` are ascending and fill their pages without -a rebuild. - -### Reading the size per relation - -```sql -SELECT n.nspname || '.' || c.relname AS relation, - pg_size_pretty(pg_relation_size(c.oid)) AS heap, - pg_size_pretty(COALESCE(pg_total_relation_size(NULLIF(c.reltoastrelid, 0)), 0)) AS toast, - pg_size_pretty(pg_indexes_size(c.oid)) AS indexes, - pg_size_pretty(pg_total_relation_size(c.oid)) AS total -FROM pg_class c -JOIN pg_namespace n ON n.oid = c.relnamespace -WHERE c.relkind = 'r' - AND n.nspname IN ('clinical', 'party', 'audit', 'ext') -ORDER BY pg_total_relation_size(c.oid) DESC -LIMIT 15; -``` - -Divide the growth of `clinical.node_hot` and `clinical.version_hot` between -two readings by the versions committed in between -(`SELECT count(*) FROM clinical.version_hot`) to get your own bytes per -version. The functions are described in PostgreSQL 18 docs, -[Database Object Management Functions][pg-dbobj]. - -[pg-vacuum]: https://www.postgresql.org/docs/18/routine-vacuuming.html#VACUUM-FOR-SPACE-RECOVERY -[pg-reindex]: https://www.postgresql.org/docs/18/sql-reindex.html#SQL-REINDEX-CONCURRENTLY -[pg-dbobj]: https://www.postgresql.org/docs/18/functions-admin.html#FUNCTIONS-ADMIN-DBOBJECT - ## The container image and pod hardening The published image is distroless and non-root (shell-less, with no package @@ -820,145 +107,6 @@ verify the published attestations before rollout; the verification command is in None of these four is something this project can assert on your behalf, which is why they are written as your checklist rather than as our claim. -## Upgrades - -- **Upgrade in place within v6; the migrations are append-only.** A released - migration is never edited again, so a database created by an earlier v6 - release takes the new release's migrations on top of the ones it already - carries. The server - records the checksum of every applied migration and refuses to start against - a database whose recorded checksums differ from the files it carries - (`migration 1 was previously applied but has been modified`), which is why - editing one would lock every existing installation out of its own database - rather than revise its history. A correction ships as a new migration, and a - CI guard fails any pull request that modifies, renames or deletes one the - base branch already has. A rolling upgrade must still stay compatible with - the _previous_ schema for the window in which both versions run: additive - changes first, destructive changes a release later. - - Releases up to and including 4.0.18 predate this policy and did edit - migration files in place. A database created by one of those and never - upgraded since is recreated rather than migrated. A v5 database is not - upgraded in place either: see [Upgrading from v5 to v6](#upgrading-from-v5-to-v6). -- **Sweep for stale decomposition after a release that changes how content is - decomposed.** The version body is unaffected and every read serves it - correctly; what is stale is the decomposed index over it, which a - row-level query predicate depends on. `POST /ferroehr/rest/extensions/v1/admin/integrity/verify` - reports each such version as `stale_decomposition` and - `POST /ferroehr/rest/extensions/v1/admin/integrity/rebuild-nodes`, run once unscoped, rewrites the - rows from the stored document. The changelog names the affected object type - at each release that needs it; 4.2.0 is one, for demographic parties. Both - routes are on - [Admin & messaging APIs](operations-admin-apis.md#storage-integrity). -- **Upgrading a 5.5.0 that sets `[server.tls] client_ca_file`: set - `client_auth = "required"` beside it.** Before 5.5.0 the CA alone meant a - required client certificate; 5.5.0 read it under the new `client_auth` - default `none` and asked for no certificate, and from 5.6.0 such a table is - refused at load (GHSA-52mf-qg39-4q4j). See - [`[server.tls]`](installation/config-server.md#servertls-native-tls-and-mutual-tls-client-authentication). -- **Bound the DDL yourself.** Every pooled connection carries the - `[database] statement_timeout` value (60 seconds by default), and the migration - step runs on that pool, so a runaway statement is cut off, but there is **no - `lock_timeout`**, so a migration that waits behind a long transaction waits - as long as that transaction lasts. On a busy table use - `CREATE INDEX CONCURRENTLY`, add constraints `NOT VALID` and `VALIDATE` - later, and set `lock_timeout` in the migration session (or on the migrator - role) if you need the wait bounded. -- **Pin the image.** Deploy an immutable tag or, better, a `@sha256` digest, - never `latest`; roll back by re-pinning the prior digest, since the schema's - backward compatibility makes that safe. -- **Stay available.** Keep at least two replicas (or autoscaling) and a pod - disruption budget so node drains and upgrades never fully interrupt the - API. The default 30-second termination grace period covers the server's - shutdown; the audit records are stored before each response, so a - replica that stops leaves nothing in memory. - -### Upgrading from v5 to v6 - -**v6 needs a new, empty database.** v6.0.0 replaces the whole migration -history of every schema (`ext`, `clinical`, `party`, `audit`) with one -baseline that creates each object once, in its final shape. A database -prepared by v5 carries the v5 migration bookkeeping, and a v6 server refuses -to start against it, naming the schema it found and this way forward, rather -than apply its baseline over the old schema. Nothing is upgraded in place, and -no compatibility layer reads a v5 database. - -Move the records instead: - -1. With the v5 server still running, dump the repository with - [`POST {ext}/admin/dump`](operations-admin-apis.md) to a location both - servers can reach. -2. Create a new, empty PostgreSQL 19 database (or one per relocated domain, - as the v5 deployment had), and start the v6 server against it. With - `[database] migrations = "apply"` it applies the baseline at its first - boot; with `"verify"`, run `ferroehr db migrate` under the migrator - credential first. -3. Load the archive into the v6 server with - [`POST {ext}/admin/load`](operations-admin-apis.md). -4. Put the controller's access policy in place before you load an archive - that holds open care relationships - ([operational policy](operational-policy.md)), and check the configuration - with `ferroehr config check`, since v6 refuses the keys v5 removed. - -The audit trail is not part of the archive. Export what you need of the v5 -audit trail over ITI-81 before you retire the v5 database. - -The v6 baseline creates no `linkage` schema and no `ferroehr_linkage` role: a -cluster that held v5 databases may still carry that role, which v6 never names, -and you drop it with `DROP ROLE ferroehr_linkage` once no v5 database in the -cluster grants it anything. - -### How long the version you pinned is supported - -Plan the upgrade cadence around this: - -- **Only the newest release is supported.** When a new release is - published, every earlier release stops receiving fixes: there are no - maintenance branches, no long-term-support line and no backports. If you are - not on the newest release, upgrade; upgrading is free. Under the Cyber - Resilience Act, Cadasto B.V. commits to keep publishing security fixes for at - least five years after each release (Art 13(8)) and ships them only in the - newest release (Art 13(10)), which every user of an earlier release may run - under the same licence terms. Staying on an older release means running - without the fix. -- **A fix normally arrives as the next patch** on the current minor, so taking - it does not oblige you to take new behaviour, but that is the usual case, - not a promise. Where a fix is only correct alongside a behavioural change, - the release carrying it carries the change, and the changelog entry says so. -- **A published release is never repaired in place.** Release immutability - means the assets and the tag of a published release cannot be modified at - all, so the remedy for any defect is a new version. -- **The Helm chart and the published crates follow their own version lines**, - each supported only in its newest published version, which is where its - fixes ship. A chart-only fix ships as a new chart version between server - releases. - -**The running server states the end month of the commitment.** Cadasto B.V. -keeps publishing fixed releases for at least five years after each release -(CRA Art 13(8)), and the server reads its release date from its changelog -heading at build time. The end month, the date until which fixed releases -keep coming, does not make the running release supported: a release is -supported only while it is the newest. The end month is on the boot banner (`Support` line), in the boot log, in -`ferroehr --version`, under `support` in `GET /management/info`, and under -`support` in `GET /management/status` as -`{release_date, support_ends, status}`, where `support_ends` is `YYYY-MM` and -`status` is `supported` (the commitment is still running), `ended` or -`unreleased`. Once the end month has passed, -`status` reads `ended` and the server logs a `warn` line at boot and once a day -(CRA Art 13(19)). A build of a version whose changelog heading carries no date -is not a release: it reports `unreleased` and no end month. - -The server does not contact anyone to look for newer releases. To hear about -them, subscribe to the release feed -(`https://github.com/FerroHEALTH/FerroEHR/releases.atom`) and poll the -published security advisories -(`GET https://api.github.com/repos/FerroHEALTH/FerroEHR/security-advisories`). - -The consequence for change control: budget for taking every release, or budget -for maintaining a fork. There is no third option, and the full policy (with -the reasoning and what to do if you need something stronger) is -[SECURITY.md](https://github.com/FerroHEALTH/FerroEHR/blob/main/SECURITY.md#supported-versions). - ## Observability `tracing` is the single instrumentation API. From it, three signal families @@ -1061,9 +209,9 @@ annotation-discovering Prometheus, and neither is needed if you push over OTLP instead. **To turn the export off**, drop `telemetry.otlp`; nothing is exported without it. -**The default dashboard.** The "FerroEHR — service overview" Grafana +**The default dashboard.** The "FerroEHR - service overview" Grafana dashboard (request rate/errors/latency, AQL rate and phase latency, -plan-cache hit ratio, database pool, Tokio runtime, audit throughput — every +plan-cache hit ratio, database pool, Tokio runtime, audit throughput: every query written against the served metric names) reaches Grafana three ways: - **Compose**: the observability overlay provisions it automatically; @@ -1072,7 +220,7 @@ query written against the served metric names) reaches Grafana three ways: ships it as a ConfigMap labelled `grafana_dashboard: "1"`, which the Grafana Helm chart's dashboard sidecar (kube-prometheus-stack includes it) discovers and imports. The sidecar watches its own release namespace by - default — install FerroEHR there, or widen the sidecar's + default: install FerroEHR there, or widen the sidecar's `searchNamespace`. `metrics.grafanaDashboard.folder` sets the `grafana_folder` annotation for sidecars with folder routing configured. - **Anywhere else**: import @@ -1311,13 +459,13 @@ holds and what it leaves out. ## Next -- [Admin & messaging APIs](operations-admin-apis.md) — the operator-facing +- [Admin & messaging APIs](operations-admin-apis.md): the operator-facing HTTP surfaces, route by route. -- [Usage report](usage-report.md) — what the daily report to FerroPULSE +- [Usage report](usage-report.md): what the daily report to FerroPULSE carries, and how to switch it off. -- [Configuration reference](installation/configuration.md) — every setting, +- [Configuration reference](installation/configuration.md): every setting, with the server, database and telemetry keys on [their own page](installation/config-server.md). - The API reference at `/ferroehr/rest/swagger-ui` on your own deployment, or on the hosted - sandbox — the document the server itself generates. + sandbox: the document the server itself generates. diff --git a/website/book/src/performance.md b/website/book/src/performance.md index 1ce60df80d..027dedc024 100644 --- a/website/book/src/performance.md +++ b/website/book/src/performance.md @@ -18,7 +18,7 @@ then, two measurements describe FerroEHR's performance: - **The capacity test** steps the request rate up until FerroEHR degrades and names what saturated first. [Capacity](capacity.md) gives the method and `scripts/perf/capacity.sh`; each run's result, with the hardware it ran on, - is on its tracker issue, the first being #5722. + is on its tracker issue. - **The performance gate** judges each change against its base and each release against the previous one on one host ([The access path at scale](#the-access-path-at-scale)). @@ -107,7 +107,7 @@ to disk before the server answers, so an acknowledged commit survives a crash. That flush (one `fsync` on the WAL device per commit) is a physical lower bound on single-client write latency, and no storage design takes a lone sequential client below it. On a laptop-class Docker setup the flush alone -dominates a single write's budget; on server NVMe it is typically an order of +dominates a single write's budget; on server NVMe it is usually an order of magnitude smaller. FerroEHR's optimization target is therefore everything *around* the flush: the database's own per-commit work (one folded commit statement, one merged placement read) stays far below the flush itself. That is also what @@ -115,7 +115,7 @@ makes concurrent throughput scale: PostgreSQL group-commits, amortizing one flush across every transaction that reaches it in the same window. The knob behind this boundary is PostgreSQL's -[`synchronous_commit`](https://www.postgresql.org/docs/18/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT). +[`synchronous_commit`](https://www.postgresql.org/docs/19/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT). Setting it `off` makes commits return before the WAL flush: single-client write latency drops to the statement work alone, and a server crash can lose the most recent acknowledged commits (up to three times `wal_writer_delay`, @@ -243,7 +243,7 @@ against the record committed for its schema generation and class: bytes per composition version or per node row that grew more than the size budget (5 % by default) fail the run. A generation and class with no committed record fails the run, with the error in the job summary, so the change that moves the schema -generation commits the new generation's records with it (#4291). The run +generation commits the new generation's records with it. The run summary lists every round with its machine factor, and each operation with its pages per call and its raw and adjusted change. @@ -252,7 +252,7 @@ class, publishes no number, and writes nothing back to the repository: the round records leave as a run artifact, and the committed baseline under `docs/benchmarks/storage//` moves only in a pull request that says which run measured it. `docs/benchmarks/storage/README.md` records the numbers -behind each bound (#4318). +behind each bound. {{#include ../generated/storage-bench.md}} diff --git a/website/book/src/policy-examples.md b/website/book/src/policy-examples.md new file mode 100644 index 0000000000..1504eb0129 --- /dev/null +++ b/website/book/src/policy-examples.md @@ -0,0 +1,787 @@ +# Worked policy examples + +These examples write the policy parties of [Operational policy](operational-policy.md) +for common callers, as the requests an administrator sends. + + + + +The examples use the base path `/ferroehr/rest/openehr/v1`, send +`Content-Type: application/json` and `Prefer: return=representation`, and +run as an administrator. The party ids are examples: use the ids your +server returns in the `Location` header and the body. + +The provider this instance acts for is an `ORGANISATION` named +`9d2f4a7e-3c1b-4e8a-9f60-2b7d5c8e1a40`, and the federation partner below is +the `ORGANISATION` `7c4e9a2b-1f6d-4b3e-9c8a-5d2e0f7b1a36`. The default set's +healthcare provider `ORGANISATION` (`openEHR-DEMOGRAPHIC-ORGANISATION.healthcare_provider.v1.0.0`, +on [Default demographic definitions](installation/default-demographic-definitions.md)) +records both, identified by their provider identifier. Neither is a policy +party, so any demographic writer may create them. + +## A system client + +A laboratory relay commits laboratory results into EHRs at one facility. +First its `AGENT`, `POST /demographic/agent`: + + +```json +{ + "_type": "AGENT", + "archetype_node_id": "openEHR-DEMOGRAPHIC-AGENT.system.v1", + "archetype_details": { + "_type": "ARCHETYPED", + "archetype_id": { "_type": "ARCHETYPE_ID", "value": "openEHR-DEMOGRAPHIC-AGENT.system.v1" }, + "template_id": { "_type": "TEMPLATE_ID", "value": "openEHR-DEMOGRAPHIC-AGENT.system.v1.0.0" }, + "rm_version": "1.1.0" + }, + "name": { "_type": "DV_TEXT", "value": "System agent" }, + "details": { + "_type": "ITEM_TREE", "archetype_node_id": "id2", "name": { "_type": "DV_TEXT", "value": "Identifiers" }, + "items": [{ + "_type": "ELEMENT", "archetype_node_id": "id3", + "name": { + "_type": "DV_CODED_TEXT", "value": "client_id", + "defining_code": { + "_type": "CODE_PHRASE", + "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, + "code_string": "client_id" + } + }, + "value": { + "_type": "DV_IDENTIFIER", + "issuer": "https://login.example.org/machines", + "id": "lab-relay", + "type": "client_id" + } + }] + }, + "identities": [{ + "_type": "PARTY_IDENTITY", "archetype_node_id": "id4", "name": { "_type": "DV_TEXT", "value": "Name" }, + "details": { + "_type": "ITEM_TREE", "archetype_node_id": "id5", "name": { "_type": "DV_TEXT", "value": "Items" }, + "items": [{ + "_type": "ELEMENT", "archetype_node_id": "id6", "name": { "_type": "DV_TEXT", "value": "Name" }, + "value": { "_type": "DV_TEXT", "value": "Laboratory relay" } + }] + } + }] +} +``` + +Its grant is a `ROLE` it performs, `POST /demographic/role`, with the +`AGENT` `5b8e2c91-7d4a-4f3e-8a1c-6e9f0b2d4c73` the first call returned as +`performer`. Its capability grants `commit_composition` with the origin +`relay`, the template it writes and the facility it writes at, each element +named by its `openehr_access` code. A system that also registers +device measurements holds a second capability with the origin `device` and +its `device_identifier_issuer`. + + +```json +{ + "_type": "ROLE", + "archetype_node_id": "openEHR-DEMOGRAPHIC-ROLE.system_client.v1", + "archetype_details": { + "_type": "ARCHETYPED", + "archetype_id": { "_type": "ARCHETYPE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.system_client.v1" }, + "template_id": { "_type": "TEMPLATE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.system_client.v1.0.0" }, + "rm_version": "1.1.0" + }, + "name": { "_type": "DV_TEXT", "value": "System client" }, + "identities": [{ + "_type": "PARTY_IDENTITY", "archetype_node_id": "id2", "name": { "_type": "DV_TEXT", "value": "Role name" }, + "details": { + "_type": "ITEM_TREE", "archetype_node_id": "id3", "name": { "_type": "DV_TEXT", "value": "Name" }, + "items": [{ + "_type": "ELEMENT", "archetype_node_id": "id4", "name": { "_type": "DV_TEXT", "value": "Full name" }, + "value": { "_type": "DV_TEXT", "value": "Laboratory relay writes" } + }] + } + }], + "performer": { + "_type": "PARTY_REF", "namespace": "demographic", "type": "AGENT", + "id": { "_type": "HIER_OBJECT_ID", "value": "5b8e2c91-7d4a-4f3e-8a1c-6e9f0b2d4c73" } + }, + "time_validity": { + "_type": "DV_INTERVAL", + "lower": { "_type": "DV_DATE", "value": "2026-12-01" }, + "lower_unbounded": false, "upper_unbounded": true, + "lower_included": true, "upper_included": false + }, + "capabilities": [{ + "_type": "CAPABILITY", "archetype_node_id": "id6", "name": { "_type": "DV_TEXT", "value": "Relay" }, + "credentials": { + "_type": "ITEM_TREE", "archetype_node_id": "id8", "name": { "_type": "DV_TEXT", "value": "Grant" }, + "items": [ + { + "_type": "ELEMENT", "archetype_node_id": "id90", "name": { "_type": "DV_TEXT", "value": "Operation" }, + "value": { "_type": "DV_CODED_TEXT", "value": "Commit composition", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "commit_composition" } } + }, + { + "_type": "ELEMENT", "archetype_node_id": "id18", + "name": { "_type": "DV_CODED_TEXT", "value": "Origin", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "origin" } }, + "value": { "_type": "DV_CODED_TEXT", "value": "Relay", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "relay" } } + }, + { + "_type": "ELEMENT", "archetype_node_id": "id9", + "name": { "_type": "DV_CODED_TEXT", "value": "Template written", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "template" } }, + "value": { "_type": "DV_TEXT", "value": "openEHR-EHR-COMPOSITION.report-result.v1" } + }, + { + "_type": "CLUSTER", "archetype_node_id": "id10", + "name": { "_type": "DV_CODED_TEXT", "value": "Facility", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "facility" } }, + "items": [ + { + "_type": "ELEMENT", "archetype_node_id": "id11", + "name": { "_type": "DV_CODED_TEXT", "value": "Issuer", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "issuer" } }, + "value": { "_type": "DV_TEXT", "value": "urn:oid:2.16.528.1.1007.3.3" } + }, + { + "_type": "ELEMENT", "archetype_node_id": "id12", + "name": { "_type": "DV_CODED_TEXT", "value": "Identifier", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "identifier" } }, + "value": { "_type": "DV_TEXT", "value": "01234567" } + } + ] + } + ] + } + }] +} +``` + +Then a new version of the `AGENT`, `PUT /demographic/agent/{uid}` with the +`If-Match` of its version, that names the `ROLE` it performs and the +provider it acts for. A relationship is stored in its source party, and the +`AGENT`'s id exists only once the first call returns, so the acts-for +relationship goes in this second version. + + +```json +{ + "_type": "AGENT", + "archetype_node_id": "openEHR-DEMOGRAPHIC-AGENT.system.v1", + "archetype_details": { + "_type": "ARCHETYPED", + "archetype_id": { "_type": "ARCHETYPE_ID", "value": "openEHR-DEMOGRAPHIC-AGENT.system.v1" }, + "template_id": { "_type": "TEMPLATE_ID", "value": "openEHR-DEMOGRAPHIC-AGENT.system.v1.0.0" }, + "rm_version": "1.1.0" + }, + "name": { "_type": "DV_TEXT", "value": "System agent" }, + "details": { + "_type": "ITEM_TREE", "archetype_node_id": "id2", "name": { "_type": "DV_TEXT", "value": "Identifiers" }, + "items": [{ + "_type": "ELEMENT", "archetype_node_id": "id3", + "name": { + "_type": "DV_CODED_TEXT", "value": "client_id", + "defining_code": { + "_type": "CODE_PHRASE", + "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, + "code_string": "client_id" + } + }, + "value": { + "_type": "DV_IDENTIFIER", + "issuer": "https://login.example.org/machines", + "id": "lab-relay", + "type": "client_id" + } + }] + }, + "identities": [{ + "_type": "PARTY_IDENTITY", "archetype_node_id": "id4", "name": { "_type": "DV_TEXT", "value": "Name" }, + "details": { + "_type": "ITEM_TREE", "archetype_node_id": "id5", "name": { "_type": "DV_TEXT", "value": "Items" }, + "items": [{ + "_type": "ELEMENT", "archetype_node_id": "id6", "name": { "_type": "DV_TEXT", "value": "Name" }, + "value": { "_type": "DV_TEXT", "value": "Laboratory relay" } + }] + } + }], + "roles": [{ + "_type": "PARTY_REF", "namespace": "demographic", "type": "ROLE", + "id": { "_type": "HIER_OBJECT_ID", "value": "e41c7b2a-6d3f-4a9e-8b05-2f7d1c9e3a68" } + }], + "relationships": [{ + "_type": "PARTY_RELATIONSHIP", + "archetype_node_id": "openEHR-DEMOGRAPHIC-PARTY_RELATIONSHIP.acts_for.v1", + "name": { + "_type": "DV_CODED_TEXT", "value": "Acts for", + "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "local" }, "code_string": "at10" } + }, + "details": { + "_type": "ITEM_TREE", "archetype_node_id": "id3", "name": { "_type": "DV_TEXT", "value": "Details" }, + "items": [{ + "_type": "ELEMENT", "archetype_node_id": "id6", "name": { "_type": "DV_TEXT", "value": "Acts-for code" }, + "value": { + "_type": "DV_CODED_TEXT", "value": "Acts for", + "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "acts_for" } + } + }] + }, + "source": { + "_type": "PARTY_REF", "namespace": "demographic", "type": "AGENT", + "id": { "_type": "HIER_OBJECT_ID", "value": "5b8e2c91-7d4a-4f3e-8a1c-6e9f0b2d4c73" } + }, + "target": { + "_type": "PARTY_REF", "namespace": "demographic", "type": "ORGANISATION", + "id": { "_type": "HIER_OBJECT_ID", "value": "9d2f4a7e-3c1b-4e8a-9f60-2b7d5c8e1a40" } + } + }] +} +``` + +## A backend client and a demographic client + +A reporting job queries every EHR with a `system/aql-*` scope, and a master +patient index reads and writes persons through the DEMOGRAPHIC API. Neither +is a key in `ferroehr.toml`: each is a grant of the client's `AGENT`, read on +every request. A `system/aql-*` scope "would grant access to all registered +and ad-hoc AQL queries system-wide" (SMART on openEHR, master08 §Resource +Scopes), so it counts only for a client granted `query_system_wide`; no +SMART on openEHR scope covers demographic data, so the DEMOGRAPHIC API admits +a client granted `access_demographic`, or a caller holding the +`[auth] product_scope`. + +Both operations reach beyond one system's own writes, so the ceiling admits +each by name: + +```toml +[authz.grants] +allowed = ["commit_composition", "query_system_wide", "access_demographic"] +``` + +The client's `AGENT` is written as above, and its grant is a `ROLE` it +performs, `POST /demographic/role`. One `ROLE` can carry both operations; a +deployment that runs the two as separate clients gives each its own `AGENT` +and `ROLE`. + + +```json +{ + "_type": "ROLE", + "archetype_node_id": "openEHR-DEMOGRAPHIC-ROLE.system_client.v1", + "archetype_details": { + "_type": "ARCHETYPED", + "archetype_id": { "_type": "ARCHETYPE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.system_client.v1" }, + "template_id": { "_type": "TEMPLATE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.system_client.v1.0.0" }, + "rm_version": "1.1.0" + }, + "name": { "_type": "DV_TEXT", "value": "System client" }, + "identities": [{ + "_type": "PARTY_IDENTITY", "archetype_node_id": "id2", "name": { "_type": "DV_TEXT", "value": "Role name" }, + "details": { + "_type": "ITEM_TREE", "archetype_node_id": "id3", "name": { "_type": "DV_TEXT", "value": "Name" }, + "items": [{ + "_type": "ELEMENT", "archetype_node_id": "id4", "name": { "_type": "DV_TEXT", "value": "Full name" }, + "value": { "_type": "DV_TEXT", "value": "Reporting and patient index" } + }] + } + }], + "performer": { + "_type": "PARTY_REF", "namespace": "demographic", "type": "AGENT", + "id": { "_type": "HIER_OBJECT_ID", "value": "5b8e2c91-7d4a-4f3e-8a1c-6e9f0b2d4c73" } + }, + "capabilities": [{ + "_type": "CAPABILITY", "archetype_node_id": "id6", "name": { "_type": "DV_TEXT", "value": "Reporting" }, + "credentials": { + "_type": "ITEM_TREE", "archetype_node_id": "id8", "name": { "_type": "DV_TEXT", "value": "Grant" }, + "items": [ + { + "_type": "ELEMENT", "archetype_node_id": "id90", "name": { "_type": "DV_TEXT", "value": "Operation" }, + "value": { + "_type": "DV_CODED_TEXT", "value": "Query system-wide", + "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "query_system_wide" } + } + }, + { + "_type": "ELEMENT", "archetype_node_id": "id90", "name": { "_type": "DV_TEXT", "value": "Operation" }, + "value": { + "_type": "DV_CODED_TEXT", "value": "Access demographic", + "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "access_demographic" } + } + } + ] + } + }] +} +``` + +The client's next request runs under the grant, on every replica, with no +restart. The grant counts for the client's own client credentials token, +whose `client_id` the `AGENT` carries. A person signed in +through the same client holds the person's own grants, never the client's. +To withdraw it, end the `ROLE`'s `time_validity` or delete the `ROLE` +([Ending a grant](#ending-a-grant)). + +## A migration + +A migration is a system client like any other: its `AGENT` is written as +above, and its `ROLE` holds the import and export operations. Here a job +imports the EHRs of a legacy system and its extracts over one night, and may +export them again to check the result. The capability's `time_validity` +holds the migration to two days, `Not before` and `Not after` narrow it to +the night between them, and `subject_namespace` limits it to the legacy +system's patients. `[authz.grants] allowed` must admit `import_ehr`, +`import_ehr_extract` and `export_ehr_extract`. + + +```json +{ + "_type": "ROLE", + "archetype_node_id": "openEHR-DEMOGRAPHIC-ROLE.system_client.v1", + "archetype_details": { + "_type": "ARCHETYPED", + "archetype_id": { "_type": "ARCHETYPE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.system_client.v1" }, + "template_id": { "_type": "TEMPLATE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.system_client.v1.0.0" }, + "rm_version": "1.1.0" + }, + "name": { "_type": "DV_TEXT", "value": "System client" }, + "identities": [{ + "_type": "PARTY_IDENTITY", "archetype_node_id": "id2", "name": { "_type": "DV_TEXT", "value": "Role name" }, + "details": { + "_type": "ITEM_TREE", "archetype_node_id": "id3", "name": { "_type": "DV_TEXT", "value": "Name" }, + "items": [{ + "_type": "ELEMENT", "archetype_node_id": "id4", "name": { "_type": "DV_TEXT", "value": "Full name" }, + "value": { "_type": "DV_TEXT", "value": "Legacy HIS migration" } + }] + } + }], + "performer": { + "_type": "PARTY_REF", "namespace": "demographic", "type": "AGENT", + "id": { "_type": "HIER_OBJECT_ID", "value": "5b8e2c91-7d4a-4f3e-8a1c-6e9f0b2d4c73" } + }, + "capabilities": [{ + "_type": "CAPABILITY", "archetype_node_id": "id6", "name": { "_type": "DV_TEXT", "value": "Migration" }, + "time_validity": { + "_type": "DV_INTERVAL", + "lower": { "_type": "DV_DATE", "value": "2026-12-05" }, + "upper": { "_type": "DV_DATE", "value": "2026-12-06" }, + "lower_unbounded": false, "upper_unbounded": false, + "lower_included": true, "upper_included": true + }, + "credentials": { + "_type": "ITEM_TREE", "archetype_node_id": "id8", "name": { "_type": "DV_TEXT", "value": "Grant" }, + "items": [ + { + "_type": "ELEMENT", "archetype_node_id": "id90", "name": { "_type": "DV_TEXT", "value": "Operation" }, + "value": { "_type": "DV_CODED_TEXT", "value": "Import EHR", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "import_ehr" } } + }, + { + "_type": "ELEMENT", "archetype_node_id": "id90", "name": { "_type": "DV_TEXT", "value": "Operation" }, + "value": { "_type": "DV_CODED_TEXT", "value": "Import EHR extract", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "import_ehr_extract" } } + }, + { + "_type": "ELEMENT", "archetype_node_id": "id90", "name": { "_type": "DV_TEXT", "value": "Operation" }, + "value": { "_type": "DV_CODED_TEXT", "value": "Export EHR extract", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "export_ehr_extract" } } + }, + { + "_type": "ELEMENT", "archetype_node_id": "id19", + "name": { "_type": "DV_CODED_TEXT", "value": "Subject namespace", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "subject_namespace" } }, + "value": { "_type": "DV_TEXT", "value": "nl.legacy-his.patients" } + }, + { + "_type": "ELEMENT", "archetype_node_id": "id15", + "name": { "_type": "DV_CODED_TEXT", "value": "Not before", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "not_before" } }, + "value": { "_type": "DV_DATE_TIME", "value": "2026-12-05T22:00:00Z" } + }, + { + "_type": "ELEMENT", "archetype_node_id": "id16", + "name": { "_type": "DV_CODED_TEXT", "value": "Not after", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "not_after" } }, + "value": { "_type": "DV_DATE_TIME", "value": "2026-12-06T05:00:00Z" } + }, + { + "_type": "ELEMENT", "archetype_node_id": "id17", "name": { "_type": "DV_TEXT", "value": "Authorisation reference" }, + "value": { "_type": "DV_TEXT", "value": "CHG-2026-1182" } + } + ] + } + }] +} +``` + +The job then calls `POST /message/import` (`message_import_ehr`) and +`POST /message/import/{ehr_id}` (`message_import_ehr_extract`) with its own +token, and `POST /message/export` to read the result back. Each +import is committed under the job's `ACTOR` and is an access record that names +it and the provider it acts for. The versions of an extract keep their legacy +committers when a `creating_system` element of the grant names the legacy +system's `creating_system_id`; otherwise an extract naming a local party is +refused. +When the night ends the grant holds no longer, with no change to anything. + +## A federation partner + +A partner organisation's professionals read patient summaries under a +data-sharing agreement. The partner is an `ORGANISATION` that carries a +client identifier for each client its `federation` issuer issues tokens to: +an `ELEMENT` in its `details` named `openehr_access::client_id` whose value +is, for example, `{ "_type": "DV_IDENTIFIER", "issuer": +"https://federation.example", "id": "remote-portal" }`. Committing it is an +administrator's write, because the element makes it a policy party. The agreement is a `ROLE` of the +federation partner template the partner performs, with one capability per +accessor, here `person`. Each term is an element whose `name` is its +`openehr_access` code, which is how FerroEHR reads it in any archetype +(see [Federation agreements](operational-policy.md#federation-agreements)). + + +```json +{ + "_type": "ROLE", + "archetype_node_id": "openEHR-DEMOGRAPHIC-ROLE.federation_partner.v1", + "archetype_details": { + "_type": "ARCHETYPED", + "archetype_id": { "_type": "ARCHETYPE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.federation_partner.v1" }, + "template_id": { "_type": "TEMPLATE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.federation_partner.v1.0.0" }, + "rm_version": "1.1.0" + }, + "name": { "_type": "DV_TEXT", "value": "Federation partner" }, + "identities": [{ + "_type": "PARTY_IDENTITY", "archetype_node_id": "id2", "name": { "_type": "DV_TEXT", "value": "Role name" }, + "details": { + "_type": "ITEM_TREE", "archetype_node_id": "id3", "name": { "_type": "DV_TEXT", "value": "Name" }, + "items": [{ + "_type": "ELEMENT", "archetype_node_id": "id4", "name": { "_type": "DV_TEXT", "value": "Full name" }, + "value": { "_type": "DV_TEXT", "value": "Regional care network" } + }] + } + }], + "performer": { + "_type": "PARTY_REF", "namespace": "demographic", "type": "ORGANISATION", + "id": { "_type": "HIER_OBJECT_ID", "value": "7c4e9a2b-1f6d-4b3e-9c8a-5d2e0f7b1a36" } + }, + "time_validity": { + "_type": "DV_INTERVAL", + "lower": { "_type": "DV_DATE", "value": "2026-01-01" }, + "upper": { "_type": "DV_DATE", "value": "2036-12-31" }, + "lower_unbounded": false, "upper_unbounded": false, + "lower_included": true, "upper_included": true + }, + "capabilities": [{ + "_type": "CAPABILITY", "archetype_node_id": "id6", + "name": { + "_type": "DV_CODED_TEXT", "value": "Person", + "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "local" }, "code_string": "at10" } + }, + "credentials": { + "_type": "ITEM_TREE", "archetype_node_id": "id8", "name": { "_type": "DV_TEXT", "value": "Grant" }, + "items": [ + { + "_type": "ELEMENT", "archetype_node_id": "id90", "name": { "_type": "DV_TEXT", "value": "Operation" }, + "value": { "_type": "DV_CODED_TEXT", "value": "Federated person access", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "federated_person_access" } } + }, + { + "_type": "ELEMENT", "archetype_node_id": "id9", + "name": { "_type": "DV_CODED_TEXT", "value": "Agreement name", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "agreement_name" } }, + "value": { "_type": "DV_TEXT", "value": "Regional care network exchange" } + }, + { + "_type": "ELEMENT", "archetype_node_id": "id10", + "name": { "_type": "DV_CODED_TEXT", "value": "Agreement version", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "agreement_version" } }, + "value": { "_type": "DV_TEXT", "value": "2.1" } + }, + { + "_type": "ELEMENT", "archetype_node_id": "id12", + "name": { "_type": "DV_CODED_TEXT", "value": "Exchange", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "exchange" } }, + "value": { "_type": "DV_TEXT", "value": "patient summary" } + }, + { + "_type": "ELEMENT", "archetype_node_id": "id13", + "name": { "_type": "DV_CODED_TEXT", "value": "Purpose", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "purpose" } }, + "value": { "_type": "DV_CODED_TEXT", "value": "treatment", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "HL7_ActReason" }, "code_string": "TREAT" } } + }, + { + "_type": "CLUSTER", "archetype_node_id": "id14", "name": { "_type": "DV_TEXT", "value": "Legal ground" }, + "items": [ + { + "_type": "ELEMENT", "archetype_node_id": "id15", + "name": { "_type": "DV_CODED_TEXT", "value": "GDPR Article 6(1) point", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "gdpr_art_6_1" } }, + "value": { "_type": "DV_TEXT", "value": "e" } + }, + { + "_type": "ELEMENT", "archetype_node_id": "id16", + "name": { "_type": "DV_CODED_TEXT", "value": "GDPR Article 9(2) point", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "gdpr_art_9_2" } }, + "value": { "_type": "DV_TEXT", "value": "h" } + }, + { + "_type": "ELEMENT", "archetype_node_id": "id17", + "name": { "_type": "DV_CODED_TEXT", "value": "National provision", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "national_provision" } }, + "value": { "_type": "DV_TEXT", "value": "the provision the agreement names" } + } + ] + }, + { + "_type": "ELEMENT", "archetype_node_id": "id18", + "name": { "_type": "DV_CODED_TEXT", "value": "Consent source", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "consent" } }, + "value": { "_type": "DV_CODED_TEXT", "value": "Local", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "local" } } + }, + { + "_type": "ELEMENT", "archetype_node_id": "id19", + "name": { "_type": "DV_CODED_TEXT", "value": "Read scope", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "read_scope" } }, + "value": { "_type": "DV_TEXT", "value": "patient/composition-openEHR-EHR-COMPOSITION.patient_summary.v1.r" } + }, + { + "_type": "CLUSTER", "archetype_node_id": "id24", "name": { "_type": "DV_TEXT", "value": "Caller rate" }, + "items": [ + { + "_type": "ELEMENT", "archetype_node_id": "id25", + "name": { "_type": "DV_CODED_TEXT", "value": "Requests per second", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "requests_per_second" } }, + "value": { "_type": "DV_COUNT", "magnitude": 5 } + }, + { + "_type": "ELEMENT", "archetype_node_id": "id26", + "name": { "_type": "DV_CODED_TEXT", "value": "Burst", "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "burst" } }, + "value": { "_type": "DV_COUNT", "magnitude": 20 } + } + ] + } + ] + } + }] +} +``` + +## A privileged role + +A professional covers a colleague's access-log reviews for one week. The +grant is a `ROLE` of the privileged template performed by the professional's +`PERSON` `3e7a1d5c-9b2f-4c8e-a6d0-1f4b8e2c7a95`, with one capability per +privilege, here `subject audit`. The privileged role never grants the +administrator role or emergency access: the identity provider and the +configuration grant those. + + +```json +{ + "_type": "ROLE", + "archetype_node_id": "openEHR-DEMOGRAPHIC-ROLE.privileged.v1", + "archetype_details": { + "_type": "ARCHETYPED", + "archetype_id": { "_type": "ARCHETYPE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.privileged.v1" }, + "template_id": { "_type": "TEMPLATE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.privileged.v1.0.0" }, + "rm_version": "1.1.0" + }, + "name": { "_type": "DV_TEXT", "value": "Privileged role" }, + "identities": [{ + "_type": "PARTY_IDENTITY", "archetype_node_id": "id2", "name": { "_type": "DV_TEXT", "value": "Role name" }, + "details": { + "_type": "ITEM_TREE", "archetype_node_id": "id3", "name": { "_type": "DV_TEXT", "value": "Name" }, + "items": [{ + "_type": "ELEMENT", "archetype_node_id": "id4", "name": { "_type": "DV_TEXT", "value": "Full name" }, + "value": { "_type": "DV_TEXT", "value": "Access log review cover" } + }] + } + }], + "performer": { + "_type": "PARTY_REF", "namespace": "demographic", "type": "PERSON", + "id": { "_type": "HIER_OBJECT_ID", "value": "3e7a1d5c-9b2f-4c8e-a6d0-1f4b8e2c7a95" } + }, + "capabilities": [{ + "_type": "CAPABILITY", "archetype_node_id": "id6", + "name": { + "_type": "DV_CODED_TEXT", "value": "Subject audit", + "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "local" }, "code_string": "at10" } + }, + "time_validity": { + "_type": "DV_INTERVAL", + "lower": { "_type": "DV_DATE", "value": "2026-12-07" }, + "upper": { "_type": "DV_DATE", "value": "2026-12-13" }, + "lower_unbounded": false, "upper_unbounded": false, + "lower_included": true, "upper_included": true + }, + "credentials": { + "_type": "ITEM_TREE", "archetype_node_id": "id8", "name": { "_type": "DV_TEXT", "value": "Grant" }, + "items": [ + { + "_type": "ELEMENT", "archetype_node_id": "id90", "name": { "_type": "DV_TEXT", "value": "Operation" }, + "value": { + "_type": "DV_CODED_TEXT", "value": "Read subject audit", + "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "read_subject_audit" } + } + }, + { + "_type": "ELEMENT", "archetype_node_id": "id11", "name": { "_type": "DV_TEXT", "value": "Authorisation reference" }, + "value": { "_type": "DV_TEXT", "value": "Cover for the privacy officer, approved by the CMIO" } + }] + } + }] +} +``` + +## A scribe composing for physicians + +A scribe records the notes the physicians of the same provider dictate. The +grant is a `ROLE` of the privileged template, version `1.0.1`, whose kind +`at14` is `Compose for`, performed by the scribe's `PERSON` +`3e7a1d5c-9b2f-4c8e-a6d0-1f4b8e2c7a95`. Each `COMPOSITION` the scribe +commits names the physician as its composer, and the committer is the scribe. + + +```json +{ + "_type": "ROLE", + "archetype_node_id": "openEHR-DEMOGRAPHIC-ROLE.privileged.v1", + "archetype_details": { + "_type": "ARCHETYPED", + "archetype_id": { "_type": "ARCHETYPE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.privileged.v1" }, + "template_id": { "_type": "TEMPLATE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.privileged.v1.0.1" }, + "rm_version": "1.1.0" + }, + "name": { "_type": "DV_TEXT", "value": "Privileged role" }, + "identities": [{ + "_type": "PARTY_IDENTITY", "archetype_node_id": "id2", "name": { "_type": "DV_TEXT", "value": "Role name" }, + "details": { + "_type": "ITEM_TREE", "archetype_node_id": "id3", "name": { "_type": "DV_TEXT", "value": "Name" }, + "items": [{ + "_type": "ELEMENT", "archetype_node_id": "id4", "name": { "_type": "DV_TEXT", "value": "Full name" }, + "value": { "_type": "DV_TEXT", "value": "Medical scribe" } + }] + } + }], + "performer": { + "_type": "PARTY_REF", "namespace": "demographic", "type": "PERSON", + "id": { "_type": "HIER_OBJECT_ID", "value": "3e7a1d5c-9b2f-4c8e-a6d0-1f4b8e2c7a95" } + }, + "capabilities": [{ + "_type": "CAPABILITY", "archetype_node_id": "id6", + "name": { + "_type": "DV_CODED_TEXT", "value": "Compose for", + "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "local" }, "code_string": "at14" } + }, + "credentials": { + "_type": "ITEM_TREE", "archetype_node_id": "id8", "name": { "_type": "DV_TEXT", "value": "Grant" }, + "items": [{ + "_type": "ELEMENT", "archetype_node_id": "id90", "name": { "_type": "DV_TEXT", "value": "Operation" }, + "value": { + "_type": "DV_CODED_TEXT", "value": "Compose for", + "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "compose_for" } + } + }] + } + }] +} +``` + +Allow the operation by name: `[authz.grants] allowed = ["commit_composition", "compose_for"]`. + +## Just-in-time admission + +A first login of a person no party carries creates a provisional `PERSON` +only when a `create_at_login` grant admits it. The grant is a `ROLE` like +any other, and FerroEHR reads it on every first login, whoever performs the +`ROLE`: here the provider `ORGANISATION` performs it, which reads as "the +hospital admits its own staff". Its capability names the issuer by +`login_issuer` and declares the admission conditions: + +- `admit_idp`: the identity providers whose logins are created, read from + the issuer's `[[authz.party_binding.issuer]] idp_claim` (`idp` by + default); +- `admit_group`: the groups, read from the `group_claim` of the issuer's + party table, one of which an admitted login holds; +- `admit_role`: the roles, read from `[auth] role_claims`, one of which an + admitted login holds; +- `admit_assurance`: the lowest `[authz.assurance]` level an admitted login + carries. + +A login is admitted when it meets every condition the grant declares; each +list admits any one of its values. Several grants in force admit a login +when any one of them does. A grant names at least one `login_issuer` and +at least one of `admit_idp`, `admit_group`, `admit_role` and +`admit_assurance`, so no grant admits every login of an issuer: a grant +without a condition is refused with `422`, as is an element whose value +does not read. `[authz.grants] allowed` must list `create_at_login`, which +the default does not. + +The provider admits the logins of its Microsoft Entra tenant from members of +one group at assurance substantial or above, from 1 December 2026, +`POST /demographic/role`: + + +```json +{ + "_type": "ROLE", + "archetype_node_id": "openEHR-DEMOGRAPHIC-ROLE.login_admission.v1", + "archetype_details": { + "_type": "ARCHETYPED", + "archetype_id": { "_type": "ARCHETYPE_ID", "value": "openEHR-DEMOGRAPHIC-ROLE.login_admission.v1" }, + "rm_version": "1.1.0" + }, + "name": { "_type": "DV_TEXT", "value": "Login admission" }, + "identities": [{ + "_type": "PARTY_IDENTITY", "archetype_node_id": "at0001", "name": { "_type": "DV_TEXT", "value": "Role name" }, + "details": { + "_type": "ITEM_TREE", "archetype_node_id": "at0002", "name": { "_type": "DV_TEXT", "value": "Name" }, + "items": [{ + "_type": "ELEMENT", "archetype_node_id": "at0003", "name": { "_type": "DV_TEXT", "value": "Full name" }, + "value": { "_type": "DV_TEXT", "value": "Staff first login" } + }] + } + }], + "performer": { + "_type": "PARTY_REF", "namespace": "demographic", "type": "ORGANISATION", + "id": { "_type": "HIER_OBJECT_ID", "value": "9d2f4a7e-3c1b-4e8a-9f60-2b7d5c8e1a40" } + }, + "time_validity": { + "_type": "DV_INTERVAL", + "lower": { "_type": "DV_DATE", "value": "2026-12-01" }, + "lower_unbounded": false, "upper_unbounded": true, + "lower_included": true, "upper_included": false + }, + "capabilities": [{ + "_type": "CAPABILITY", "archetype_node_id": "at0010", "name": { "_type": "DV_TEXT", "value": "Admission" }, + "credentials": { + "_type": "ITEM_TREE", "archetype_node_id": "at0011", "name": { "_type": "DV_TEXT", "value": "Terms" }, + "items": [ + { + "_type": "ELEMENT", "archetype_node_id": "at0012", "name": { "_type": "DV_TEXT", "value": "Operation" }, + "value": { + "_type": "DV_CODED_TEXT", "value": "Create at login", + "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "create_at_login" } + } + }, + { + "_type": "ELEMENT", "archetype_node_id": "at0013", + "name": { + "_type": "DV_CODED_TEXT", "value": "Login issuer", + "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "login_issuer" } + }, + "value": { "_type": "DV_URI", "value": "https://login.microsoftonline.com/0f1e2d3c-4b5a-4968-8776-655443322110/v2.0" } + }, + { + "_type": "ELEMENT", "archetype_node_id": "at0014", + "name": { + "_type": "DV_CODED_TEXT", "value": "Admitted group", + "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "admit_group" } + }, + "value": { "_type": "DV_TEXT", "value": "5f2a9c1e-0000-4000-8000-00000000c11a" } + }, + { + "_type": "ELEMENT", "archetype_node_id": "at0015", + "name": { + "_type": "DV_CODED_TEXT", "value": "Admitted assurance", + "defining_code": { "_type": "CODE_PHRASE", "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, "code_string": "admit_assurance" } + }, + "value": { "_type": "DV_TEXT", "value": "substantial" } + } + ] + } + }] +} +``` + +The `ROLE` is a policy party, so only an administrator writes or reads it. +The next first login of that tenant that meets both conditions creates its +`PERSON`, on every replica and with no restart. To stop creating, end the +`ROLE` as below; a `PERSON` already created stays. The configuration keeps +only how the issuer's tokens are read +([Just-in-time creation](installation/config-authz.md#just-in-time-creation)). + +## Ending a grant + +To end a grant, an administrator commits a new version of the `ROLE` whose +`time_validity` ends before today (an upper bound of yesterday, or of today +with `upper_included` false), with `PUT /demographic/role/{uid}` and the +`If-Match` of its current version, or deletes it with +`DELETE /demographic/role/{uid}`. Both are versions with their committer, so +the revision history keeps the grant and who ended it, and the change decides +the caller's next request. diff --git a/website/book/src/pseudonymisation.md b/website/book/src/pseudonymisation.md new file mode 100644 index 0000000000..65114e79fc --- /dev/null +++ b/website/book/src/pseudonymisation.md @@ -0,0 +1,157 @@ +# The pseudonymisation boundary + +Which database role reads which domain, and how a subject is linked across the boundary. + + + + +The pseudonymisation boundary separates *a record from the person it is +about*, and it is enforced by PostgreSQL grants rather than by the server's own +routing: code that reaches for the wrong schema is a bug that can +be fixed, while a database role able to read two domains defeats the +separation however correct the code is. + +GDPR [Art. 4(5)](https://eur-lex.europa.eu/eli/reg/2016/679/oj) defines +pseudonymisation as processing where attributing data to a person requires +additional information "kept separately and subject to technical and +organisational measures", and Art. 32(1)(a) names it a security measure for +health data. EDPB Guidelines 01/2025 require that separation to hold against +internal actors, operators with database access included. + +Two domains hold the two parts, each behind its own role: + +```mermaid +flowchart LR + server["FerroEHR server"] + server -->|ferroehr_clinical| ehr[("clinical
versions and nodes,
keyed by an opaque subject pseudonym")] + server -->|ferroehr_party| demo[("party
parties, with no
national identifier")] + server -->|audit writer| audit[("audit
ATNA record repository")] + ehr -. barred .- demo +``` + +Read one domain and you hold a clinical record whose subject is an opaque +identifier, or a set of people with no records attached. Only the two together +re-identify anything, and no credential the server uses holds both. The +migrations create the roles, grant each its own schema, and **revoke every +other domain explicitly, in both directions**; each role is `NOINHERIT` and a +member of no other, so a grant cannot arrive through a membership. + +The boundary is checked at startup, not assumed: the server reads the +catalogue for every table, view, sequence and function each role can reach in +a domain it does not own, and **refuses to serve** if it finds one, naming the +role and the object. A misconfigured grant is a failed boot, not a silent +weakening. + +Two limits are worth stating plainly. The clinical schema holds a *pseudonym* +only when `[privacy] subject_namespaces` declares the namespaces a subject +reference may draw from; left unset, whatever a client sends is what gets +stored, and no schema split saves you from a national identifier written into +the clinical side; see +[Privacy and identifiers](installation/config-privacy.md). And the split is a +schema split by default: giving the demographic domain its own +`[database.party] url` is what turns it into a credential split, which is the +deployment step described in +[Operations](database-operations.md#database-roles-and-least-privilege). + +## Encryption at rest is a deployment requirement + +FerroEHR encrypts no field before it reaches PostgreSQL. A national identifier +belongs in the master patient index, never in the CDR, which knows the subject +only as a pseudonym +([Privacy & data minimisation](installation/config-privacy.md#national-identifiers-belong-in-the-master-patient-index)), +so the server holds no identifier to seal. What it does hold, every party and +every clinical record, sits in the database as written. GDPR Art. 32(1)(a) +names encryption as a measure for that risk: encrypt every database volume, +replicas and WAL archives included, and every backup and dump at rest, with the +keys outside the database hosts. The +[go-live checklist](security/go-live-checklist.md#9-the-database-volumes-and-backups-are-encrypted-at-rest) +checks it before real data arrives. + +## Resolving across the boundary + +One question needs both domains at once: *which record belongs to this +person?* The server answers it in the application, over two connections, never +in the database. An EHR names its subject in its own +`EHR_STATUS.subject.external_ref`, which the `ehr` relation copies into its +subject columns on every EHR create and `EHR_STATUS` update. A cohort and the +AQL demographic join read the parties on the `party` connection and the EHRs whose subject names them on the `clinical` connection, +with a second search path and, when `[database.party] url` is set, a second +database role. FerroEHR matches, links and merges no patients, and holds no +national identifier: resolving a person to their pseudonym is the master +patient index's job. + +**No statement performs the join, because no credential could**: the +clinical role holds no grant in `party` and the party role holds none in +`clinical`, both revocations are explicit and in both directions, and the boot +check refuses to serve a database where either has been given one. The +crossing exists as an application step that can be audited, rather than as a +query anyone holding one password could write. + +Every crossing records an access event in the `linkage` domain, naming who +asked, the purpose of use they declared, and how many EHRs it reached. A miss +is recorded like a hit: it says someone asked whether this deployment holds a +record for that person. The event deliberately does **not** name the EHR that +came back. A record pairing a party with its EHR would make the audit trail a +map from parties to their EHRs, which the split exists to withhold. + +Looking an EHR up by subject (`GET /ehr?subject_id=…&subject_namespace=…`) +does **not** cross the boundary. That operation matches the EHR's own +`EHR_STATUS.subject.external_ref`, which is the opaque pseudonym the privacy +layer already constrains, so it resolves a pseudonym rather than an identity +and reads no party. It records a linkage-domain access event all the same, +naming the subject namespace and the EHR it found, because who resolved a +subject to a record is worth knowing wherever it happened. + +The lookup puts the subject identifier in the URL, because ITS-REST passes it +as a query parameter. FerroEHR keeps it out of everything it writes: the +request log and every trace span record the path and the matched route without +the query string, and the `404` for an unknown subject names only the +namespace. A reverse proxy or load balancer in front of FerroEHR sees the whole +URL, so configure it not to log query strings on this route, or not at all. +FerroPIX as the EHR index provider (IHE PIXm, `record.subject_index = "pixm"`) +resolves a patient identifier to an EHR without putting it in a FerroEHR URL. + +## The subject link in the party domain + +The access evaluator needs the `PERSON` of an EHR's subject to read its care +relationships and its representatives. Under `record.subject_index = "pixm"` +the EHR names its subject by a pseudonym, so the patient's `PERSON` declares +it: an element of `PARTY.details` named by the `record_subject` code of +the draft openEHR access terminology `openehr_access`, +whose `DV_IDENTIFIER` holds the pseudonym and its namespace. An identifier +another organisation issued belongs in `details` (RM Demographic IM §2.1.3), +and the cross-reference stays out of the EHR (RM EHR IM §EHR Status). FerroEHR +projects it into the party table `binding_record_subject` at the commit of the +`PERSON`, and each replica holds the resolutions it uses in a bounded cache, +so a decision on a held subject adds no database transaction, a miss costs one +indexed read, and no decision calls the identity source. + +**This is an accepted trade-off.** Without the +element, mapping a pseudonym back to a person needs a steward action in the +identity source. With it, the party domain maps the pseudonym to the `PERSON` +for every patient whose `PERSON` carries the element. The clinical side is +unchanged: it holds the pseudonym alone, and `ferroehr_clinical` still reads +nothing in `party`. Re-identifying a clinical record still needs both domains, +so the condition of GDPR Art. 4(5), additional information kept separately, +holds inside the CDR, and the link sits in the party domain under its own role +and dump, the "identity cross-reference" BASE Architecture Overview §Anonymity +describes. Only the `PERSON`s that need care relationships or representation +need the element, so the exposure is per patient (Art. 25(2)). The evaluator's +resolution tells the caller nothing, so it writes no `linkage` access event; a +representative's EHR lookup records one per subject reference it resolves. + +## Declaring the posture + +The separations above are each a configuration key, and a deployment that has +made none of them is indistinguishable from one that has made all of them +until something goes wrong. The top-level `deployment.profile` key +([configuration](installation/configuration.md#deploymentprofile)) makes the +posture explicit: `production` refuses to start while a separation is missing +and not accepted by name, and reads the cluster each pool reached from +`pg_control_system()` rather than trusting the DSN text; `sandbox`, the +default, names every missing separation on the banner, in the boot log and on +`GET /management/status`, reports the profile on `GET /rest/status`, and must +not hold real patient data. The database keeps +its own line of defence for the subject pseudonym too: once +`privacy.subject_namespaces` is declared, a trigger on `ehr` refuses a subject +reference that is not a UUID, whichever code path or session writes it. diff --git a/website/book/src/querying-aql.md b/website/book/src/querying-aql.md index bc1b517ac6..91b61e3bc3 100644 --- a/website/book/src/querying-aql.md +++ b/website/book/src/querying-aql.md @@ -43,14 +43,14 @@ ORDER BY o/data[at0001]/events[at0006]/data[at0003]/items[at0004]/value/magnitud Data recorded under an ADL 1.4 id (`.v1` alone) is found only by a `.v1` query. The namespace must match exactly: `org.example::…` finds only data recorded in `org.example`, and an id without a namespace finds only data - recorded without one (#4629, #4630). + recorded without one. - **`CONTAINS`** expresses structural containment: "an EHR that contains a composition that contains a blood-pressure observation". Chains can nest several deep, and combine with `AND`, `OR`, and `NOT`. Folder containment follows the RM's reference model: `FOLDER f CONTAINS COMPOSITION c` matches the compositions a folder's `items` reference, transitively over the folder's sub-tree, and `FOLDER f1 CONTAINS FOLDER f2` matches strict - sub-folders plus the folders of a versioned folder the `items` reference — + sub-folders plus the folders of a versioned folder the `items` reference, one reference hop, so a chain of references is expressed by chaining `CONTAINS`. A pair the RM defines no containment relationship for (say `COMPOSITION CONTAINS COMPOSITION`) is refused with a typed error. @@ -428,7 +428,7 @@ producing a list of patient identifiers first, which is exactly the disclosure the split between clinical and demographic storage exists to avoid. `POST /ferroehr/rest/extensions/v1/query/cohort` answers them without producing that list. It is a FerroEHR -extension — no openEHR spec governs it: AQL is defined over the clinical domain +extension; no openEHR spec governs it: AQL is defined over the clinical domain and has no demographic source, and ITS-REST publishes an ad-hoc and a stored query and nothing else. @@ -436,7 +436,7 @@ query and nothing else. 1. A predicate from the deployment's allow-list selects **parties** in the demographic domain. It reads one archetype leaf and returns identifiers, - nothing else — no name, address or national identifier leaves that domain. + nothing else: no name, address or national identifier leaves that domain. 2. Those parties resolve to the **EHRs** whose `EHR_STATUS.subject` names them: the `external_ref` whose `id.value` is the party's uid without `::::`, the reference `POST /ehr` stores. Identifiers in, @@ -449,7 +449,7 @@ other, and the server refuses to boot if one can read across. You never receive identifier: the response carries what your AQL projected, plus counts. **The allow-list.** A cohort predicate can only name something the deployment -declared, under `[privacy.cohort.predicates]` — the surface is off until at least one is +declared, under `[privacy.cohort.predicates]`; the surface is off until at least one is bound, and the route answers `404` until then. Five keys are bindable: `city`, `postcode_area`, `sex`, `age_band` and `organisation`. Each binding names the archetype of the leaf's nearest archetyped ancestor, the leaf's @@ -496,7 +496,7 @@ curl -u ferroehr:ferroehr -X POST \ `q`, `offset`, `fetch` and `query_parameters` mean what they mean on the ad-hoc body. There is no `ehr_id`: the cohort **is** the scope, and supplying one is a -`400`. Several `cohort` entries **intersect** — city *and* sex, not city *or* +`400`. Several `cohort` entries **intersect**: city *and* sex, not city *or* sex. The response is an ordinary `RESULT_SET` with one extra block: @@ -517,7 +517,7 @@ The response is an ordinary `RESULT_SET` with one extra block: ``` `size` is how many EHRs the cohort resolved to, `served_ehrs` how many the rows -actually came from, and `definition` a SHA-256 digest of the predicate list — +actually came from, and `definition` a SHA-256 digest of the predicate list: the cohort's identity, carrying none of its values. **Small-cell suppression.** A result set narrow enough to name one person @@ -528,7 +528,7 @@ looking like an empty cohort: a caller who cannot tell the two apart will keep widening the predicate until the boundary leaks. Set the threshold to `0` to disable suppression. -**The access record.** Every execution — suppressed and failed ones included — +**The access record.** Every execution, suppressed and failed ones included, records one `linkage`-domain access event naming the cohort by its digest, the purpose you declared, and how many EHRs were served. A crossing of this boundary that nobody can reconstruct afterwards is what the access log exists to prevent. @@ -536,7 +536,7 @@ The predicate values are never recorded: they *are* the cohort, and a trail carrying them would be a second copy of it. **Limits.** A predicate matching more than `privacy.cohort.max_cohort_size` parties -(default `100000`) is refused `422` rather than truncated — a silently shortened +(default `100000`) is refused `422` rather than truncated: a silently shortened cohort is a wrong denominator with nothing on the wire to say so. More named subjects than that ceiling are refused the same way. An unbound predicate name, a malformed age band (the form is `-` whole years, both @@ -711,7 +711,7 @@ gets `400` with a message naming the rule. **Who may run it, and what they see.** The log has its own access control, apart from any clinical query right, and the query follows the rules of the -[access log's own resources](audit.md#reading-the-access-log-over-its-rest): +[access log's own resources](access-log.md#reading-the-access-log-over-its-rest): | Caller | Reads | |---|---| diff --git a/website/book/src/reference/aql-functions.md b/website/book/src/reference/aql-functions.md new file mode 100644 index 0000000000..c18be9a067 --- /dev/null +++ b/website/book/src/reference/aql-functions.md @@ -0,0 +1,29 @@ + + + + +# AQL built-in functions + +**For:** integrators. Every built-in single-row function the AQL parser +accepts, by the group the AQL specification puts it in (QUERY, §Functions). +Names compare without regard to case. How to use them, the aggregates and +FerroEHR's extension functions are on [Querying with AQL](../querying-aql.md). + +| Function | Group | +|---|---| +| `LENGTH` | string | +| `CONTAINS` | string | +| `POSITION` | string | +| `SUBSTRING` | string | +| `CONCAT` | string | +| `CONCAT_WS` | string | +| `ABS` | numeric | +| `MOD` | numeric | +| `CEIL` | numeric | +| `FLOOR` | numeric | +| `ROUND` | numeric | +| `CURRENT_DATE` | date and time | +| `CURRENT_TIME` | date and time | +| `CURRENT_DATE_TIME` | date and time | +| `NOW` | date and time | +| `CURRENT_TIMEZONE` | date and time | diff --git a/website/book/src/reference/cli.md b/website/book/src/reference/cli.md new file mode 100644 index 0000000000..74b8484131 --- /dev/null +++ b/website/book/src/reference/cli.md @@ -0,0 +1,742 @@ + + + + +# Command-line reference + +**For:** operators. Every command and option of the `ferroehr` binary, +as `ferroehr --help` prints it. The guides to the commands are +on [CLI & production checklist](../installation/config-cli.md). + + + +## `ferroehr` + +```text +openEHR-conformant CDR server + +Usage: ferroehr [OPTIONS] [COMMAND] + +Commands: + serve Serves until the process is asked to stop + config Works on the configuration + healthcheck Asks the server running beside this process whether it is ready, and exits 0 only when it is + db Database schema utilities (apply or verify the migrations, or erase the instance), then exit + usage-report The usage report to `FerroPULSE`: print the report this instance would send, without sending it + definitions The definition store: `load` templates from files before `serve` + access-log The access log: seal a checkpoint, verify, export and import + audit-chain The system chain, the records outside the access log: seal its head and verify it + party-binding The party binding side table: `refill` it after a mapping change + pmir The PMIR feed messages the consumer refused: list, retry or settle them + report Write a redacted report of what this deployment runs (build, features, specification pins, migration level, posture, licence, manufacturer and configuration), the file a complaint or an incident report attaches + help Print this message or the help of the given subcommand(s) + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help + + -V, --version + Print version +``` + +## `ferroehr serve` + +```text +Serves until the process is asked to stop + +Usage: ferroehr serve [OPTIONS] + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr config` + +```text +Works on the configuration + +Usage: ferroehr config [OPTIONS] + +Commands: + check Reads the configuration, reports every refusal with its key, and prints the running tree with every secret redacted + help Print this message or the help of the given subcommand(s) + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr config check` + +```text +Reads the configuration, reports every refusal with its key, and prints the running tree with every secret redacted + +Usage: ferroehr config check [OPTIONS] + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr healthcheck` + +```text +Asks the server running beside this process whether it is ready, and exits 0 only when it is + +Usage: ferroehr healthcheck [OPTIONS] + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr db` + +```text +Database schema utilities (apply or verify the migrations, or erase the instance), then exit + +Usage: ferroehr db [OPTIONS] + +Commands: + migrate Apply the embedded migrations and exit; the DSN must hold DDL rights + verify Verify, without issuing any DDL, that the database carries exactly this build's migrations; exit 0 when it does, 1 otherwise + erase Permanently erase every piece of data and every setting this instance stores: the multimedia blobs, then every schema the migrations create + sweep-blobs Delete every multimedia blob no stored version references and that is older than `[record.multimedia] orphan_grace`: the blobs commits that failed after their upload left behind + help Print this message or the help of the given subcommand(s) + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr db migrate` + +```text +Apply the embedded migrations and exit; the DSN must hold DDL rights + +Usage: ferroehr db migrate [OPTIONS] + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr db verify` + +```text +Verify, without issuing any DDL, that the database carries exactly this build's migrations; exit 0 when it does, 1 otherwise + +Usage: ferroehr db verify [OPTIONS] + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr db erase` + +```text +Permanently erase every piece of data and every setting this instance stores: the multimedia blobs, then every schema the migrations create. + +Without `--confirm` it erases nothing: it prints what it would erase and the value `--confirm` must carry, and exits 1. Run it with every server stopped; the DSN must own the schemas. + +Usage: ferroehr db erase [OPTIONS] + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --confirm + The instance to erase, as the run without `--confirm` prints it: the stored instance id, or the clinical database's name when the database stores no instance id + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help (see a summary with '-h') +``` + +## `ferroehr db sweep-blobs` + +```text +Delete every multimedia blob no stored version references and that is older than `[record.multimedia] orphan_grace`: the blobs commits that failed after their upload left behind. + +Without `--apply` it deletes nothing and prints what it would delete. It can run while servers serve: a blob younger than the grace period is always kept. + +Usage: ferroehr db sweep-blobs [OPTIONS] + +Options: + --apply + Delete the orphans instead of listing them + + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help (see a summary with '-h') +``` + +## `ferroehr usage-report` + +```text +The usage report to `FerroPULSE`: print the report this instance would send, without sending it + +Usage: ferroehr usage-report [OPTIONS] --print + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --print + Print the report as the exact JSON body a send would carry, then exit. Required: printing is the only action + + --event + Which report to print + + Possible values: + - start: The report sent at each process start + - daily: The report sent once a day, with the metrics window + + [default: start] + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help (see a summary with '-h') +``` + +## `ferroehr definitions` + +```text +The definition store: `load` templates from files before `serve` + +Usage: ferroehr definitions [OPTIONS] + +Commands: + load Store each file in the definition store, in the order given, with the validation and versioning of the REST upload, then exit. An `.opt` file is an OPT 1.4 template and an `.adls` file an ADL 2 archetype or template, whose parents and slot fillers come before it. A file whose id is stored with the same text is left alone; one stored with other text is refused + help Print this message or the help of the given subcommand(s) + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr definitions load` + +```text +Store each file in the definition store, in the order given, with the validation and versioning of the REST upload, then exit. An `.opt` file is an OPT 1.4 template and an `.adls` file an ADL 2 archetype or template, whose parents and slot fillers come before it. A file whose id is stored with the same text is left alone; one stored with other text is refused + +Usage: ferroehr definitions load [OPTIONS] ... + +Arguments: + ... + The definition files + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr access-log` + +```text +The access log: seal a checkpoint, verify, export and import + +Usage: ferroehr access-log [OPTIONS] + +Commands: + checkpoint Print the checkpoint of the head of the access log, sealing it with the keyring's key when no append sealed it + verify Verify the access log against its newest checkpoint, or the one in `--checkpoint`, and print every finding. Exits non-zero when the log does not verify + export Export one EHR's access log, with the checkpoint it verifies against, for the EHR's transfer to another system + import Import an EHR's access log another system exported, verified against its checkpoint and `[audit.access_log] trusted_key_files`, and record the import as an entry of this system's log + help Print this message or the help of the given subcommand(s) + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr access-log checkpoint` + +```text +Print the checkpoint of the head of the access log, sealing it with the keyring's key when no append sealed it + +Usage: ferroehr access-log checkpoint [OPTIONS] + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr access-log verify` + +```text +Verify the access log against its newest checkpoint, or the one in `--checkpoint`, and print every finding. Exits non-zero when the log does not verify + +Usage: ferroehr access-log verify [OPTIONS] + +Options: + --checkpoint + A checkpoint kept outside this system, as the JSON `ferroehr access-log checkpoint` printed + + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr access-log export` + +```text +Export one EHR's access log, with the checkpoint it verifies against, for the EHR's transfer to another system + +Usage: ferroehr access-log export [OPTIONS] --ehr-id + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --ehr-id + The EHR whose log is exported + + --output + Where to write the export; `-` or unset writes it to stdout + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr access-log import` + +```text +Import an EHR's access log another system exported, verified against its checkpoint and `[audit.access_log] trusted_key_files`, and record the import as an entry of this system's log + +Usage: ferroehr access-log import [OPTIONS] --input + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --input + The export to import + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr audit-chain` + +```text +The system chain, the records outside the access log: seal its head and verify it + +Usage: ferroehr audit-chain [OPTIONS] + +Commands: + seal Seal every committed system record in windows with the keyring's key, and print the newest window's seal + verify Verify every sealed window of the system records against the newest seal, or the one in `--seal`, and print every finding. Exits non-zero when the records do not verify + help Print this message or the help of the given subcommand(s) + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr audit-chain seal` + +```text +Seal every committed system record in windows with the keyring's key, and print the newest window's seal + +Usage: ferroehr audit-chain seal [OPTIONS] + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr audit-chain verify` + +```text +Verify every sealed window of the system records against the newest seal, or the one in `--seal`, and print every finding. Exits non-zero when the records do not verify + +Usage: ferroehr audit-chain verify [OPTIONS] + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --seal + A seal kept outside this system, as the JSON `ferroehr audit-chain seal` printed + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr party-binding` + +```text +The party binding side table: `refill` it after a mapping change + +Usage: ferroehr party-binding [OPTIONS] + +Commands: + refill Rebuild the binding side table, the policy grants included, from the party versions under the configured mapping and store its digest. Run it with every replica stopped: it refuses while a replica's lease is live. A key issuer added or removed needs no refill: the running replicas fill and retire its key space themselves. With no mapping configured it rebuilds the policy grants alone. It then rebuilds the `EHR_ACCESS` projection from every EHR's current `EHR_ACCESS` version + check Report, from the party versions and writing nothing, what binding will make of them: the keys per issuer, duplicates, inactive and abandoned persons, the provisional persons just-in-time creation left incomplete for longer than `[authz.party_binding] provisional_report_after`, key-bearing persons with no professional `ROLE`, the mapped Basic users, and the committer that introduced each key. It exits non-zero on a duplicate, a missing person or a key whose committer fails the provenance rule + adopt Give each listed `PERSON` a professional `ROLE` of the mapping's role template, in one demographic CONTRIBUTION committed by the first administrator named, with one access record per adopted `PERSON`. It refuses, naming them, the `PERSON`s whose key fails the provenance rule of `check` + grant Grant an operation of the `openehr_access` terminology to a client, on the operator's authority: an `AGENT` carrying the client identifier, unless an `ACTOR` names the client already, and a `ROLE` it performs whose capability grants the operation with the scope elements given. It is the first grant of a new deployment, such as the `scim_provision` of the client that provisions the administrators; every later grant is an administrator's write through the Demographic API. A client that holds the operation already gets nothing. With `--basic-user`, the `ROLE` is performed by the `PERSON` the Basic user binds to, such as the `hold_scopes` of a development lane's users + help Print this message or the help of the given subcommand(s) + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr party-binding refill` + +```text +Rebuild the binding side table, the policy grants included, from the party versions under the configured mapping and store its digest. Run it with every replica stopped: it refuses while a replica's lease is live. A key issuer added or removed needs no refill: the running replicas fill and retire its key space themselves. With no mapping configured it rebuilds the policy grants alone. It then rebuilds the `EHR_ACCESS` projection from every EHR's current `EHR_ACCESS` version + +Usage: ferroehr party-binding refill [OPTIONS] + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr party-binding check` + +```text +Report, from the party versions and writing nothing, what binding will make of them: the keys per issuer, duplicates, inactive and abandoned persons, the provisional persons just-in-time creation left incomplete for longer than `[authz.party_binding] provisional_report_after`, key-bearing persons with no professional `ROLE`, the mapped Basic users, and the committer that introduced each key. It exits non-zero on a duplicate, a missing person or a key whose committer fails the provenance rule + +Usage: ferroehr party-binding check [OPTIONS] + +Options: + --admin + An administrator, named by the container id of its `PERSON`: a key its commit introduced passes the provenance rule + + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --admin-key + An administrator, named by the `identifier_issuer` and value of a binding key its `PERSON` carries + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + --migration + The committer name of a migration the operator declares: a key its commit introduced passes the provenance rule + + --expected + The identity provider's assigned users, one login identifier per line: every one with no `PERSON` is listed + + --expected-issuer + The `identifier_issuer` the `--expected` logins are keys of; needed when more than one `[auth.issuer..party]` table is configured + + -h, --help + Print help +``` + +## `ferroehr party-binding adopt` + +```text +Give each listed `PERSON` a professional `ROLE` of the mapping's role template, in one demographic CONTRIBUTION committed by the first administrator named, with one access record per adopted `PERSON`. It refuses, naming them, the `PERSON`s whose key fails the provenance rule of `check` + +Usage: ferroehr party-binding adopt [OPTIONS] ... + +Arguments: + ... + The container ids of the `PERSON`s to adopt + +Options: + --admin + An administrator, named by the container id of its `PERSON`: a key its commit introduced passes the provenance rule + + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --admin-key + An administrator, named by the `identifier_issuer` and value of a binding key its `PERSON` carries + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + --migration + The committer name of a migration the operator declares: a key its commit introduced passes the provenance rule + + -h, --help + Print help +``` + +## `ferroehr party-binding grant` + +```text +Grant an operation of the `openehr_access` terminology to a client, on the operator's authority: an `AGENT` carrying the client identifier, unless an `ACTOR` names the client already, and a `ROLE` it performs whose capability grants the operation with the scope elements given. It is the first grant of a new deployment, such as the `scim_provision` of the client that provisions the administrators; every later grant is an administrator's write through the Demographic API. A client that holds the operation already gets nothing. With `--basic-user`, the `ROLE` is performed by the `PERSON` the Basic user binds to, such as the `hold_scopes` of a development lane's users + +Usage: ferroehr party-binding grant [OPTIONS] --operation + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --issuer + The issuer of the client's tokens + + --client-id + The client's OAuth 2.0 `client_id` + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + --basic-user + The Basic user of `[[auth.basic.users]]` whose `PERSON` is granted the operation, found by the binding key `[[authz.party_binding.basic_user]]` maps it by, in place of a client + + --operation + The operation's code, such as `scim_provision` + + --element + A scope element of the grant, its code of the draft access terminology and the text it names, such as `binding_issuer=urn:example:login` + + --provider-issuer + The issuer of a `provider` element's `DV_IDENTIFIER`, paired in order with `--provider-id`: a provider whose care relationships and memberships a `write_care_relationship` grant writes + + --provider-id + The id of a `provider` element's `DV_IDENTIFIER`, paired in order with `--provider-issuer` + + -h, --help + Print help +``` + +## `ferroehr pmir` + +```text +The PMIR feed messages the consumer refused: list, retry or settle them + +Usage: ferroehr pmir [OPTIONS] + +Commands: + list Print the refused messages still to retry or settle, oldest first, as JSON: each with its refusal code, receipt and refusal time, attempts, the Registry's identities it names and the `PERSON`s it keeps split, as counts. No identifier value is printed + retry Put a refused message back at its arrival position once its cause is fixed, such as a `[[pix.identifier_domain]]` entry or a grant added; a running replica applies it next. Refused when a message received after it that names one of its identities has applied + settle Close a refused message without applying it: `discard` keeps its splits, `lift-splits` removes them so its identifiers and record subjects resolve as before the message. A discarded message may still have its splits lifted + help Print this message or the help of the given subcommand(s) + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr pmir list` + +```text +Print the refused messages still to retry or settle, oldest first, as JSON: each with its refusal code, receipt and refusal time, attempts, the Registry's identities it names and the `PERSON`s it keeps split, as counts. No identifier value is printed + +Usage: ferroehr pmir list [OPTIONS] --operator + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --operator + The operator the access records name + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr pmir retry` + +```text +Put a refused message back at its arrival position once its cause is fixed, such as a `[[pix.identifier_domain]]` entry or a grant added; a running replica applies it next. Refused when a message received after it that names one of its identities has applied + +Usage: ferroehr pmir retry [OPTIONS] --operator + +Arguments: + + The message's `MessageHeader.id` + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --operator + The operator the access record names + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` + +## `ferroehr pmir settle` + +```text +Close a refused message without applying it: `discard` keeps its splits, `lift-splits` removes them so its identifiers and record subjects resolve as before the message. A discarded message may still have its splits lifted + +Usage: ferroehr pmir settle [OPTIONS] --decision --reason --operator + +Arguments: + + The message's `MessageHeader.id` + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --decision + `discard` or `lift-splits` + + --reason + Why, 1 to 1000 characters naming no identifier + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + --operator + The operator the row and the access record name + + -h, --help + Print help +``` + +## `ferroehr report` + +```text +Write a redacted report of what this deployment runs (build, features, specification pins, migration level, posture, licence, manufacturer and configuration), the file a complaint or an incident report attaches + +Usage: ferroehr report [OPTIONS] + +Options: + --config + The TOML configuration file; unset, the product's `_CONFIG` variable names it + + --output + Where to write the report; `-` writes it to stdout. Unset, it is `ferroehr-report-.json` in the working directory + + --set + One configuration key set over the file and the environment, as `key=value`; repeatable + + -h, --help + Print help +``` diff --git a/website/book/src/reference/refusal-codes.md b/website/book/src/reference/refusal-codes.md new file mode 100644 index 0000000000..da0ae2ef46 --- /dev/null +++ b/website/book/src/reference/refusal-codes.md @@ -0,0 +1,31 @@ + + + + +# Access refusal codes + +**For:** integrators and operators. Every code the access evaluator refuses +a request under, with the status the caller receives. A `403` names its code +in the problem's `detail`; a `404` answers as if the data did not exist and +names nothing. A `refused-confidentiality` answers `404` instead at a level +the access policy conceals. The access log records the code either way. What each step +decides is on [How FerroEHR decides access](../explanation/access-model.md). + +| Code | Answer | +|---|---| +| `refused-opt-out` | 404 | +| `refused-restricted` | 404 | +| `refused-consent-denied` | 403 | +| `refused-policy-denied` | 403 | +| `refused-sensitivity` | 403 | +| `refused-confidentiality` | 403 | +| `refused-no-care-relationship` | 403 | +| `refused-outside-episode` | 403 | +| `refused-purpose-missing` | 403 | +| `refused-reason-missing` | 403 | +| `refused-consent-required` | 403 | +| `refused-not-subject` | 403 | +| `refused-not-represented` | 403 | +| `refused-consent-reference-missing` | 403 | +| `refused-excluded` | 403 | +| `refused-conflict` | 403 | diff --git a/website/book/src/security.md b/website/book/src/security.md index 99da7654a4..cbed50c47d 100644 --- a/website/book/src/security.md +++ b/website/book/src/security.md @@ -73,7 +73,6 @@ honour **refuses to boot** rather than degrading at the first request: | a `password_hash` below `m=19456,t=2,p=1` argon2id | error: the OWASP Argon2id floor | | `[authz.assurance] minimum` with an empty `levels` map, or with no mapped value at or above it | error: every patient-data request would be refused | | an `[authz.assurance] levels` value that is blank or carries whitespace, a quote or a backslash | error: the step-up challenge names the values in one quoted `acr_values` parameter (RFC 9470 §3) | -| `[authz.professional]` | error: removed; the token's `fhirUser` classifies the caller | | two issuers sharing an audience, or no `[authz.party_binding] provider` | error: every person is bound to a party, under the provider the deployment acts for | | a Basic user with no `[[authz.party_binding.basic_user]]` mapping | error: a Basic user is a person, bound by its key | | an `[authz.rbac] role_issuers` entry that names a `federation` issuer | error: only the deployment's own people hold an administrator role | @@ -183,7 +182,7 @@ acting for the user (RFC 9068 §2.2, RFC 8693 §4.1). The authorization server's registry is the one list of clients, so a token whose `aud` names FerroEHR admits its client. The access record names the person by their `sub`, and a delegated token's actor beside them; see [Audit -trail](audit.md#the-ehds-logging-elements-mapped). +trail](ehds-logging.md#the-ehds-logging-elements-mapped). What counts as **patient data**: every API route except the definition family (`/definition/...`: templates, archetypes, stored-query texts), terminology, @@ -225,834 +224,10 @@ hours) if prompt revocation matters, and use refresh tokens for session length. ## Authorization -Authorization has two composable layers. The per-EHR `EHR_ACCESS` gate with -the access evaluator is the openEHR-grounded base and is always on; the coarse -role layer is active when authentication is enabled. A request must clear every -active layer. Deployments serving SMART apps can enable a third, token-scope -layer on top; see [SMART App Launch](smart-app-launch.md). The access -evaluator alone confines a patient to their own EHR -([a patient's own EHR](#a-patients-own-ehr)). - -The model as a whole (parties, roles and grants, the patient's settings, the -access policy, justification and the legal marks) is explained on [How -FerroEHR decides access](explanation/access-model.md). This section holds the -details of each part. - -### Per-EHR access control (`EHR_ACCESS`) - -Every EHR carries a versioned `EHR_ACCESS` object, the openEHR -access-decision authority for that record. A new EHR has no settings, and what -that admits is a **server-wide choice**: - -| `authz.rbac.ehr_access_default` | An EHR with no settings | -|---|---| -| `open` *(default)* | reachable by any caller the coarse layers already admitted | -| `restricted` | reachable only by `authz.rbac.admin_role` | - -`open` is the default because it is what every existing deployment runs, and -changing it changes who can read existing records. `restricted` is object-level -**default-deny**, and it is the setting to reach for if your threat model -includes a caller enumerating record ids: a server-created `ehr_id` is a -time-ordered UUIDv7, so it is not even unpredictable, and the OWASP -[Insecure Direct Object Reference Prevention](https://cheatsheetseries.owasp.org/cheatsheets/Insecure_Direct_Object_Reference_Prevention_Cheat_Sheet.html) -cheat sheet is explicit that an unpredictable identifier is not itself an access -control. - -> [!NOTE] -> Under `restricted`, the admin role still reaches a setting-less EHR. That is -> deliberate: a plain deny would make such a record unreachable by everyone -> (including the operator who would author the settings that fix it) which is an -> outage rather than a control. A patient reaches only their own EHR -> ([a patient's own EHR](#a-patients-own-ehr)); this key decides only the -> default disposition. - -Committing settings of the `access_directives` scheme switches that EHR to -explicit policy, and those settings **always win over the server default**, -in both directions. The settings are an `ACCESS_DIRECTIVE_SETTINGS`, a class -of FerroEHR's draft access control package, and every coded value is a code -of the access control groups of the draft openEHR access terminology `openehr_access`: - -```json -{ - "_type": "EHR_ACCESS", - "name": { "_type": "DV_TEXT", "value": "EHR Access" }, - "archetype_node_id": "openEHR-EHR-EHR_ACCESS.access_directives.v1", - "archetype_details": { - "_type": "ARCHETYPED", - "archetype_id": { "_type": "ARCHETYPE_ID", - "value": "openEHR-EHR-EHR_ACCESS.access_directives.v1" }, - "rm_version": "1.2.0" - }, - "settings": { - "_type": "ACCESS_DIRECTIVE_SETTINGS", - "default_access": { - "_type": "DV_CODED_TEXT", "value": "restricted", - "defining_code": { "_type": "CODE_PHRASE", - "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr_access" }, - "code_string": "restricted" } - }, - "gate_keepers": [ - { "_type": "PARTY_SELF" }, - { "_type": "PARTY_RELATED", - "external_ref": { "_type": "PARTY_REF", "namespace": "demographic", "type": "PERSON", - "id": { "_type": "HIER_OBJECT_ID", - "value": "0190b3a2-5a3e-7c1d-9e2f-3b4c5d6e7f80" } }, - "relationship": { "_type": "DV_CODED_TEXT", "value": "guardian", - "defining_code": { "_type": "CODE_PHRASE", - "terminology_id": { "_type": "TERMINOLOGY_ID", "value": "openehr" }, - "code_string": "10" } } } - ] - } -} -``` - -- **Default access:** `open` admits any caller the other layers admit. - `restricted` admits the administrator (`authz.rbac.admin_role`), the - gate-keepers, a caller with a live care relationship to the subject and a - caller a consent permit names; `consent_required` admits the - administrator, the gate-keepers and a caller a consent permit names. Every - other caller gets `403` with `refused-consent-required`. The record's - person always reads their own record. An EHR Extract export by manifest - (`POST /message/export`) passes the access evaluator for every EHR the - manifest names before it reads any content, so one EHR the caller may not - reach refuses the whole export. -- **Who writes the settings:** while the current settings name no - gate-keeper, the record's person writes their own settings, as a - mentally competent adult is their own gate-keeper (BASE Architecture - Overview, Access Control). Once the settings name gate-keepers, a new - `EHR_ACCESS` version is committed only by a gate-keeper they name. - `PARTY_SELF` names the record's person; any other gate-keeper names a - party of the demographic service by its `external_ref`, matched against - the `PERSON` the caller is bound to. Naming gate-keepers without - `PARTY_SELF`, such as a guardian, takes the person's own write away. - Changing `gate_keepers` is itself a write, so only a current writer - changes them. An administrator acting on the person's instruction writes - in every case. Settings held closed are written only by an administrator. - Every other caller is refused with `403`. A gate-keeper commits changes with a - CONTRIBUTION (there is no dedicated `EHR_ACCESS` endpoint in the openEHR - REST API). The controller commits them on the person's instruction with - `POST /ferroehr/rest/extensions/v1/admin/ehr-access`, which names the EHR - in its body, so it reaches an EHR a restriction hides, and reads every - version with `GET /ferroehr/rest/extensions/v1/admin/ehr-access?ehr_id=…`. - Every change is versioned and audited like all record content. -- **Who reads the settings:** the administrator, the record's person and the - gate-keepers. To anyone else the settings are absent, so a restriction stays - invisible to a provider (EHDS Art. 8): an AQL query returns no - `EHR_ACCESS` row of the EHR, an EHR Extract leaves its `EHR_ACCESS` out, - and a CONTRIBUTION that commits an `EHR_ACCESS` version reads as unknown - (`404`). One caller more receives the `EHR_ACCESS` in an EHR Extract: the - holder of an `export_ehr_extract` grant whose `subject_namespace` covers - the EHR, such as a migration client, since the extract transfers the whole - EHR and an import elsewhere must keep the person's directives. Those - callers read the settings over the wire with - `GET /ferroehr/rest/extensions/v1/ehr/{ehr_id}/ehr_access` and its - `versioned_ehr_access` reads, a FerroEHR extension shaped on the - `EHR_STATUS` reads ([Resource walkthroughs](using-the-api/resources.md#ehr_access)), - which another product uses to exchange the directives. -- **Every write is checked:** a CONTRIBUTION, an EHR Extract import and an - admin archive load that carry settings are refused whole naming the first - defect: with `400` for settings of another scheme (the removed - `FERROEHR_ACCESS_CONTROL_V1` among them) or a member the class does not - declare, and with `422` for a broken invariant of the draft package, named - as `CLASS.Invariant`, such as `ACCESS_DIRECTIVE.Restriction_denies`, or a - `DV_DATE_TIME` or `DV_DURATION` that is no ISO 8601 value - (`DV_DATE_TIME.Value_valid`). The - same writes, and the controller's commit, refuse with `422` a directive - that names a party the demographic service does not hold, naming the - directive and the party: an actor scope's `party`, or the `external_ref` - of the `instructed_by` party, in the directive or any of its exceptions. A - reference of another type than the party it names is refused the same - way, and so is an id that is no UUID, since the evaluator could never - match it to a caller. A gate-keeper whose `external_ref` names such a - party is refused the same way, naming the gate-keeper, since it would lock - the settings to nobody. An import may name a party its own demographics - chapter carries, and an archive load one its demographic records carry. - An import and an archive load check only the head `EHR_ACCESS` version, - the one in force: an earlier version is the unchanged record of what was - in force then and decides nothing, so a party erased since (under GDPR - Art. 17, for example) never blocks a faithful restore of your own export. - `PARTY_SELF` names the record's person and needs no lookup. -- **Unreadable settings:** stored settings that do not read as the scheme - hold the EHR closed. A request that names the EHR is refused with `500`, - no query reaches it, and the server logs an error naming it. Only settings - stored before the write check can hold an EHR. An administrator repairs a - held EHR with - `POST /ferroehr/rest/extensions/v1/admin/ehr-access/repair`, body - `{"ehr_id": "…", "settings": {…}}`: the new settings must pass the write - check, the repair commits a new `EHR_ACCESS` version with its own commit - audit and contribution, and it writes an access record - (`ehr-access-repair:`) naming the administrator. The - repair is refused with `409` for an EHR that is not held; such an EHR - changes its settings with a CONTRIBUTION. -- **Every replica decides by the committed settings:** the commit of an - `EHR_ACCESS` version writes the EHR's settings into a side table in the - same transaction, as a settings class and its facts, and notifies every - replica when it commits. The class is what the EHR's settings share with - others, and the facts are what is particular to the EHR: instants, parties, - objects and origins. Every opt-out from a date shares one class. Each - replica holds a copy of the settings of the EHRs it read most recently and - of every class, and drops an entry on that notification, so a revoked - gate-keeper or directive decides the next request on every replica. A query - reads each EHR's class and facts in its own SQL, so its counts and pages - stay exact. An EHR of a class the replica has not copied yet contributes no - row. While a replica's listener is down it reads the settings on every - request, and a settings store that cannot answer is `503`. The first boot - fills the side table from the stored versions, and - `ferroehr party-binding refill` rebuilds it. -- **What a replica holds does not grow with the EHRs that carry settings:** - at most 4096 EHRs' settings and the settings classes. The measured sizes - and times, against the whole-set copy this replaced: - -{{#include ../generated/access-index-bench.md}} -- **The access evaluator decides every request:** see - [Access directives](#access-directives) below. -- **The default definition:** every boot stores the archetype - `openEHR-EHR-EHR_ACCESS.access_directives.v1.0.0` when no definition of its - id is stored, and never over a stored one. It constrains the settings to - `ACCESS_DIRECTIVE_SETTINGS` and its attributes; the definition upload - validates an archetype that names a class of the draft access control - package against the RM extended by that package. FerroEHR reads the - settings by their codes, never by this id, so a deployment may use its own. - -The scheme is a FerroEHR extension: openEHR mandates the `EHR_ACCESS` object -and its change control but publishes no concrete access-control scheme. The -decision also holds for AQL, ad-hoc and stored queries alike: data the caller -may not read contribute no rows, whether the query names the EHR in its -`WHERE` clause, in an `EHR` predicate, through the `ehr_id` parameter, or not -at all, as in a population query, and `COUNT`, `LIMIT` and `OFFSET` count only -the rows the caller reads. - -### Access directives - -The access evaluator decides every request that reaches an EHR. Its steps, -refusal codes and answers are on [How FerroEHR decides -access](explanation/access-model.md#how-one-request-is-decided); the rules -below say when each step applies. - -- **Who is bound.** The record's person skips every step on their own EHR - (EHDS Art. 3), so no controller rule limits a patient's own access, and is - refused at step 0 on any other. A caller bound to the person reads their own - record as the person, unless it performs a professional `ROLE`: then its - read is a professional's, refused at step 5 as a conflict of interest, and - the staff member reads their own record under their own login. A - representative reaches only the EHR of the subject it represents, refused - at step 0 on any other, and is held there to steps 1 to 3 and 5 and skips - the others (Art. 4(2)): a controller rule can keep, say, a minor's confidential - data from a parent. - An access service is a caller holding an `access_service` grant or a - verified caller of a `federation` issuer. -- **When a directive applies.** Every attribute an `applies_to` entry sets - must hold for the caller: the party (its own `PERSON` or `AGENT`, a care - team it is a member of, the provider its client acts for, or a `GROUP` - that provider is a member of), a role it performs (the coded `name` of a - `ROLE` in force it performs, compared by terminology and code; a token's - role claims never count), the `care` relationship (a live care relationship), the - `representative` and `proxy` relationships, or its caller kind. Its - `operations` (`read`, `write`, `export`, `query`), `purposes` and - `time_validity` must hold too, and its `data` scopes say which data it - covers: objects, templates, root archetypes, categories (through the - [category map](audit.md)), sensitivities, origins and commit time. One - level of `exceptions` of the opposite effect narrows it. -- **A fact that cannot be read never opens data.** A `time_validity` bound - with no offset, or a commit with no recorded origin, is read as covered by - a deny and not by a permit, and so is a purpose the request does not - declare, against a directive of the person. -- **A purpose is declared.** The caller states the purpose, and the access - policy's `purpose_required` refuses a request without one at step 4. A - controller rule's `purposes` therefore match only a purpose the request - declares: "no medical examination" refuses that purpose and nothing else, - and a request with no purpose under a policy that does not require one is - not refused by a purpose rule. -- **Emergencies.** An emergency is a - [justification](#justified-access-outside-the-care-relationships) of the - access policy whose `emergency` is set. A caller it names that declares - its purpose and states a reason reads data a restriction, a consent deny, - an exclusion or a deny rule covers where its `emergency_override` holds, - and passes steps 6 to 8 (Art. 11(5)); an access service that may override - an opt-out reads an opted-out EHR the same way, unless it acts for the - person (Art. 10(2)). A directive whose `emergency_override` is false binds - in every emergency, as an absolute opt-out of the Member State's law does - (recital 55). Each such access is recorded as an emergency with its - reason. -- **Writes.** A write is judged by steps 1 and 2 for the EHR as a whole and - by steps 3 to 8 for the version it commits: its template, root archetype, - origins and the sensitivities the policy's classifications give it. A - restriction and an opt-out restrict who sees data, not its recording - (EHDS Art. 8): no write is refused for its content by either, so care is - always documented and a write never reveals one, and the data written stay - restricted for reading. Where the answer depends on the - datum, the first step that refuses that datum answers, for a named object - as for a written version, before any step about the EHR alone. -- **Every decision is a copy.** The settings, the caller facts and the access - policy are held on each replica and dropped on the notification of the - commit that changes them, so a decision adds no database transaction. A - named object is read for its template, archetype, origins and commit time - only when a directive, label or classification of the EHR depends on them. -- **Refusals.** A `403` names its code in `detail`, and with - `Prefer: return=representation` in the `refusal` member, with the - `legal_grounds` of the controller rules that refused at step 5 - ([problem types](using-the-api/problems.md#forbidden)). Steps 1 and 2 say - nothing. - -The decision procedure, its order and its codes are FerroEHR's own design: -RM EHR IM §EHR Access requires every decision to follow `EHR_ACCESS`, and -publishes no procedure. - -### Care relationships - -Where the [access policy](#the-access-policy) sets -`care_relationship_required`, a professional reads a patient's clinical data -only while a care relationship to the patient is live: the professional's -`PERSON` is a member of a care team or unit the patient's `PERSON` is under -the care of, and the admission has begun and has not ended more than the -policy's `relationship_grace` ago. Otherwise step 7 refuses with -`403 refused-no-care-relationship`. openEHR leaves it to the care delivery -environment to say who cares for whom (BASE Architecture Overview, §The -Problem of Roles), so your ADT system writes admissions and team rosters -under the `write_care_relationship` grant, or your identity provider -provisions care teams as SCIM Groups. An admission, a transfer, a discharge -or a membership change decides the next request on every replica. - -A query that names no EHR reads care from the care projection, which a -replica uses only while it reflects the care facts the replica holds, so a -discharge or a removed membership never admits from a stale row -([The care projection](installation/config-privacy.md#the-care-projection)). -How the relationships are modelled is on -[Caller facts: roles and care relationships](operational-policy.md#caller-facts-roles-and-care-relationships). - -### Sensitivity - -Data carries a sensitivity from two places: a label on a single object in -the person's `EHR_ACCESS` settings, and a classification in the access -policy that gives every object it covers (by template, root archetype, -category or origin) its sensitivities. Sensitivity codes are those of your -jurisdiction's terminology, such as HL7 `HL7_Confidentiality` and -`HL7_ActCode`. Step 6 refuses data with a sensitivity that no applying permit -names, with `403 refused-sensitivity`. Two permits clear a caller: a consent -permit of the person whose `data` names the sensitivity, and a permit rule -of the access policy, such as one that clears the psychiatrist role for -`PSY`. No capability or token claim clears a caller. - -### Record confidentiality - -The controller can protect a whole record, for example of a public figure, -a staff member or a person under protection, by setting a confidentiality -marking in the record's `EHR_ACCESS` settings: the `marking` of -`ACCESS_DIRECTIVE_SETTINGS`, a `CONFIDENTIALITY_MARKING` with the level, who -set it, when and why. The level is a code of HL7 `HL7_Confidentiality`: `N` -normal (the same as no marking), `R` restricted or `V` very restricted -(`U`, `L` and `M` read as `N`). A label on one object can carry a marking -too, and a classification of the access policy a `confidentiality`; the -confidentiality of a datum is the highest of the three. - -- **Who sets it.** Only the controller, through `POST /admin/ehr-access` - (or a CONTRIBUTION by a holder of the administrator role). A version a - patient or another gate-keeper commits must carry the current marking - unchanged; one that sets, changes or clears it is refused `403` whole. -- **Who reads the record.** Step 6 refuses data above `N` that no applying - permit clears. A permit clears a datum when one of its `data` scopes - names, in `confidentialities`, the datum's level or a higher one, so a - permit for `V` also clears `R`. With no rule that names a level, a marked - record is read by its subject alone. A typical policy permits `R` to - callers with a care relationship (`applies_to` with `relationship` `care`) - for a treatment purpose, and `V` to a named role. The patient still reads - their own record, and an emergency justification invoked with a reason - lifts the step, recorded in the access log. -- **What a refused caller sees.** A named read answers `403 - refused-confidentiality`, which names neither the level nor the reason, so - `R` and `V` answer alike. A level listed in the access policy's - `concealed_confidentialities` answers `404`, as an unknown record. A - query, an export and `GET /ehr?subject_id=` always leave a refused record - out, inside the query's one SQL statement, so `COUNT`, `LIMIT` and paging - agree. -- **Who reads the marking.** The subject and the controller read the - `EHR_ACCESS` settings whole. A representative, and any other gate-keeper - who is not the subject, reads them without `marking`, since the marking - itself says the record is protected. That holds on every route that - serves the settings: `GET /ehr/{ehr_id}/ehr_access` and the - `versioned_ehr_access` reads, a CONTRIBUTION read with `Prefer: - resolve_refs`, an EHR Extract (unless the caller holds an - `export_ehr_extract` grant, whose extract moves the marking with the - record) and AQL, where a whole `EHR_ACCESS` or its `settings` comes - without the marking (no path below `settings` resolves in AQL, for any - reader, so no query filters on the marking). A version served this way no - longer holds the data its `signature` signs, so it carries no `signature`, - and the REST response says so in the header `Redacted: marking`, a header - of this CDR's own design (no openEHR or HTTP specification defines one). -- **The access log.** Every access to a marked record carries the level as - the entry's security label (the BALP `entity.securityLabel` in the - `v3-Confidentiality` system), a refusal names the marking's level in its - description, and the controller's commit that sets or clears a marking is - an entry naming the level it set or cleared. - -### The access policy - -The controller's access policy is one versioned `ACCESS_POLICY` that holds -for every EHR this FerroEHR keeps: the classifications above, whether access -needs a declared purpose (step 4) and a care relationship (step 7), the -controller's rules (step 5, EHDS Art. 11(3)), the catalogue of named -directives a person accepts by reference, and the restrictions of the -access log's subject view. An administrator holding the -`write_access_policy` grant writes it over the admin API, and it decides the -next request on every replica. Its `justifications` say who may open a -record outside their care relationships, and in an emergency -([below](#justified-access-outside-the-care-relationships)). The trust and -the floor stay in `ferroehr.toml`: `authz.rbac.admin_role` and -`ehr_access_default`. The policy can only tighten them. Until you write one, -nothing is tightened and nobody is admitted on a justification. The model and -the rules are on [The access policy](operational-policy.md#the-access-policy). - -### Justified access outside the care relationships - -A clinician sometimes needs a record outside their caseload: a consultation, -a second opinion, a colleague's patient on a shift, or an emergency. Your -EHR lets them open it when your access policy allows it for the purpose they -declare, asks them why, and FerroEHR keeps the reason in the access record -the patient reads (EHDS Art. 9 and Annex II 3.2, Art. 11(5)). The -justification, the header and the bound of the reason are this CDR's own -design; the purposes are HL7 v3 `ActReason` codes, and the reason travels -on as the text of the purpose of use (FHIR R4 `AuditEvent.purposeOfEvent` -and `agent.purposeOfUse`, IHE BALP). - -- **The policy.** Each entry of `ACCESS_POLICY.justifications` names the - `purposes` that invoke it, the callers that may (`applies_to`, actor - scopes as in a rule: a role they perform, a party, a caller kind; void - means every professional), and whether it is an `emergency`. Without - `justifications` nobody is admitted on one. -- **The request.** The clinician declares the purpose in `x-purpose-of-use` - and the reason in `x-access-reason` (`[audit] reason_header`): their own - words, percent-encoded UTF-8 (RFC 3986 §2.1) so any language travels in an - HTTP header, 1 to 1000 characters after decoding, with no control - character. A malformed or longer value is a `400` naming the header, and - nothing is recorded in part. -- **The decision.** The first justification whose purposes hold the - declared purpose and whose `applies_to` names the caller is invoked. It - stands in for a live care relationship at steps 7 and 8 for the data no - relationship of the caller covers: with a reason they are admitted, and - without one they are refused `403 refused-reason-missing`, which tells - your EHR to ask the clinician why. Inside the caller's care relationships - no reason is asked. An emergency justification lifts each - `emergency_override` and steps 6 to 8, and needs the reason before any - directive is read, so its refusal never reveals a restriction. -- **What it never lifts.** A justification that is no emergency lifts no - restriction, opt-out, consent deny, exclusion, controller rule, - sensitivity, confidentiality or conflict. The patient's restriction still - refuses (EHDS Art. 8), and a GDPR Art. 18 restriction of processing refuses - every access, an emergency included. -- **The record.** The access record stores the purpose and the reason - (`audit_event.justification`), the access-log entry names the - justification with its `reason` (`justification`, or `emergency`), and the - patient's own ITI-81 retrieval shows who looked, why and that it rested on - a justification ([Audit](audit.md#justified-and-emergency-access)). - -```mermaid -sequenceDiagram - participant C as Clinician (EHR app) - participant F as FerroEHR - participant E as Access evaluator - participant L as Access record - participant P as Patient portal - C->>F: GET composition, x-purpose-of-use TREAT - F->>E: decide (no care relationship) - E-->>F: refused-reason-missing - F-->>C: 403 refused-reason-missing - C->>F: GET composition, x-purpose-of-use TREAT, x-access-reason - F->>E: decide (justification 1 invoked, reason stated) - E-->>F: admitted on the justification - F->>L: purpose TREAT, justification and reason - F-->>C: 200 composition - P->>F: GET AuditEvent?patient=... - F-->>P: purposeOfEvent TREAT, text = the reason -``` - -A policy that admits consultations under `TREAT` and emergencies under -`ETREAT` to every professional, and break the glass only to the emergency -physicians: - -```json -"justifications": [ - { "_type": "ACCESS_JUSTIFICATION", "emergency": false, - "purposes": [{ "_type": "DV_CODED_TEXT", "value": "treatment", - "defining_code": { "terminology_id": { "value": "HL7_ActReason" }, "code_string": "TREAT" } }] }, - { "_type": "ACCESS_JUSTIFICATION", "emergency": true, - "purposes": [{ "_type": "DV_CODED_TEXT", "value": "break the glass", - "defining_code": { "terminology_id": { "value": "HL7_ActReason" }, "code_string": "BTG" } }], - "applies_to": [{ "_type": "ACCESS_ACTOR_SCOPE", - "role": { "_type": "DV_CODED_TEXT", "value": "emergency physician", - "defining_code": { "terminology_id": { "value": "urn:example:roles" }, "code_string": "EP" } } }] } -] -``` - -Each purpose must also be on `[audit] purpose_codes` when that list is set, -since a purpose the audit layer does not record is no declared purpose. - -### Restriction of access by health professionals (EHDS Art. 8) - -Regulation (EU) 2025/327 Art. 8 gives a person the right to restrict the -access of health professionals and healthcare providers to all or parts of -their data, and has the fact of the restriction stay invisible to healthcare -providers. Art. 11(5) lets the restricted data be reached where necessary to -protect the person's vital interests, logged so the person can see it. No -openEHR specification governs this; it is our own design. - -- **Recording it.** A restriction is a `restriction` deny directive of the - EHR's own `EHR_ACCESS` settings (the `access_directives` scheme above). The - controller records it on the person's instruction by committing a new - `EHR_ACCESS` version with `POST /ferroehr/rest/extensions/v1/admin/ehr-access`, - for the whole EHR (no `data`) or for the versioned objects its - `data[].objects` name, and lifts it by committing a version without it - ([the routes](operations-admin-apis.md#legal-marks-restriction-objection-and-retention)). - `GET /ferroehr/rest/extensions/v1/admin/ehr-access` reads every version, so a - lifted restriction stays in the history, and an EHR Extract carries the - versions. A whole-EHR restriction covers data recorded after it too. -- **What the server reads of it.** The access evaluator reads every - attribute of the directive for each caller ([Access directives](#access-directives)): - its `data` scope, `applies_to`, `operations`, `purposes`, `time_validity` - and `exceptions`. The event stream, which has no caller, withholds every - object a restriction in force covers, and the whole EHR for a `data` scope - beyond `objects`. -- **What a professional sees.** Restricted data reads as absent: a restricted - composition or EHR answers **404** exactly as an unknown one does, a query - leaves it out at every scope (and a query scoped to a restricted EHR answers - as for an unknown EHR), an export skips it, a CONTRIBUTION lists none of its - versions, the event stream withholds it, and a write to it is refused as a - write to an unknown target. No status, header or count says that a - restriction exists. -- **What it does not change.** Nothing is deleted, and storage and the - controller's own processing go on: the admin routes (dump, archive, erase, - the registers) see everything. It is not the GDPR Art. 18 restriction of - processing, which answers **403** and stops processing itself. -- **The emergency override.** A caller an emergency - [justification](#justified-access-outside-the-care-relationships) of the - access policy names, declaring its purpose and stating a reason, reads the - restricted data where the directive's `emergency_override` holds, and its - access record names the emergency with the reason - ([Audit](audit.md#justified-and-emergency-access)). Without the reason, or - without a justification that names the caller, nothing is lifted. - -The grain is the versioned object, the whole EHR, or both. A finer grain (one -entry inside a composition) is not built: an object is the unit the version -reads, the queries and the exports already decide on, and splitting a -composition would change what the stored, signed version holds. - -### Opt-out from the access services (EHDS Art. 10) - -Regulation (EU) 2025/327 Art. 10(1) lets a Member State's law give a person -"the right to opt out from the access to their personal electronic health data -registered in an EHR system through the electronic health data access services -referred to in Articles 4 and 12", and has the Member State "ensure that the -exercise of that right is reversible". Art. 10(2) lets the Member State admit -"a healthcare provider or health professional" where processing "is necessary -in order to protect the vital interests of the data subject or of another -natural person", even after an opt-out. No openEHR specification governs this; -it is our own design. - -FerroEHR ships the software part: a mark on the whole EHR that the callers you -grant as the access services read as absent. Whether the right exists, how -the person exercises it, and the rules and safeguards of Art. 10(2) are your -Member State's law and yours to apply. Where the Member State enforces the -opt-out in its own services, leave the mark unused. - -- **Granting the access services.** Your Art. 4 access service (the - person's) and your Art. 12 health professional access service each hold an - `access_service` grant in the CDR: a capability of a `ROLE` their `ACTOR` - or `PERSON` performs ([Operational policy](operational-policy.md#what-the-grants-decide)). - `[authz.grants] allowed` does not allow `access_service` by default, so the - opt-out holds for nobody, and recording one is refused with **400**. A role - a token names grants nothing here. -- **Recording and reversing it.** An opt-out is an `opt_out` deny directive - of the EHR's own `EHR_ACCESS` settings, at most one, covering the whole EHR. - The controller records it on the person's instruction by committing a new - `EHR_ACCESS` version with `POST /ferroehr/rest/extensions/v1/admin/ehr-access`, - and reverses it by committing a version without it - ([the routes](operations-admin-apis.md#legal-marks-restriction-objection-and-retention)). - The reversed opt-out stays readable as a past version, and a version - without one is accepted whatever the configuration, so an opt-out can - always be reversed. Its `emergency_override` false makes it absolute: no - vital-interest override lifts it (EHDS recital 55). -- **What an access service sees.** A request from a caller holding an - `access_service` grant reads the EHR as absent: a route that names the EHR or an - object in it answers **404** as for an unknown EHR, a population query leaves - its data out, a query scoped to it answers as for an unknown EHR, an export - and the lookup by subject find no such EHR, and a write to it is refused as a - write to an unknown EHR. -- **What it does not change.** Every other caller reads the record as before: - your own care, through callers that hold no `access_service` grant, and the - controller's admin routes. Nothing is deleted. It is not the Art. 8 - restriction above, which reaches every professional route and leaves the - person's own access open. -- **The vital-interest override.** An access-service caller an emergency - [justification](#justified-access-outside-the-care-relationships) names - (an `applies_to` of caller kind `access_service`), declaring its purpose - and stating a reason, reads the EHR where the opt-out's - `emergency_override` holds, unless it acts for the - person (a SMART `patient/` grant or the patient claim), because Art. 10(2) - names a healthcare provider or health professional. Its access record - names the emergency with the reason - ([Audit](audit.md#justified-and-emergency-access)), and a - route that names the opted-out EHR, in its path or in a `POST - /message/export` manifest, adds an access record - `access-opt-out-override:ehr-wide` against it. -- **The record.** Each commit and each read through the controller's route - is an access record on the EHR (`ehr-access:ehr-wide`) naming the - administrator. - -```toml -[authz.grants] -allowed = ["commit_composition", "access_service"] - -[audit] -purpose_codes = ["TREAT", "ETREAT"] -``` - -### Information a person inserts (EHDS Art. 5) - -Regulation (EU) 2025/327 Art. 5 lets a person, or their representative, insert -information in their own EHR through the access services. That information -"shall be clearly distinguishable as having been inserted by the natural -person or by his or her representative", and the person "shall not be able to -directly alter the electronic health data and related information inserted by -health professionals". FerroEHR keeps both rules at the commit. No openEHR -specification governs who may change what, so the rules are our own design; -the marker is the RM's own. - -- **Who counts as the person.** A caller the party binding binds to the - `PERSON` an EHR's subject names, with no professional `ROLE`. A patient - claim or a `patient/` scope in the token does not make a caller the person, - because a professional's token in a patient's context carries both (SMART - on openEHR master08 §Resource Scopes). -- **Who counts as the representative.** A person bound to their own `PERSON` - who acts for the patient through a representation relationship FerroEHR has - recorded ([how a login is looked up](installation/config-auth.md#how-a-login-is-looked-up)), - ([Representatives](operational-policy.md#representatives)). - The rules below hold for the representative exactly as for the person. -- **The marker.** Every version and CONTRIBUTION the person commits records - `PARTY_SELF` with no `external_ref` as `AUDIT_DETAILS.committer`, the RM's - way to say the committer is the record subject (RM common, Audit Details). - A representative's records `PARTY_RELATED`, naming the representative's own - `PERSON` and the coded relationship. FerroEHR writes this committer itself - and refuses one the request states that differs, in the - `openehr-audit-details` header or in a CONTRIBUTION body. Every read of the version carries it, an AQL query reads it with - `v/commit_audit/committer`, the contribution list extension flags the change - set with `inserted_by_person`, and the viewer names the committer "The person - or their representative". The marker is part of the stored version, so a - dump and its restore keep it. -- **The composer.** A COMPOSITION the person or the representative commits - names the person (`PARTY_SELF`) or their representative (`PARTY_RELATED`) - as its composer. - Any other composer is refused with **403**, so the person cannot present what - they insert as a professional's. -- **What the person may change.** The person and their representative may - update and delete a version whose committer is `PARTY_SELF` or - `PARTY_RELATED`. An update or a deletion of a version anyone else committed, - a professional or a system, is refused with **403** and a body that names - EHDS Art. 5, whether it comes as a direct write or inside a CONTRIBUTION. - Nothing is written. The marker is in the version, so the rule holds whatever - became of the access record of the write. -- **What a professional may change.** A professional's writes are unchanged. - A professional may update or delete an entry the person inserted; the new - version is the professional's, which the person may then no longer alter. - The person's own versions stay in the version history. - -### Delayed access by the person (EHDS Art. 3(3)) - -Regulation (EU) 2025/327 Art. 3(1) gives a person access to their data -"immediately after the personal electronic health data have been registered in -an EHR system". Art. 3(3) lets a Member State restrict that right "by delaying -access to their personal electronic health data for a limited period of time -until a health professional is able to properly communicate and explain to the -natural persons concerned information that can have a significant impact on -their health". Recital 10 gives the example: a diagnosis of an incurable -disease should come first in a consultation, not through an electronic -channel. This is the opposite direction of the Art. 8 restriction above: the -data is withheld from the person, never from a professional. No openEHR -specification governs it; it is our own design. - -FerroEHR ships the software part. Whether the delay applies, to which data and -for how long is the Member State's rule, and you configure it in -[the access-delay register](installation/config-auth.md#the-access-delay-register), an -[admin register](operational-policy.md#the-admin-registers). It is off by -default, so the person's access stays immediate. - -- **What is held.** With the register on, every new COMPOSITION whose category - (the [audit category register](installation/config-audit.md#the-audit-category-register), template first, - then the root archetype) is listed in the register's `categories` is held from - the moment it is committed, for the register's `max_delay`. Only the first version - is held: a composition the person has already seen stays visible when it is - amended, and a professional holds an amendment by hand if it needs - explaining. A composition the person commits is never held from them. -- **Who it is held from.** A request that may be the person's own: a bearer - token the party binding binds as the person or a representative. Such a - token is treated as the - person's, whatever `user/` or `system/` grant it also carries, so a mixed - token is withheld from rather than shown the data too early. The rule is the - FerroHEALTH family's, shared with the other products through - `ferrohealth-smart`. To that request a held composition reads - as absent: a read answers **404** as for an unknown composition, a query and - an export leave it out, a CONTRIBUTION lists none of its versions, and a write - to it is refused as a write to an unknown target. -- **On a professional's own record.** The person an EHR belongs to is read - from the party binding: a caller whose identity is bound to the `PERSON` - the EHR's `EHR_STATUS.subject` names is that record's person, whatever - roles it holds. On that EHR the hold applies to them as above, in a read, - a query pinned to the EHR, a query across the population and an export, - and their own write to it is never held. A bound person holding no role - reaches only their own records, so the hold applies on every one. -- **What a professional sees.** Everything else, as before. The hold changes - no professional route, query or export on another person's record. -- **Releasing it.** The treating professional releases a composition once it - has been explained, from the clinical surface with - `POST /ferroehr/rest/extensions/v1/ehr/{ehr_id}/versioned_composition/{versioned_object_uid}/access-delay/release`. - The route takes the checks of a write to that EHR: its `EHR_ACCESS` gate and - the SMART `composition-` update grant. A request that may be the person's is refused with **403**. The - controller releases with - `POST /ferroehr/rest/extensions/v1/admin/access-delay/release`, and holds - one by hand with `POST /ferroehr/rest/extensions/v1/admin/access-delay`, for - at most the access-delay register's `max_delay` - ([the routes](operations-admin-apis.md#legal-marks-restriction-objection-and-retention)). -- **The limit.** Every hold ends by itself when its period passes, released or - not, because Art. 3(3) allows a delay "for a limited period of time" only. -- **The record.** Placing a hold, releasing it and its expiry are each an - access record: the release names the professional who made it, and the - server writes the expiry record within a minute of the limit passing. -- **The person's access trail (Art. 9).** A record about a held composition - would tell the person a result exists. The subject-scoped ITI-81 read, the - one an app serves the person's own trail from, leaves out every - record that names a held composition, its hold included, until the hold is - released or expires; the records then appear unchanged, with their original - times. The filter is `ehds-logging`'s, the FerroHEALTH family's EHDS - logging component. The controller's unscoped read shows every record at - all times. - -Turning the section off makes every held composition readable to the person at -once: the holds stay in the register, and no new one can be placed. - -### RBAC (role-based, coarse) - -Every openEHR operation is classified as **Public**, **Clinical**, or -**Admin**, and a role model gates each class. Roles are plain, -case-insensitive strings. A Clinical operation needs an authenticated caller -and no role; the configured roles default to `ADMIN` (`admin_role`, every -Admin operation) and `READONLY` (`readonly_role`, refused on every write). - -| Environment variable | Default | Meaning | -|---|---|---| -| `FERROEHR__AUTHZ__RBAC__ENABLED` | `true` | the coarse role gate (active only when auth is enabled) | -| `FERROEHR__AUTHZ__RBAC__ADMIN_ROLE` | `ADMIN` | role required for admin operations | -| `FERROEHR__AUTHZ__RBAC__READONLY_ROLE` | `READONLY` | role marking a principal read-only: refused on every write | -| `FERROEHR__AUTH__ISSUER____ROLE_CLAIMS` | `["roles","groups","entitlements"]` | JWT claim paths mined for roles, per issuer; a Keycloak issuer adds `realm_access.roles` | -| `FERROEHR__AUTHZ__RBAC__ROLE_ISSUERS` | empty | the names of the issuers whose role claims may grant the administrator role; a token of any other issuer never holds it | - -Roles come from the JWT claims listed in `ROLE_CLAIMS`, or from a Basic user's -configured roles. The defaults are the carriers -[RFC 9068 §2.2.3.1](https://www.rfc-editor.org/rfc/rfc9068#section-2.2.3.1) names -for conveying authorization state (`roles`, `groups`, `entitlements`, of which -`roles` and `entitlements` are [SCIM](https://www.rfc-editor.org/rfc/rfc7643#section-4.1.2) -attributes), the default every FerroHEALTH product shares. A claim path may be -dotted, so an issuer that nests them differently, such as Keycloak's -`realm_access.roles`, is configuration rather than a code change; a claim -carrying a single string and one carrying an array are both accepted. - -**A Clinical operation needs at least one role of any name; an Admin operation -needs the admin role.** A Basic user holds the roles its `roles` list names -and nothing else, so a user with none is refused every Clinical operation; -`roles = ["USER"]` satisfies the Clinical class and no Admin operation. A -bearer token whose SMART on openEHR resource scopes are all `system/` scopes, -such as `system/template-*.r`, is a backend client and needs no role for a -Clinical operation: its scopes decide what it reaches. The record's person and -their representative need no role either: a caller the party binding binds -to the `PERSON` they are, and a -caller acting for the person pass the Clinical class, and the access -evaluator decides from who they are (EHDS Art. 3 and 4(2)), confining them -to their own records. A token's own reading of the patient never counts -without that binding. The read-only role still refuses their writes. -Any other `user/` or `patient/` token belongs to a professional and still needs -a role. The former `user_role` key is refused at boot. -Disabling RBAC restores authentication-only behaviour. - -> [!IMPORTANT] -> **The management surface is not configured here.** `/management/*` is governed -> entirely by `[management.endpoints]`, one level per endpoint, and nothing under -> `[authz.rbac]` changes it. There is **no global default beside it: an endpoint -> you do not name is `off`** and is not mounted at all. -> -> Each level means: `off`, not mounted, answers `404`; `private`, any -> authenticated principal; `admin_only`, authenticated **and** holding -> `authz.rbac.admin_role` (the one place RBAC is consulted); `public`, no check -> at all, including no authentication. -> -> The consequence worth internalising: `prometheus = "public"` is reachable by -> an anonymous caller **whatever** your RBAC settings say, because a `public` -> endpoint is mounted outside the authentication layer. Lock the surface down by -> raising the levels in `[management]`, and read the effective set back from -> `/management/env` (or from the boot log line that names every mounted -> endpoint and its level) rather than assuming. - -> [!IMPORTANT] -> **The OAuth2 `scope` claim does not grant roles.** A scope grants a *client* -> delegated authority ([RFC 6749 §3.3](https://www.rfc-editor.org/rfc/rfc6749#section-3.3)); -> it asserts nothing about the subject's roles. Reading it as one also made the -> at-least-one-role check pass for every OIDC token, since `openid` alone -> satisfied it. If your callers rely on a scope naming a role, move that role -> into one of the role claims above. Scopes remain on the principal and still -> drive SMART scope enforcement. - -> [!NOTE] -> The downloadable Compose quickstart deliberately runs with RBAC **off** and a -> single user, so every surface works out of the box (see -> [Docker Compose](installation/compose.md)). Turn the role gate on with -> `[authz.rbac] enabled = true` (or `FERROEHR__AUTHZ__RBAC__ENABLED=true`) and -> give each principal an explicit `roles` list. - -A principal carrying the `readonly_role` (default `READONLY`) is refused on -every write operation (creating an EHR, committing a composition, uploading a -template, and any update/delete) even when it also holds granting roles such -as `ADMIN` (a restriction always overrides a grant). Reads and AQL queries stay -permitted, so a `READONLY` account is an authenticated, view-only principal. The -repository's from-source development stack ships one such account -(`ferroehr-readonly`, password `ferroehr`) alongside `ferroehr` and -`ferroehr-admin`, with RBAC at its default `enabled = true`, so the separation -can be tried out; the downloadable quickstart file has neither (one user, no -role gate). - -### A patient's own EHR - -A caller is the patient, the `subject` caller kind of the -[access evaluator](#access-directives), through a SMART App Launch -patient-context credential: a bearer token whose `patient/` grants name the -launch EHR in `ehrId` (master07 §Context Selection). -The patient's own EHR is the `ehrId` of that token's launch context -(ITS-REST SMART App Launch §Context Selection). The evaluator skips every step -of the decision procedure for the patient on their own EHR (EHDS Art. 3) and -refuses them every other EHR with **`403`** `refused-not-subject`, which the -access record names as step 0 (subject). No key -turns this on or off, and a representative comes in as a delegation of the -subject's directives. - -- An operation on another patient's EHR is refused with **`403`**, whether the - EHR is named in the path, the body or only in the result. That covers the - EHR, `EHR_STATUS`, COMPOSITION, CONTRIBUTION and DIRECTORY operations and - their item tags, and the EHR Extract import and export routes; an export by - manifest (`POST /message/export`) holds every EHR it names, and one EHR of - another patient refuses the whole export. -- An AQL query reads only the rows of the patient's own EHR, whatever the query - scopes or projects, including a query that reads only the `ehr` row, and its - counts and pages see only those rows. -- A patient-context token whose launch context names no EHR reaches none, and - an operation on EHR data that names no EHR (creating an EHR, a lookup by - subject, a query with no single-EHR scope, an import naming no EHR) is - refused the same way. - -The evaluator holds the launch context alone. The SMART layer checks a -`patient/` grant's resource family and permission and refuses on nothing -else, so every route answers a caller on another EHR the same way and the -access record names step 0. A professional whose grants are `patient/` grants -alone, a clinician app launched for one patient, is held to that patient's -EHR the same way, and on that EHR takes every step of the procedure. A contact -point's caller is held to the EHR of its treatment relationship -confirmation's patient. The `[auth] patient_claim` and -`[auth] patient_namespace` keys of earlier releases are gone; a configuration -that sets either is refused as naming unknown keys. +Who may do what is decided by the per-EHR access evaluator, the coarse role +gate and, when enabled, the SMART scopes. How the parts fit is on [How FerroEHR +decides access](explanation/access-model.md), and each layer in detail is on +[Access control in detail](access-control.md). ## Response security headers @@ -1251,158 +426,10 @@ admission time inside a Kubernetes cluster is covered separately, in ## The pseudonymisation boundary -The pseudonymisation boundary separates *a record from the person it is -about*, and it is enforced by PostgreSQL grants rather than by the server's own -routing: code that reaches for the wrong schema is a bug that can -be fixed, while a database role able to read two domains defeats the -separation however correct the code is. - -GDPR [Art. 4(5)](https://eur-lex.europa.eu/eli/reg/2016/679/oj) defines -pseudonymisation as processing where attributing data to a person requires -additional information "kept separately and subject to technical and -organisational measures", and Art. 32(1)(a) names it a security measure for -health data. EDPB Guidelines 01/2025 require that separation to hold against -internal actors, operators with database access included. - -Two domains hold the two parts, each behind its own role: - -```mermaid -flowchart LR - server["FerroEHR server"] - server -->|ferroehr_clinical| ehr[("clinical
versions and nodes,
keyed by an opaque subject pseudonym")] - server -->|ferroehr_party| demo[("party
parties, with no
national identifier")] - server -->|audit writer| audit[("audit
ATNA record repository")] - ehr -. barred .- demo -``` - -Read one domain and you hold a clinical record whose subject is an opaque -identifier, or a set of people with no records attached. Only the two together -re-identify anything, and no credential the server uses holds both. The -migrations create the roles, grant each its own schema, and **revoke every -other domain explicitly, in both directions**; each role is `NOINHERIT` and a -member of no other, so a grant cannot arrive through a membership. - -The boundary is checked at startup, not assumed: the server reads the -catalogue for every table, view, sequence and function each role can reach in -a domain it does not own, and **refuses to serve** if it finds one, naming the -role and the object. A misconfigured grant is a failed boot, not a silent -weakening. - -Two limits are worth stating plainly. The clinical schema holds a *pseudonym* -only when `[privacy] subject_namespaces` declares the namespaces a subject -reference may draw from — left unset, whatever a client sends is what gets -stored, and no schema split saves you from a national identifier written into -the clinical side; see -[Privacy and identifiers](installation/config-privacy.md). And the split is a -schema split by default: giving the demographic domain its own -`[database.party] url` is what turns it into a credential split, which is the -deployment step described in -[Operations](operations.md#database-roles-and-least-privilege). - -### Encryption at rest is a deployment requirement - -FerroEHR encrypts no field before it reaches PostgreSQL. A national identifier -belongs in the master patient index, never in the CDR, which knows the subject -only as a pseudonym -([Privacy & data minimisation](installation/config-privacy.md#national-identifiers-belong-in-the-master-patient-index)), -so the server holds no identifier to seal. What it does hold, every party and -every clinical record, sits in the database as written. GDPR Art. 32(1)(a) -names encryption as a measure for that risk: encrypt every database volume, -replicas and WAL archives included, and every backup and dump at rest, with the -keys outside the database hosts. The -[go-live checklist](security/go-live-checklist.md#9-the-database-volumes-and-backups-are-encrypted-at-rest) -checks it before real data arrives. - -### Resolving across the boundary - -One question needs both domains at once: *which record belongs to this -person?* The server answers it in the application, over two connections, never -in the database. An EHR names its subject in its own -`EHR_STATUS.subject.external_ref`, which the `ehr` relation copies into its -subject columns on every EHR create and `EHR_STATUS` update. A cohort and the -AQL demographic join read the parties on the `party` connection and the EHRs whose subject names them on the `clinical` connection, -with a second search path and, when `[database.party] url` is set, a second -database role. FerroEHR matches, links and merges no patients, and holds no -national identifier: resolving a person to their pseudonym is the master -patient index's job. - -**No statement performs the join, because no credential could**: the -clinical role holds no grant in `party` and the party role holds none in -`clinical`, both revocations are explicit and in both directions, and the boot -check refuses to serve a database where either has been given one. The -crossing exists as an application step that can be audited, rather than as a -query anyone holding one password could write. - -Every crossing records an access event in the `linkage` domain, naming who -asked, the purpose of use they declared, and how many EHRs it reached. A miss -is recorded like a hit: it says someone asked whether this deployment holds a -record for that person. The event deliberately does **not** name the EHR that -came back. A record pairing a party with its EHR would make the audit trail a -map from parties to their EHRs, which the split exists to withhold. - -Looking an EHR up by subject (`GET /ehr?subject_id=…&subject_namespace=…`) -does **not** cross the boundary. That operation matches the EHR's own -`EHR_STATUS.subject.external_ref`, which is the opaque pseudonym the privacy -layer already constrains, so it resolves a pseudonym rather than an identity -and reads no party. It records a linkage-domain access event all the same, -naming the subject namespace and the EHR it found, because who resolved a -subject to a record is worth knowing wherever it happened. - -The lookup puts the subject identifier in the URL, because ITS-REST passes it -as a query parameter. FerroEHR keeps it out of everything it writes: the -request log and every trace span record the path and the matched route without -the query string, and the `404` for an unknown subject names only the -namespace. A reverse proxy or load balancer in front of FerroEHR sees the whole -URL, so configure it not to log query strings on this route, or not at all. -FerroPIX as the EHR index provider (IHE PIXm, planned in -[#3380](https://github.com/FerroHEALTH/FerroEHR/issues/3380)) resolves a -patient identifier to an EHR without putting it in a FerroEHR URL. - -### The subject link in the party domain - -The access evaluator needs the `PERSON` of an EHR's subject to read its care -relationships and its representatives. Under `record.subject_index = "pixm"` -the EHR names its subject by a pseudonym, so the patient's `PERSON` declares -it: an element of `PARTY.details` named by the `record_subject` code of -the draft openEHR access terminology `openehr_access`, -whose `DV_IDENTIFIER` holds the pseudonym and its namespace. An identifier -another organisation issued belongs in `details` (RM Demographic IM §2.1.3), -and the cross-reference stays out of the EHR (RM EHR IM §EHR Status). FerroEHR -projects it into the party table `binding_record_subject` at the commit of the -`PERSON`, and each replica holds the resolutions it uses in a bounded cache, -so a decision on a held subject adds no database transaction, a miss costs one -indexed read, and no decision calls the identity source. - -**This is an accepted trade-off** (owner decision, 2026-11-14, -[#5634](https://github.com/FerroHEALTH/FerroEHR/issues/5634)). Without the -element, mapping a pseudonym back to a person needs a steward action in the -identity source. With it, the party domain maps the pseudonym to the `PERSON` -for every patient whose `PERSON` carries the element. The clinical side is -unchanged: it holds the pseudonym alone, and `ferroehr_clinical` still reads -nothing in `party`. Re-identifying a clinical record still needs both domains, -so the condition of GDPR Art. 4(5), additional information kept separately, -holds inside the CDR, and the link sits in the party domain under its own role -and dump, the "identity cross-reference" BASE Architecture Overview §Anonymity -describes. Only the `PERSON`s that need care relationships or representation -need the element, so the exposure is per patient (Art. 25(2)). The evaluator's -resolution tells the caller nothing, so it writes no `linkage` access event; a -representative's EHR lookup records one per subject reference it resolves. - -### Declaring the posture - -The separations above are each a configuration key, and a deployment that has -made none of them is indistinguishable from one that has made all of them -until something goes wrong. The top-level `deployment.profile` key -([configuration](installation/configuration.md#deploymentprofile)) makes the -posture explicit: `production` refuses to start while a separation is missing -and not accepted by name, and reads the cluster each pool reached from -`pg_control_system()` rather than trusting the DSN text; `sandbox`, the -default, names every missing separation on the banner, in the boot log and on -`GET /management/status`, reports the profile on `GET /rest/status`, and must -not hold real patient data. The database keeps -its own line of defence for the subject pseudonym too: once -`privacy.subject_namespaces` is declared, a trigger on `ehr` refuses a subject -reference that is not a UUID, whichever code path or session writes it. +The clinical record and the parties it is about live in two domains, each +behind its own PostgreSQL role, and no credential the server uses reads both. The roles, the subject link and the +posture you declare are on [The pseudonymisation +boundary](pseudonymisation.md). ## One instance, one organisation @@ -1417,8 +444,8 @@ to the layer that hosts several systems, not inside one of them. So several organisations are served by several instances: one instance, one database, one set of domain roles each. That is a stronger boundary than a row -predicate — a defect in a query cannot cross it, because there is nothing to -cross — and it is what the §System Identity rule needs, since `system_id` +predicate: a defect in a query cannot cross it, because there is nothing to +cross, and it is what the §System Identity rule needs, since `system_id` "becomes embedded in the version identifiers of committed -- and possibly signed -- content" and "cannot easily be changed afterwards". One `system_id` shared across organisations mints version identifiers that cannot tell the diff --git a/website/book/src/security/committer.md b/website/book/src/security/committer.md index 931883462f..c197355934 100644 --- a/website/book/src/security/committer.md +++ b/website/book/src/security/committer.md @@ -4,9 +4,9 @@ Every version FerroEHR stores carries an `AUDIT_DETAILS`, and its `committer` is the "identity and optional reference into identity management service, of user who committed the item" (RM common, `AUDIT_DETAILS`). FerroEHR writes that committer itself, from the caller it authenticated and the demographic -party it bound the caller to. A client no longer says who committed. This +party it bound the caller to; a client does not say who committed. This page shows what the server writes for each kind of caller, what a client may -still send, the refusals, and how a professional's party gets the login +send, the refusals, and how a professional's party gets the login identifier the binding matches. @@ -30,7 +30,7 @@ identifier the binding matches. No openEHR specification governs how a login is matched to a party, when the match is made, or what happens when none matches. That is FerroEHR's own design, configured under -[`[authz.party_binding]`](../installation/config-auth.md#authzparty_binding). +[`[authz.party_binding]`](../installation/config-authz.md#authzparty_binding). ## The committer for each kind of caller @@ -162,7 +162,7 @@ governs who may name whom as composer. | An import of a version whose committer names a local party, from a system no `creating_system` element of the importer's import grant names | `403` | A login the binding cannot use is refused before any commit; the codes are -under [How a login is looked up](../installation/config-auth.md#how-a-login-is-looked-up). +under [How a login is looked up](../installation/config-authz.md#how-a-login-is-looked-up). ### The deviation from ITS-REST @@ -196,7 +196,7 @@ how the caller was bound: `binding` (`bound`, `provisional`, `external`, `organisation`, `system`, `self` or a `refused-*` code), the party, its groups, the provider, the actor chain of a delegated token and the client. The values and their renderings are under -[The binding outcome](../audit.md#the-binding-outcome). +[The binding outcome](../ehds-logging.md#the-binding-outcome). ## How a party gets its login identifier @@ -207,17 +207,17 @@ binds a professional only while it performs a live professional `ROLE`, and a representative only while it is the source of a recorded representation relationship. A `PERSON` that is neither binds a login as the person themself: no role, `PARTY_SELF` as the committer, and only the EHRs whose -subject is that `PERSON` (#6106). The identifier gets there in one of four ways: +subject is that `PERSON`. The identifier gets there in one of four ways: 1. **SCIM.** Your identity provider provisions the person through - [FerroEHR's SCIM 2.0 endpoint](../installation/config-auth.md#authscim) at + [FerroEHR's SCIM 2.0 endpoint](../installation/config-scim.md#authscim) at `/scim/v2/`, sending the key in `urn:ietf:params:scim:schemas:extension:ferrohealth:2.0:User:loginIdentifier`. FerroEHR creates the `PERSON` and its professional `ROLE` in one contribution. 2. **Just-in-time creation** at the first login, off until an administrator writes a `create_at_login` grant for the issuer in the CDR - ([Operational policy](../operational-policy.md#just-in-time-admission)). + ([Operational policy](../policy-examples.md#just-in-time-admission)). 3. **The demographic API**, under the administrator role. 4. **An existing `PERSON`** that already carries the identifier, adopted as [the migration](../installation/party-binding-migration.md) describes. diff --git a/website/book/src/security/dpia.md b/website/book/src/security/dpia.md index ffab02ae35..8e61371df8 100644 --- a/website/book/src/security/dpia.md +++ b/website/book/src/security/dpia.md @@ -197,7 +197,7 @@ authority. ## Next -- [Records of processing](records-of-processing.md) — the Art. 30 template. -- [Go-live checklist](go-live-checklist.md) — the checks to run before a +- [Records of processing](records-of-processing.md): the Art. 30 template. +- [Go-live checklist](go-live-checklist.md): the checks to run before a deployment holds real patient data. -- [Threat model](../threat-model.md) — the residual risk at each boundary. +- [Threat model](../threat-model.md): the residual risk at each boundary. diff --git a/website/book/src/security/go-live-checklist.md b/website/book/src/security/go-live-checklist.md index 26cf05786a..e4d7674dac 100644 --- a/website/book/src/security/go-live-checklist.md +++ b/website/book/src/security/go-live-checklist.md @@ -38,7 +38,7 @@ The server runs the same check at every boot and refuses to serve on a breach, so this is the early warning rather than the only one. The statements that create the roles, and what each one may reach afterwards, -are [Operations → Database roles](../operations.md#database-roles-and-least-privilege) +are [Operations → Database roles](../database-operations.md#database-roles-and-least-privilege) and [the threat model](../threat-model.md#what-each-database-credential-can-reach). > [!WARNING] @@ -196,7 +196,7 @@ floor and ceiling your law sets with its provision, such as the five Dutch years of the [Besluit vaststelling bewaartermijn logging](https://wetten.overheid.nl/BWBR0042391) or the German three-year ceiling of SGB V § 309 Abs. 1. Until you do, every entry is kept without end and the `log_retention` readiness indicator reads -`degraded`. The [audit trail page](../audit.md#retention-and-who-chooses-it) +`degraded`. The [audit trail page](../ehds-logging.md#retention-and-who-chooses-it) sets out the rules a policy write is refused under. Verify the seals work before you need it: diff --git a/website/book/src/security/records-of-processing.md b/website/book/src/security/records-of-processing.md index 4782362c48..2b950d52eb 100644 --- a/website/book/src/security/records-of-processing.md +++ b/website/book/src/security/records-of-processing.md @@ -124,7 +124,7 @@ The identity fields Art. 30(1)(a) asks for are yours in every case: | Art. 30 field | What the software does | |---|---| -| Purpose | Identifying the health professionals and the representatives who act on the record, so each version and each access names the natural person and the provider (EHDS Art. 13(4), Annex II 3.1 and 3.2), when [`[auth.scim]`](../installation/config-auth.md#authscim) or [just-in-time creation](../installation/config-auth.md#just-in-time-creation) is on | +| Purpose | Identifying the health professionals and the representatives who act on the record, so each version and each access names the natural person and the provider (EHDS Art. 13(4), Annex II 3.1 and 3.2), when [`[auth.scim]`](../installation/config-scim.md#authscim) or [just-in-time creation](../installation/config-authz.md#just-in-time-creation) is on | | Categories of data subject | The deployment's own professionals, its Basic users, and registered representatives | | Categories of personal data | Per professional: the binding key (the identity provider's immutable user id), the `userName`, the `externalId`, the name, the groups (care teams), the lifecycle state and the professional `ROLE`. Contact attributes only where the operator maps them; none are mapped by default. Just-in-time creation writes only the key, the `userName` and the name | | Source (Art. 14(2)(f)) | The identity provider: Microsoft Entra ID, Keycloak or another SCIM client, or the access token at the first login | @@ -157,9 +157,9 @@ the organisation: ## Next -- [Data protection impact assessment](dpia.md) — the technical description and +- [Data protection impact assessment](dpia.md): the technical description and the risk register. -- [Go-live checklist](go-live-checklist.md) — what to verify before real data +- [Go-live checklist](go-live-checklist.md): what to verify before real data arrives. -- [Shared responsibility](../compliance/shared-responsibility.md) — which +- [Shared responsibility](../compliance/shared-responsibility.md): which duties the software can carry. diff --git a/website/book/src/signing/digest.md b/website/book/src/signing/digest.md index 95f16ebabd..32d52ac5df 100644 --- a/website/book/src/signing/digest.md +++ b/website/book/src/signing/digest.md @@ -120,7 +120,7 @@ That copy has its own channel: `POST /ferroehr/rest/extensions/v1/admin/integrit re-derives every stored version from its decomposed rows and reports any that no longer match the stored document. It is an admin route, it runs outside the request path, and it reports by identifier rather than by -content. The [admin API reference](../operations-admin-apis.md#storage-integrity) +content. The [admin API reference](../storage-admin-apis.md#storage-integrity) documents the report and its five defect values. ## Verification at read @@ -143,7 +143,7 @@ CONTRIBUTION read resolves under `Prefer: resolve_refs`. A plain content read (`GET /ehr/{ehr_id}/composition/{uid_based_id}`) returns the COMPOSITION rather than the VERSION that carries the signature, and runs no check. AQL reads the decomposed storage rows directly and runs no check either; the -[storage-parity sweep](../operations-admin-apis.md#storage-integrity) is what +[storage-parity sweep](../storage-admin-apis.md#storage-integrity) is what covers those. > [!WARNING] diff --git a/website/book/src/smart-app-launch.md b/website/book/src/smart-app-launch.md index b8e835c2a7..23c1687147 100644 --- a/website/book/src/smart-app-launch.md +++ b/website/book/src/smart-app-launch.md @@ -114,7 +114,7 @@ restart: a capability of a `ROLE` the client's `AGENT` performs, coded `openehr_access::query_system_wide` or `openehr_access::access_demographic`, under an `[authz.grants] allowed` that admits the code. See -[Operational policy](operational-policy.md#a-backend-client-and-a-demographic-client) +[Operational policy](policy-examples.md#a-backend-client-and-a-demographic-client) for a worked example. A grant counts for a client's own app-only token; a person signed in through that client holds the person's grants. @@ -124,7 +124,7 @@ When an app is launched for a patient, your authorization server puts the openEHR EHR id of the launch context in the token's `ehrId` claim (master07 §Context Selection). The SMART layer checks a `patient/` grant for its resource family and permission, and the -[access evaluator](security.md#a-patients-own-ehr) holds a caller whose +[access evaluator](access-control.md#a-patients-own-ehr) holds a caller whose grants are `patient/` grants alone to that one EHR: - the grant reaches only the EHR its token's `ehrId` names, so a token that @@ -140,7 +140,7 @@ grants are `patient/` grants alone to that one EHR: - it reaches EHR data alone, never a template definition; - a write under a grant of `patient/` scopes alone is the person's own: it is marked as inserted by the person and may not alter a version a professional - committed ([EHDS Art. 5](security.md#information-a-person-inserts-ehds-art-5)). + committed ([EHDS Art. 5](access-control.md#information-a-person-inserts-ehds-art-5)). `user/` and `system/` grants carry no such binding, and when a `user/` grant covers the same operation the wider grant wins. diff --git a/website/book/src/storage-admin-apis.md b/website/book/src/storage-admin-apis.md new file mode 100644 index 0000000000..b14f1b062a --- /dev/null +++ b/website/book/src/storage-admin-apis.md @@ -0,0 +1,369 @@ +# Storage integrity, dump and load + +The admin routes that check and repair stored content, dump and load a repository, and +export and import EHR Extracts. The other admin routes are on [Admin & messaging +APIs](operations-admin-apis.md). + + + +## Storage integrity + +Two routes that check the stored data against itself and repair what they +find, behind the same switch and role. FerroEHR stores every version's content twice: once as the +materialized document a point read serves, and once as the decomposed rows the +AQL engine queries. A commit writes both in the same transaction, so they +always agree; anything that changes one of them behind the server's back +breaks that agreement. + +| Route | **200** body | +|---|---| +| `POST {ext}/admin/integrity/verify` | the sweep report | +| `POST {ext}/admin/integrity/rebuild-nodes` | the rebuild report | + +The sweep covers **both pseudonymisation domains**, clinical and demographic, +in one pass. Every finding names the domain it came from, so a report can never +describe half the store while looking like it described all of it. It re-derives +every stored version from its decomposed rows and compares the result with the +stored document, then decomposes that document again and compares the rows it +would write, which is what catches rows an older release left in a shape this +one no longer produces. It reads the archived tier as well, takes +no lock, and runs outside the request path of any clinical call, so it is safe +to run on a live server. It is also a full scan of what it covers, so schedule +it rather than calling it per request. + +Four optional query parameters narrow the scan, and they compose. Both routes +take the same set: + +| Parameter | Effect | +|---|---| +| `ehr_id` | cover only versions belonging to that EHR | +| `vo_id` | cover only versions of that versioned object | +| `sys_version` | cover only that version of it; the ordinal is per-object, so it needs `vo_id` and is a **400** on its own | +| `committed_since` | cover only versions whose validity begins at or after that RFC 3339 instant | + +Use them. Verifying one record after a support incident, or everything written +since a known point, costs a fraction of a full repository scan. + +### Verifying a whole large repository + +By default the route computes the whole report before it answers, so it has to +finish inside the server's 30-second request timeout. Send +`Accept: application/x-ndjson` and it streams the same sweep instead, writing +each finding as it is made. Nothing bounds that response, so this is how you +verify a repository too large to scope: + +```bash +curl -sN -X POST \ + -H 'Accept: application/x-ndjson' \ + "$BASE/admin/integrity/verify" +``` + +The body is one JSON object per line, each carrying a `type`: + +| `type` | When | Carries | +|---|---|---| +| `mismatch` | as each disagreement is found | the same five fields the report's `mismatches` entries carry, `domain` included | +| `progress` | once per page of versions read | the counts so far | +| `summary` | once, at the end | the final counts and `elapsed_ms` | +| `error` | instead of `summary`, if the sweep failed part-way | a short message; the detail is in the server log | + +Two consequences are worth planning around. The status code is sent before the +work is done, so a sweep that fails half-way still answered `200`: read to the +end and check that the last line is a `summary`, not an `error`. And the stream +carries no reporting cap, so every mismatch reaches you rather than the first +thousand. + +The stream has to be asked for by name. A request sending `*/*`, or no `Accept` +at all, gets the aggregated document below, unchanged. + +```json +{ + "versions_checked": 128, + "versions_with_body": 126, + "versions_without_body": 2, + "mismatch_count": 1, + "mismatches": [ + { + "domain": "clinical", + "vo_id": "8849182c-82ad-4088-a07f-48ead4180515", + "sys_version": 2, + "kind": "COMPOSITION", + "defect": "content_differs" + } + ], + "truncated": false, + "elapsed_ms": 431 +} +``` + +`domain` is `clinical` or `demographic`, naming the schema the damaged version +lives in. It is also what the repair below uses to reach it. + +`defect` is one of five values: + +- `content_differs`: both copies exist and hold different content. +- `nodes_missing`: the version has a stored document but no decomposed rows. +- `nodes_unreadable`: the decomposed rows exist but no longer form one tree. +- `unexpected_nodes`: the version is a logical delete, which stores no + document, yet decomposed rows exist for it. +- `stale_decomposition`: the rows hold exactly the stored document, but not in + the shape this version of the server decomposes it into. An older release + wrote them. The content is intact and every read serves it correctly; what is + stale is the index over it, so a query that depends on the current shape does + not reach this version until the repair below rewrites its rows. +- `orphan_nodes`: decomposed rows exist that no stored version reads, because + their version is gone or lives in the other storage tier. `kind` names the + class of the rows' root. The sweep reports them once it has read every + version of a domain, and a sweep scoped by `committed_since` leaves them out, + since rows without a version have no commit time. + +`mismatch_count` is the full count. `mismatches` is capped at 1000 entries and +`truncated` says whether the cap was reached; every mismatch is logged at +`warn` level with its identifiers whatever the cap does, so a truncated report +never loses a finding. The log line and the response carry identifiers only, +never content. + +A finding is **not** a request failure: the sweep ran and is telling you what +it saw, so the status stays **200** and the report is the body. Check +`mismatch_count`, not the status code. + +> [!NOTE] +> This is the companion check to [digest signing](signing/digest.md). A stored +> digest covers the document a point read serves; it says nothing about the +> decomposed rows, which no read-path check recomputes. Together the two cover +> both copies. + +### Repairing what the sweep found + +The sweep is the diagnosis. `POST {ext}/admin/integrity/rebuild-nodes` is the +repair: it re-derives the decomposed rows of every damaged version from that +version's stored document, one transaction per version. + +```bash +curl -s -X POST "$BASE/admin/integrity/rebuild-nodes?ehr_id=$EHR_ID" +``` + +It runs the same sweep first and writes only the versions that sweep reports +damaged, so a run over healthy data writes nothing at all. The scope +parameters are the same four, so a repair can be as narrow as one version: + +```bash +curl -s -X POST \ + "$BASE/admin/integrity/rebuild-nodes?vo_id=$VO_ID&sys_version=2" +``` + +Which copy wins is not a choice the route makes. The stored document is the +version's canonical serialized form, the bytes a point read serves and the +bytes a digest was taken over; the decomposed rows are an index derived from +it. So the repair only ever runs in that direction, and a version whose +**document** is the damaged copy is refused rather than having the damage +copied into the index. + +Each version is repaired inside one transaction: the document is read under a +row lock, decomposed, the old rows deleted, the new set inserted, and the +version re-derived from what was just written and compared with the document +before the commit. Anything that fails rolls that transaction back, so the +version's rows are left exactly as they were. One refusal never stops the run +that found it. + +An archived object is thawed for the repair and re-archived in the same +transaction, marker and all, because a write to a versioned object always +happens in the primary tier. + +A logically deleted version stores no document, so it rebuilds to no rows, +which is the repair for `unexpected_nodes`. Rows reported `orphan_nodes` have no +document to rebuild from, so the rebuild deletes them. + +The same route is the upgrade step after a release that changes how content is +decomposed. Rows written by the older release hold the right content, so +nothing is damaged, but they are the wrong shape for the new one and the sweep +reports them `stale_decomposition`. Rebuilding writes them again from the +stored document, which is all the upgrade is. Run it unscoped once and the next +sweep is clean: + +```bash +curl -s -X POST "$BASE/admin/integrity/rebuild-nodes" +``` + +The changelog names the affected object type at each such release. + +```json +{ + "versions_checked": 128, + "versions_damaged": 2, + "versions_rebuilt": 1, + "versions_refused": 1, + "records": [ + { + "domain": "clinical", + "vo_id": "8849182c-82ad-4088-a07f-48ead4180515", + "sys_version": 2, + "kind": "COMPOSITION", + "defect": "content_differs", + "outcome": "rebuilt", + "node_rows": 41 + }, + { + "domain": "demographic", + "vo_id": "1f0b7d64-6b2a-4a1f-9f0e-6b1d2a3c4d5e", + "sys_version": 1, + "kind": "PERSON", + "defect": "content_differs", + "outcome": "refused", + "reason": "the stored body does not decompose: ..." + } + ], + "truncated": false, + "elapsed_ms": 812 +} +``` + +`defect` is the sweep verdict that selected the version, from the five values +above. `outcome` is `rebuilt`, carrying the `node_rows` the version now has, or +`refused`, carrying the `reason`. `records` is capped at 1000 entries with +`truncated` saying whether the cap was reached; every record is logged at +`info` level with its identifiers whatever the cap does. + +A refusal is **not** a request failure, so the status stays **200**. Check +`versions_refused`: anything above zero means a stored document is itself +damaged, and that is a restore-from-backup question rather than a rebuild one. + +Unlike the sweep, this route writes, so a server in read-only mode refuses it. + +## Dump and load + +Two routes that move the whole repository to and from an archive on the +**server's** file system, behind the same switch and role. Both answer **200** +with a JSON array of per-entity failure reports; an **empty** array means +everything succeeded. + +### `POST {ext}/admin/dump` + +Writes an archive of every EHR **and of every standalone demographic +container**: the parties and party relationships that live outside any EHR. +The body is `{"file_sys_loc": "…"}` plus the optional export settings: + +| Field | Values | Default | +|---|---|---| +| `logical_format` | `openehr_canonical_json` or `openehr_canonical_xml` | canonical JSON | +| `compression_format` | `zip` or `7z` (omit for loose files) | uncompressed | +| `segment_split_size` | segment size in kb (a positive integer) | `1024` | + +`logical_format` chooses how the clinical **content** is serialized, not how +the archive is packaged: + +- `openehr_canonical_json` (the default) keeps each version's content inline + in the segment files, exactly as this server stores it. +- `openehr_canonical_xml` writes each version to its own + `versions/.xml` entry instead: a complete `ORIGINAL_VERSION` + document under the openEHR-published `` root, ready to hand to any + tool that reads canonical openEHR XML. + +The archive is a directory holding a `manifest.json`, one or more +`segment-NNNN.json` files, and a `blobs/` subdirectory for any externalized +multimedia. When the repository holds standalone demographic containers, the +archive additionally carries a `demographic-commons.json` (their shared +audits and contributions) and one or more `demographic-NNNN.json` segments, +one record per party or relationship, in the same version-record shape the +EHR segments use. With `compression_format` set, those same entries are +packed into a single `archive.zip` or `archive.7z` inside the location +instead. The +archive's own bookkeeping (the manifest and the segment skeleton) stays JSON +in both logical formats, because openEHR publishes no XML document form for +it. + +### `POST {ext}/admin/load` + +Populates the repository from an archive. It takes the location and nothing +else: the container (loose files, a single `archive.zip`, or a single +`archive.7z`) is detected from what the location holds, and the logical format +is read from the archive's own manifest, so a load never has to be told how +the dump was written. Archives written before the demographic wave existed +simply carry no demographic entries and load unchanged. + +The repository being loaded into **need not be empty**. An EHR whose id is +already present is reported and skipped rather than failing the load, so the +response array names each one; and a standalone demographic container that +already exists is reported the same way, under its own kind (`PERSON`, +`ORGANISATION`, `GROUP`, `AGENT`, `ROLE`, or `PARTY_RELATIONSHIP`) as the +`entity_type`: + +```json +[ { "entity_type": "EHR", + "entity_id": "7d44b88c-4199-4bad-97dc-d78268e01398", + "dump_status": false, + "error": "an EHR with this id already exists" } ] +``` + +Both directions are lossless: a dump and a load reproduce every record, +whichever format and container you choose. + +### Refusals + +| Status | When | +|---|---| +| **400** | a missing or blank `file_sys_loc`; a format value outside the lists above; a non-positive `segment_split_size`; an `encoding` field (the openEHR service model declares that enumeration with no members, so no value a client could send names one); on load, an archive carrying externalized multimedia this server has no store for, and a malformed archive (a mangled or truncated container, manifest, segment or blob entry, or a manifest naming no known format), the [`archive-invalid`](using-the-api/problems.md#archive-invalid) problem, which names the entry. Nothing is loaded | +| **415** | the request `Content-Type` is not `application/json` | +| **500** | a location that holds **no** archive, or one the server's filesystem refuses to read: the service model's `file_not_writable` error for these operations. Nothing is loaded. On dump, the same status covers a location, segment, payload entry or manifest that could not be created or written | + +A single unreadable `versions/*.xml` entry is *not* in that family: it belongs +to one EHR, so that EHR is reported in the response array and skipped whole +while the rest of the archive loads. + +> [!NOTE] +> The activity report, the archive routes and the dump/load pair are FerroEHR +> extensions: the openEHR *service model* defines these operations, but the +> released REST API surfaces no endpoint for them, so their URLs are our own. +> The two `…/restore` routes go one step further: the service model declares +> the archive calls and no un-archive counterpart, so both the operation and its +> URL are ours. They gate no openEHR conformance claim; see +> [Conformance](conformance.md). + +## EHR Extract export and import + +Four routes under `{ext}/message` that move whole records between systems. +Unlike the admin extensions above, these are **not** admin-gated; see +[the gate table](operations-admin-apis.md#where-these-routes-live-and-what-gates-them). + +- `GET {ext}/message/export/{ehr_id}`: export one whole EHR. **200** with a + JSON array holding one `EXTRACT` that carries every versioned object of the + EHR, latest versions only. **400** if `ehr_id` is not a well-formed + identifier, which is refused before any lookup; **404** if the EHR does not + exist; **406** if `Accept` cannot be satisfied (the extract list is JSON + only). +- `POST {ext}/message/export` with an `EXTRACT_SPEC` body: export by + specification. **200** with one `EXTRACT` per manifest entity, in manifest + order. The manifest must name at least one entity, and each entity must + name its record by `ehr_id` or `subject_id`, otherwise **400**; an + identifier that names nothing is **404**. `extract_type` must be one of the + extract-content-type codes the openEHR Reference Model names + (`openehr-ehr`, `openehr-demographic`, `openehr-synchronisation`, + `openehr-generic`, `generic-emr`) or the catch-all `other`; anything else + is **400**, as is a selection this service does not support (search + criteria, an unsupported commit-time interval). This route is classified as + a **read**: it selects over held versions and commits nothing, exactly like + the ad-hoc AQL `POST`. +- `POST {ext}/message/import` with an `EXTRACT` body: clone a whole EHR. Add + `?ehr_id=` to fix the identifier the clone lands under; leave it off + and the source identifier the extract carries is re-used. **201** with + `{"uid": ""}`, so a caller that supplied no id still learns what was + created. The extract must carry an `EHR_STATUS` (**400**), and the target + must not already exist: **409**, which also covers an imported `EHR_STATUS` + naming a subject another EHR already holds. +- `POST {ext}/message/import/{ehr_id}` with an `EXTRACT` body: add the + extract's content to an **existing** EHR as new versions. **204**. **404** + if the EHR does not exist; **409** if the EHR already holds an `EHR_STATUS` + or `EHR_ACCESS` under a different object id, or the imported status names + another EHR's subject; **422** if a version in the extract is semantically + invalid (template, RM-invariant or terminology validation). + +All four accept either `application/json` or `application/xml` bodies; any +other `Content-Type` is **415**. + +> [!NOTE] +> The whole `{ext}/message` group is a FerroEHR extension: the openEHR service +> model defines a Message component, but the released REST API publishes no +> message or extract endpoint at all. These URLs are our own and gate no +> openEHR conformance claim; see [Conformance](conformance.md). For the +> workflow-level view (what an extract is good for and how to drive an +> import) see [EHR Extract & messaging](beyond-core/messaging.md). diff --git a/website/book/src/storage-sizing.md b/website/book/src/storage-sizing.md new file mode 100644 index 0000000000..4861bf3c1d --- /dev/null +++ b/website/book/src/storage-sizing.md @@ -0,0 +1,202 @@ +# Storage sizing + +How much disk a FerroEHR database takes, how the figures were measured, and how to measure +your own. + + + +The database grows with two things: the composition versions you commit and +the requests the access log records. Size a deployment from the figures below, +then check it against your own data with the query at the end of this section. +No openEHR specification governs storage layout or sizing: these are +measurements of our own design. + +## What the figures were measured on + +The run of 2026-11-26, on the quickstart (`docker-compose.yml` with +`FERROEHR_EHR_INDEX=local` and the usage report off), with the images pinned by +digest: + +| Image | Digest | +|---|---| +| `ghcr.io/ferrohealth/ferroehr` (built from commit `31f0f293cb`) | `sha256:3ec481157f904e622403d23404656211187f7d60586f639411ffa089f582ef06` | +| `ghcr.io/ferrohealth/ferroehr-postgres` (PostgreSQL 19.0) | `sha256:2fc22cc02891a84b82eaebdc858fd3eeaf8e4915e6f7e41a0361f69f5cc70099` | + +PostgreSQL ran with `shared_buffers=1GB`, `max_wal_size=4GB`, +`wal_compression=lz4` and default autovacuum, in a Podman VM with 8 CPUs and +16 gibibytes of memory. `scripts/perf/storage-sizing.sh` drove each workload +over ITS-REST with 8 workers, on a fresh database each time, and read the size +of every relation and the WAL position after each phase: + +| Phase | Vital signs | International Patient Summary | +|---|---|---| +| EHRs created | 300 | 100 | +| Compositions committed | 3 000 (10 per EHR) | 500 (5 per EHR) | +| Updates (`PUT` with `If-Match`) | 750 | 125 | +| Deletes | 300 | 50 | +| Composition reads | 6 000 | 1 000 | + +The compositions are the vendored CKM examples: vital signs is 10 769 bytes of +canonical JSON without whitespace and 43 RM nodes, the International Patient +Summary 87 133 bytes and 395 RM nodes. + +## Measuring your own figures + +`scripts/perf/storage-sizing.sh` in the repository runs the same phases +against a running FerroEHR and reports the bytes per create, update, delete +and read, per relation, and the node rows with their heap and index bytes per +row. Start the server on a fresh database, so the run is all the database +holds, then: + +```sh +scripts/perf/storage-sizing.sh run sizing-out +``` + +It reads the sizes through `psql` as the database superuser, by default in the +quickstart's `ferroehr-postgres` container (`SIZING_PSQL` names another +command), and writes `sizing-out/report.json`. +`SIZING_TEMPLATE=international-patient-summary` measures the larger +composition, and `SIZING_EHRS`, `SIZING_PER_EHR`, `SIZING_UPDATES`, +`SIZING_DELETES` and `SIZING_READS` set the counts; the script's header lists +every setting. With the defaults (300 EHRs, 3 000 vital signs creates, 750 +updates, 300 deletes and 6 000 reads) it reproduces the figures below within +a few percent. Its WAL figures include the full-page images each phase's +`CHECKPOINT` forces, so they are higher than a steady state. + +## Bytes per composition version + +| Per committed version | Vital signs (10.8 KB of JSON) | International Patient Summary (87 KB of JSON) | +|---|---|---| +| Node rows | 43 rows of 190 B heap and 65 B of index, 11.0 KB | 395 rows of 174 B heap and 66 B of index, 94.6 KB | +| `version` row, with the body compressed (lz4) | 2.4 KB, in the row | 11.4 KB, in TOAST | +| `contribution`, `vo_head`, `commit_audit_facts` and `audit_reservation` | 0.6 KB | 1.2 KB | +| **Clinical storage per create** | **14.0 KB (1.3 × the JSON)** | **107 KB (1.2 × the JSON)** | +| An update that commits the same content again | 2.8 KB | 13.2 KB | +| A delete (a version with no body and no nodes) | 0.9 KB | 3.1 KB | +| WAL written per create | 25 KB | 177 KB | + +The node rows hold 79 % of a vital signs version's clinical bytes and 88 % of +an International Patient Summary's, so the size of a version follows the +number of RM nodes in the composition more closely than the length of its +JSON. The driver's updates commit the example body again: such an update adds +the version row and its change-control rows and no node rows. A new EHR takes +about 10 KB, its `EHR_STATUS` version and its access-log entry included. + +## Bytes per audit record + +Every audited request writes an entry of the openEHR access log +(`audit.access_log_entry`, with its search index `audit.access_log_index`), +reads included. An entry takes about 1.5 KB for a composition read or create +of vital signs, and 1.3 to 1.9 KB for an International Patient Summary. For a +read-heavy workload the access log can outgrow the clinical data: 6 000 +composition reads added about as much as 630 new vital signs versions. + +## A sizing estimate + +Add up, for the period you size for: + +- the composition versions you expect, times the bytes per version of your + own templates (14 KB for one like vital signs, about 0.3 KB per RM node as + a first estimate); +- the audited requests, times about 1.5 KB, for as long as the + [audit retention](ehds-logging.md#retention-and-who-chooses-it) keeps them; +- `pg_wal`, up to `max_wal_size` (below); +- your backups and WAL archive, which this database does not hold. + +One million vital-signs-sized versions take about 14 GB, and ten million +audited requests about 15 GB. + +## Audit retention + +An access policy with no `log_retention`, the default, keeps every audit +record forever, so the access log grows with every request for the life of +the database. A period (`ACCESS_POLICY.log_retention.period`, in years or +days) makes the reaper delete each record on or after its end date, hourly, +and the `audit_event` table then levels off at roughly the period times the +request rate. The space of a deleted row is not returned to the operating system: +`VACUUM` marks it free and later records reuse it (PostgreSQL 19 docs, +[Routine Vacuuming, Recovering Disk Space][pg-vacuum]). +The reaper also deletes the search tokens no remaining record names. The +period is the controller's legal choice, within the floors and ceilings it +declares, set out on the audit page. +The openEHR access log levels off too: each entry is kept for its own period, +its tombstone as long again, and then a run of tombstones folds into one gap +row ([steady-state size](ehds-logging.md#the-access-log-at-steady-state)). + +## `pg_wal` + +PostgreSQL keeps the write-ahead log of the last checkpoints in `pg_wal`, up +to about `max_wal_size` (4 GB in the quickstart), on the same volume as the +data unless you move it. `max_wal_size` is a soft limit: a failing +`archive_command`, `wal_keep_size` or a replication slot whose standby falls +behind holds more (PostgreSQL 19 docs, +[WAL Configuration](https://www.postgresql.org/docs/19/wal-configuration.html)). +Budget it as a fixed amount beside the database, not as growth. A commit +writes about 1.8 times its stored size to the WAL (25 KB for a 14.0 KB vital +signs version), which is what a WAL archive for point-in-time recovery receives. + +Set `wal_compression = lz4`. The first change to a page after a checkpoint +writes the whole page to the WAL, and lz4 compresses those images at a CPU +cost far below the flush it saves. Since PostgreSQL 19, `on` picks +the first of zstd, lz4 and pglz the server was built with, where it always +meant pglz before (PostgreSQL 19 docs, +[WAL Configuration](https://www.postgresql.org/docs/19/runtime-config-wal.html#GUC-WAL-COMPRESSION)); +naming `lz4` keeps the measured method. The quickstart and the capacity +harness both run with it. + +## Vacuum and fillfactor + +The clinical write path is insert-only: a composition update or delete adds a +version and never updates or deletes an existing `version` or node row, so the +clinical tables accumulate no dead tuples. Changing autovacuum or fillfactor settings does +not change the volume. Autovacuum still has to run, for the planner +statistics and to freeze old rows before transaction ID wraparound. + +## Index maintenance + +The node table's primary key, `clinical.node_hot_pkey`, takes inserts from +concurrent commits at many places in the index, so its pages split and stay +partly empty, and a rebuild packs its leaves again. Rebuild it after heavy +write periods, without blocking reads or writes: + +```sql +-- leaf density before; pgstattuple ships with PostgreSQL +CREATE EXTENSION IF NOT EXISTS pgstattuple; +SELECT avg_leaf_density FROM pgstatindex('clinical.node_hot_pkey'); + +REINDEX INDEX CONCURRENTLY clinical.node_hot_pkey; +``` + +Run it as the database owner or a role holding `MAINTAIN` on +`clinical.node_hot`. `REINDEX CONCURRENTLY` needs room for a second copy of +the index while it runs, and it waits for every transaction older than +itself to finish, so one long-running query or an idle open transaction holds +it up (PostgreSQL 19 docs, +[REINDEX, Rebuilding Indexes Concurrently][pg-reindex]). + + +## Reading the size per relation + +```sql +SELECT n.nspname || '.' || c.relname AS relation, + pg_size_pretty(pg_relation_size(c.oid)) AS heap, + pg_size_pretty(COALESCE(pg_total_relation_size(NULLIF(c.reltoastrelid, 0)), 0)) AS toast, + pg_size_pretty(pg_indexes_size(c.oid)) AS indexes, + pg_size_pretty(pg_total_relation_size(c.oid)) AS total +FROM pg_class c +JOIN pg_namespace n ON n.oid = c.relnamespace +WHERE c.relkind = 'r' + AND n.nspname IN ('clinical', 'party', 'audit', 'ext') +ORDER BY pg_total_relation_size(c.oid) DESC +LIMIT 15; +``` + +Divide the growth of `clinical.node_hot` and `clinical.version_hot` between +two readings by the versions committed in between +(`SELECT count(*) FROM clinical.version_hot`) to get your own bytes per +version. The functions are described in PostgreSQL 19 docs, +[Database Object Management Functions][pg-dbobj]. + +[pg-vacuum]: https://www.postgresql.org/docs/19/routine-vacuuming.html#VACUUM-FOR-SPACE-RECOVERY +[pg-reindex]: https://www.postgresql.org/docs/19/sql-reindex.html#SQL-REINDEX-CONCURRENTLY +[pg-dbobj]: https://www.postgresql.org/docs/19/functions-admin.html#FUNCTIONS-ADMIN-DBOBJECT diff --git a/website/book/src/templates-validation.md b/website/book/src/templates-validation.md index 9bc7f9597a..39dce8928f 100644 --- a/website/book/src/templates-validation.md +++ b/website/book/src/templates-validation.md @@ -725,6 +725,6 @@ each `path: message` pair, separated by `; `. ## Next -- [Using the API → Resource walkthroughs](using-the-api/resources.md) — the full +- [Using the API → Resource walkthroughs](using-the-api/resources.md): the full composition create/update/delete lifecycle. -- [Querying with AQL](querying-aql.md) — reading the data back out by path. +- [Querying with AQL](querying-aql.md): reading the data back out by path. diff --git a/website/book/src/threat-model.md b/website/book/src/threat-model.md index 95b8c7b0ab..3e54ab5985 100644 --- a/website/book/src/threat-model.md +++ b/website/book/src/threat-model.md @@ -107,7 +107,7 @@ flowchart LR Each boundary below names the control that holds and the risk that remains. -### B1 — Network and protocol +### B1: Network and protocol **Control.** TLS terminates either at the server (`rustls`, TLS 1.3 by default, the post-quantum hybrid key exchange X25519MLKEM768 preferred) or in front of @@ -140,7 +140,7 @@ the harness. - **TLS termination in front of the server is the operator's**; nothing in the software can tell whether the hop behind the proxy is encrypted. -### B2 — Authentication +### B2: Authentication **Control.** Two mechanisms: HTTP Basic against Argon2id PHC hashes with a verified-credential cache, and OAuth 2.0 bearer tokens validated against the @@ -167,7 +167,7 @@ names no reason, so it is not an oracle for expired-versus-forged. is intended for machine callers and small deployments; the Argon2id cost is the only brake on offline cracking if a hash leaks. -### B3 — Authorization +### B3: Authorization **Control.** Five stages, each of which can only *narrow* what the previous one allowed, which is what makes an optional stage safe to leave off: @@ -209,7 +209,7 @@ never consent, and a broken control never looks like a policy outcome. recorded.** That is what the audit trail is for, and detection is not prevention. -### B4 — Content validation and outbound calls +### B4: Content validation and outbound calls **Control.** Committed content is validated against the operational template (the WebTemplate walker), the Reference Model's own invariants (machine-derived @@ -247,12 +247,12 @@ and reads nothing from the answer beyond its status code. - **Validation does not make content true.** A well-formed composition asserting a clinically wrong fact is stored, correctly. -### B5 — Instance separation +### B5: Instance separation **Control.** One instance serves one organisation: one database, one set of domain roles. There is no tenant column, no row policy and no session setting to get wrong, because there is nothing inside the instance to separate. That is -also where openEHR puts the boundary — BASE `architecture_overview` +also where openEHR puts the boundary: BASE `architecture_overview` `master06-design_of_the_ehr.adoc` §The EHR System calls a system "a distinct logical repository corresponding to an organisational entity that is _legally responsible_" for the data and "distinct from any underlying virtualisation @@ -275,7 +275,7 @@ EHR systems in a multi-tenant fashion". one value mint version identifiers that cannot tell the responsible parties apart. -### B6 — The database +### B6: The database **Control.** The application connects with least-privilege roles, one per pseudonymisation domain, and the schema is prepared by a separate credential @@ -306,7 +306,7 @@ contribution and an audit record in the same transaction. dumps are worth together, is [Backup artefacts](#backup-artefacts) below. -### B7 — The audit trail +### B7: The audit trail **Control.** Every access is recorded in both official renderings (DICOM PS3.15 and FHIR R4 `AuditEvent`/BALP) into a local Audit Record Repository, on by @@ -317,7 +317,7 @@ fabricated subject. System records and access-log entries are **sealed** in signed windows, so `ferroehr audit-chain verify` and `ferroehr access-log verify` name any record that was altered, removed or inserted, and the server runs that verification itself on a schedule -([tamper evidence](audit.md#tamper-evidence)). ITI-81 is the retrieval side; ITI-19 mutual TLS is available for +([tamper evidence](audit-integrity.md#tamper-evidence)). ITI-81 is the retrieval side; ITI-19 mutual TLS is available for node authentication. **Residual risk.** @@ -335,7 +335,7 @@ node authentication. actions; ITI-81 retrieval is a PHI-disclosure surface and is authorized like any other. -### B8 — The supply chain +### B8: The supply chain **Control.** Releases are built by a reusable workflow that satisfies SLSA v1.0 Build L3, signed through Sigstore with a signer identity a consumer can pin, diff --git a/website/book/src/tutorials/first-integration.md b/website/book/src/tutorials/first-integration.md new file mode 100644 index 0000000000..91cc73cc81 --- /dev/null +++ b/website/book/src/tutorials/first-integration.md @@ -0,0 +1,148 @@ + + + +# Your first integration + +**For:** developers building on the REST API. This tutorial takes you from an +empty server to a stored, updated and queried composition, and shows the two +answers every integration has to handle: a stale version and a missing record. +Every request on this page is run against the server in CI, so the requests +and the statuses they show are the ones the server gives. + + + +## Before you start + +Run the quickstart ([Getting started](../getting-started.md)). The requests +below are plain HTTP against `http://localhost:8080`. Send them with any HTTP +client and add your credentials: on the quickstart that is HTTP Basic +`ferroehr` / `ferroehr` (`curl -u ferroehr:ferroehr`). A production deployment +takes an OAuth 2.0 bearer token from your authorization server instead +([SMART App Launch](../smart-app-launch.md), [Enterprise identity +providers](../identity-providers.md)). + +Download two files from the repository: the vital signs template +[`vital-signs.opt`](https://github.com/FerroHEALTH/FerroEHR/blob/main/corpus/templates/ckm/vital-signs.opt) +and an example composition for it, +[`vital-signs.example.json`](https://github.com/FerroHEALTH/FerroEHR/blob/main/corpus/templates/ckm/vital-signs.example.json). + +Placeholders in braces, such as `{ehr_id}`, stand for a value an earlier +answer gave you. + +## 1. Upload the template + +A template tells the server what a composition may contain +([Templates & validation](../templates-validation.md)). Send the file as the +body: + + +```http +POST /ferroehr/rest/openehr/v1/definition/template/adl1.4 +Content-Type: application/xml +``` + +The server answers `201 Created`. Uploading the same template again answers +`409 Conflict`. + +## 2. Create an EHR + + +```http +POST /ferroehr/rest/openehr/v1/ehr +Prefer: return=representation +``` + +`Prefer: return=representation` asks for the new EHR in the body. Keep its +`ehr_id.value`: every clinical request names it. + +## 3. Commit a composition + + +```http +POST /ferroehr/rest/openehr/v1/ehr/{ehr_id}/composition +Content-Type: application/json +Prefer: return=representation +``` + +The answer carries the composition with its version id in `uid.value`, such +as `8849182c-82ad-4088-a07f-48ead4180515::local.ferroehr::1`: the versioned +object's id, the system that created it and the version number. The `ETag` +header carries the same id. + +## 4. Read it back + + +```http +GET /ferroehr/rest/openehr/v1/ehr/{ehr_id}/composition/{uid} +Accept: application/json +``` + +Ask for `application/xml` to get canonical XML, or a simplified format +([Content negotiation & errors](../using-the-api/content-negotiation.md)). + +## 5. Update it + +An update names the versioned object in the path and the version you read in +`If-Match`, so two clients cannot overwrite each other unseen: + + +```http +PUT /ferroehr/rest/openehr/v1/ehr/{ehr_id}/composition/{object} +Content-Type: application/json +Prefer: return=representation +If-Match: "{uid}" +``` + +The answer is version 2. Every earlier version stays readable: an openEHR +repository never overwrites a version. + +## 6. Handle a stale version + +Send the same update again, still naming version 1: + + +```http +PUT /ferroehr/rest/openehr/v1/ehr/{ehr_id}/composition/{object} +Content-Type: application/json +If-Match: "{uid}" +``` + +The server answers `412 Precondition Failed`, because version 2 is now the +latest. Read the latest version, apply your change to it, and send the update +with its id. + +## 7. Query with AQL + + +```http +POST /ferroehr/rest/openehr/v1/query/aql +Content-Type: application/json + +{ + "q": "SELECT c/uid/value FROM EHR e[ehr_id/value=$ehr_id] CONTAINS COMPOSITION c", + "query_parameters": { "ehr_id": "{ehr_id}" } +} +``` + +Each row holds the selected columns of one composition: here the id of its +latest version. [Querying with AQL](../querying-aql.md) covers the language. + +## 8. Handle a missing record + + +```http +GET /ferroehr/rest/openehr/v1/ehr/00000000-0000-4000-8000-000000000000 +Accept: application/json +``` + +An error is an RFC 9457 problem details document. Its `type` names what went +wrong, and [Problem types](../using-the-api/problems.md) lists them all. A +`403` means the access decision refused the caller +([How FerroEHR decides access](../explanation/access-model.md)). + +## Next + +- [Resource walkthroughs](../using-the-api/resources.md): every resource and + operation. +- [Content negotiation & errors](../using-the-api/content-negotiation.md): + formats, `Prefer`, `ETag` and `If-Match` in detail. diff --git a/website/book/src/upgrades.md b/website/book/src/upgrades.md new file mode 100644 index 0000000000..a411bc7610 --- /dev/null +++ b/website/book/src/upgrades.md @@ -0,0 +1,201 @@ +# Upgrades + +How to move a running deployment to a new release, and how long a release is supported. + + + +- **Upgrade in place within v6; the migrations are append-only.** A released + migration is never edited again, so a database created by an earlier v6 + release takes the new release's migrations on top of the ones it already + carries. The server + records the checksum of every applied migration and refuses to start against + a database whose recorded checksums differ from the files it carries + (`migration 1 was previously applied but has been modified`), which is why + editing one would lock every existing installation out of its own database + rather than revise its history. A correction ships as a new migration, and a + CI guard fails any pull request that modifies, renames or deletes one the + base branch already has. A rolling upgrade must still stay compatible with + the _previous_ schema for the window in which both versions run: additive + changes first, destructive changes a release later. + + A v5 database is not upgraded in place: see [Upgrading from v5 to v6](#upgrading-from-v5-to-v6). +- **Sweep for stale decomposition after a release that changes how content is + decomposed.** The version body is unaffected and every read serves it + correctly; what is stale is the decomposed index over it, which a + row-level query predicate depends on. `POST /ferroehr/rest/extensions/v1/admin/integrity/verify` + reports each such version as `stale_decomposition` and + `POST /ferroehr/rest/extensions/v1/admin/integrity/rebuild-nodes`, run once unscoped, rewrites the + rows from the stored document. The changelog names the affected object type + at each release that needs it. Both routes are on + [Admin & messaging APIs](storage-admin-apis.md#storage-integrity). +- **Bound the DDL yourself.** Every pooled connection carries the + `[database] statement_timeout` value (60 seconds by default), and the migration + step runs on that pool, so a runaway statement is cut off, but there is **no + `lock_timeout`**, so a migration that waits behind a long transaction waits + as long as that transaction lasts. On a busy table use + `CREATE INDEX CONCURRENTLY`, add constraints `NOT VALID` and `VALIDATE` + later, and set `lock_timeout` in the migration session (or on the migrator + role) if you need the wait bounded. +- **Pin the image.** Deploy an immutable tag or, better, a `@sha256` digest, + never `latest`; roll back by re-pinning the prior digest, since the schema's + backward compatibility makes that safe. +- **Stay available.** Keep at least two replicas (or autoscaling) and a pod + disruption budget so node drains and upgrades never fully interrupt the + API. The default 30-second termination grace period covers the server's + shutdown; the audit records are stored before each response, so a + replica that stops leaves nothing in memory. + +## Upgrading from v5 to v6 + +**v6 needs a new, empty database.** v6.0.0 replaces the whole migration +history of every schema (`ext`, `clinical`, `party`, `audit`) with one +baseline that creates each object once, in its final shape. A database +prepared by v5 carries the v5 migration bookkeeping, and a v6 server refuses +to start against it, naming the schema it found and this way forward, rather +than apply its baseline over the old schema. Nothing is upgraded in place, and +no compatibility layer reads a v5 database. + +Move the records instead: + +1. With the v5 server still running, dump the repository with + [`POST {ext}/admin/dump`](storage-admin-apis.md#post-extadmindump) to a location both + servers can reach. +2. Create a new, empty PostgreSQL 19 database (or one per relocated domain, + as the v5 deployment had), and start the v6 server against it. With + `[database] migrations = "apply"` it applies the baseline at its first + boot; with `"verify"`, run `ferroehr db migrate` under the migrator + credential first. +3. Load the archive into the v6 server with + [`POST {ext}/admin/load`](storage-admin-apis.md#post-extadminload). +4. Put the controller's access policy in place before you load an archive + that holds open care relationships + ([operational policy](operational-policy.md)), and check the configuration + with `ferroehr config check`, since v6 refuses the keys v5 removed. + +The audit trail is not part of the archive. Export what you need of the v5 +audit trail over ITI-81 before you retire the v5 database. + +The v6 baseline creates no `linkage` schema and no `ferroehr_linkage` role: a +cluster that held v5 databases may still carry that role, which v6 never names, +and you drop it with `DROP ROLE ferroehr_linkage` once no v5 database in the +cluster grants it anything. + +## How long the version you pinned is supported + +Plan the upgrade cadence around this: + +- **Only the newest release is supported.** When a new release is + published, every earlier release stops receiving fixes: there are no + maintenance branches, no long-term-support line and no backports. If you are + not on the newest release, upgrade; upgrading is free. Under the Cyber + Resilience Act, Cadasto B.V. commits to keep publishing security fixes for at + least five years after each release (Art 13(8)) and ships them only in the + newest release (Art 13(10)), which every user of an earlier release may run + under the same licence terms. Staying on an older release means running + without the fix. +- **A fix normally arrives as the next patch** on the current minor, so taking + it does not oblige you to take new behaviour, but that is the usual case, + not a promise. Where a fix is only correct alongside a behavioural change, + the release carrying it carries the change, and the changelog entry says so. +- **A published release is never repaired in place.** Release immutability + means the assets and the tag of a published release cannot be modified at + all, so the remedy for any defect is a new version. +- **The Helm chart and the published crates follow their own version lines**, + each supported only in its newest published version, which is where its + fixes ship. A chart-only fix ships as a new chart version between server + releases. + +**The running server states the end month of the commitment.** Cadasto B.V. +keeps publishing fixed releases for at least five years after each release +(CRA Art 13(8)), and the server reads its release date from its changelog +heading at build time. The end month, the date until which fixed releases +keep coming, does not make the running release supported: a release is +supported only while it is the newest. The end month is on the boot banner (`Support` line), in the boot log, in +`ferroehr --version`, under `support` in `GET /management/info`, and under +`support` in `GET /management/status` as +`{release_date, support_ends, status}`, where `support_ends` is `YYYY-MM` and +`status` is `supported` (the commitment is still running), `ended` or +`unreleased`. Once the end month has passed, +`status` reads `ended` and the server logs a `warn` line at boot and once a day +(CRA Art 13(19)). A build of a version whose changelog heading carries no date +is not a release: it reports `unreleased` and no end month. + +The server does not contact anyone to look for newer releases. To hear about +them, subscribe to the release feed +(`https://github.com/FerroHEALTH/FerroEHR/releases.atom`) and poll the +published security advisories +(`GET https://api.github.com/repos/FerroHEALTH/FerroEHR/security-advisories`). + +The consequence for change control: budget for taking every release, or budget +for maintaining a fork. There is no third option, and the full policy (with +the reasoning and what to do if you need something stronger) is +[SECURITY.md](https://github.com/FerroHEALTH/FerroEHR/blob/main/SECURITY.md#supported-versions). + +## Upgrading the Helm release + +Migrations are **append-only** (a schema change is a new file, never an edit to +an applied one) so a rolling upgrade stays compatible with the previous schema +during the window where both versions run: additive DDL first, destructive +changes in a later release once all pods are on the new version. Keep +`replicaCount` at two or more (or `autoscaling.enabled`) and the default +PodDisruptionBudget so upgrades and node drains never fully interrupt the API; +the default `terminationGracePeriodSeconds` covers the binary's shutdown drain. +Roll back by re-pinning the prior image tag or digest. + +The step from v5 to v6 is the exception: v6 starts from a new migration +baseline and needs a new, empty database, so it is a new installation with the +records moved by archive dump and load +([Operations → Upgrading from v5 to v6](upgrades.md#upgrading-from-v5-to-v6)). + +A change anywhere under `config`, `config.files` or `secrets` changes the +`checksum/config` pod annotation, so `helm upgrade` rolls the pods for a +configuration-only change too, including a rotated secret or an edited +mounted file, both of which are read at boot and would otherwise reach the volume while +every running pod kept using the old value. + +`helm uninstall` removes everything the chart created; the chart declares no +PersistentVolumeClaim, so nothing is left behind; your database, and the Secret +holding its DSN, are yours and survive. + +Preview an upgrade against what you have installed with +`helm diff`, or render the new chart version and read it: + +```shell +helm template ferroehr oci://ghcr.io/ferrohealth/charts/ferroehr --version 43.0.1 \ + -n ferroehr -f my-values.yaml | less +``` + +Working from a checkout instead, `deploy/helm/validate.sh` runs the chart's full +render gate: the helm-version pin, lint, YAML validity, the structural +Restricted-profile and selector-immutability gates, the secret-leak gate, the +values-schema probes, and the golden-render diff. It is the same gate CI runs on +every change to the chart, so a local run and a pull request agree by +construction. + +### Check your values before you deploy them + +A render that lints is not a deployment that boots. `validate.sh` never runs the +server, so it cannot see a configuration the server refuses: a missing +authentication mechanism, an `HS*` algorithm, a password hash that is not a +real Argon2id PHC string, SMART enabled without its public base URL. Every one of those renders perfectly and crash-loops the pod. The +script prints exactly which properties it does not check, on success as well as +on failure, so a green run is not mistaken for a working deployment. + +The check that closes that gap runs the image against your rendered +configuration: + +```shell +FERROEHR_IMAGE=ghcr.io/ferrohealth/ferroehr:5.7.1-rc1 \ + deploy/helm/ci/boot-check.sh my-values.yaml +``` + +It renders the chart, mounts the ConfigMap and the Secret exactly as the +Deployment does (with their real values, not placeholders) replays the +declared environment, and runs `ferroehr config check` inside the image. Point +`FERROEHR_IMAGE` at the tag you intend to deploy: the answer is specific to that +image, since a key your values carry may be newer than the server that has to +read it. + +It validates configuration only; it opens no socket, so it cannot tell you the +issuer resolves, the broker is reachable or the database accepts the DSN. CI +runs the same script over every values overlay the chart ships. diff --git a/website/book/src/using-the-api/content-negotiation.md b/website/book/src/using-the-api/content-negotiation.md index b1d7d59c07..e67eaec608 100644 --- a/website/book/src/using-the-api/content-negotiation.md +++ b/website/book/src/using-the-api/content-negotiation.md @@ -157,8 +157,8 @@ types: | Media type | Meaning | |---|---| -| `application/openehr.wt.flat+json` | FLAT — one flat JSON object of `path: value` pairs | -| `application/openehr.wt.structured+json` | STRUCTURED — the same data as nested JSON | +| `application/openehr.wt.flat+json` | FLAT: one flat JSON object of `path: value` pairs | +| `application/openehr.wt.structured+json` | STRUCTURED: the same data as nested JSON | | `application/openehr.wt+json` | A template rendered as Web Template JSON (template endpoints only) | Where they work: @@ -238,7 +238,7 @@ response body. Its default is `return=minimal`: |---|---| | `return=minimal` (default) | Empty body; the identifier is in `ETag`/`Location`. Status **204** on update, **201** on create. | | `return=representation` | The full created/updated resource in the body, status **200**/**201**. | -| `return=identifier` | Just the resource identifier object — `{"uid": "…"}` (templates: `{"template_id": "…"}`). Status **200**/**201**, never 204. | +| `return=identifier` | Just the resource identifier object: `{"uid": "…"}` (templates: `{"template_id": "…"}`). Status **200**/**201**, never 204. | Use `return=representation` when you want the server-completed object back (with its assigned version id and any server-set audit fields); use `return=minimal` @@ -268,7 +268,7 @@ version created here resolves to an `ORIGINAL_VERSION`; one this server received from another system resolves to the `IMPORTED_VERSION` that wraps it (see [Imported versions](#imported-versions)). -## `ETag` and `If-Match` — optimistic concurrency +## `ETag` and `If-Match`: optimistic concurrency openEHR objects are versioned, and updates use HTTP preconditions to prevent lost updates: @@ -292,7 +292,7 @@ A **`Location`** header is emitted only when a resource is **created**. Reads and deletes identify the version through `ETag` alone, so do not expect `Location` on them; the `ETag` is the authoritative identifier. -## `Last-Modified` — when the version was committed +## `Last-Modified`: when the version was committed Alongside the `ETag`, versioned responses carry a **`Last-Modified`** header in the standard HTTP-date form (`Wed, 22 Jul 2009 19:15:56 GMT`). Its value is the diff --git a/website/book/src/using-the-api/index.md b/website/book/src/using-the-api/index.md index b72a956b03..f54ccbc1c3 100644 --- a/website/book/src/using-the-api/index.md +++ b/website/book/src/using-the-api/index.md @@ -94,9 +94,8 @@ Two things to know before you build discovery on it: profiles, so these values are FerroEHR's own. No configuration key sets it. > [!NOTE] -> The manifest lives at the API base path and nowhere else. A bare `/` alias -> existed in earlier versions and was removed. Point discovery at the base -> path. +> The manifest lives at the API base path and nowhere else. Point discovery +> at the base path. ## Authentication @@ -121,7 +120,7 @@ means "fix your credential": | Situation | Status | What it means | |---|---|---| -| No `Authorization` header | `401` | with a `WWW-Authenticate` challenge listing the schemes this server implements, and **no** `error=` code — nothing has gone wrong yet ([RFC 6750 §3.1](https://www.rfc-editor.org/rfc/rfc6750#section-3.1)) | +| No `Authorization` header | `401` | with a `WWW-Authenticate` challenge listing the schemes this server implements, and **no** `error=` code: nothing has gone wrong yet ([RFC 6750 §3.1](https://www.rfc-editor.org/rfc/rfc6750#section-3.1)) | | Credential presented and rejected | `401` | the challenge carries `error="invalid_token"`: expired, revoked, malformed (a bearer token outside the [RFC 6750 §2.1](https://www.rfc-editor.org/rfc/rfc6750#section-2.1) `b64token` alphabet included), or simply wrong | | `Authorization` header malformed | `400` | two `Authorization` headers, or a header that is no scheme followed by a space and a credential. The server never got as far as a credential, so this is a request defect (`error="invalid_request"`) | | Authenticated, not permitted | `403` | for a bearer caller the challenge carries `error="insufficient_scope"`, naming what is missing | diff --git a/website/book/src/using-the-api/resources.md b/website/book/src/using-the-api/resources.md index 29eca933b6..37cb59075e 100644 --- a/website/book/src/using-the-api/resources.md +++ b/website/book/src/using-the-api/resources.md @@ -34,7 +34,7 @@ curl -u ferroehr:ferroehr -X POST -i \ http://localhost:8080/ferroehr/rest/openehr/v1/ehr ``` -`POST /ehr` — the body is optional; you may supply an `EHR_STATUS` to set the +`POST /ehr`: the body is optional; you may supply an `EHR_STATUS` to set the subject and flags at creation. Returns **201 Created** with the new EHR id in `ETag` and a `Location` header. With `Prefer: return=representation` the body is the full `EHR`; otherwise it is empty. Supplying an `EHR_STATUS` whose subject @@ -121,12 +121,12 @@ The `versioned_ehr_status` sub-resource exposes the full version history: - `GET …/versioned_ehr_status`: the `VERSIONED_EHR_STATUS` object, - `GET …/versioned_ehr_status/revision_history`: the revision history, - `GET …/versioned_ehr_status/version` (optionally `?version_at_time=`) and - `…/version/{version_uid}` — a specific version. + `…/version/{version_uid}`: a specific version. ## EHR_ACCESS **EHR_ACCESS** holds the record's access directives: who may reach which data, -for what, until when (the [access directives](../security.md#access-directives) +for what, until when (the [access directives](../access-control.md#access-directives) scheme). An EHR holds exactly one, versioned like `EHR_STATUS`. The openEHR REST API defines no `EHR_ACCESS` endpoint, so FerroEHR reads it through its own extension under the extensions root, with the paths, `version_at_time` and @@ -398,7 +398,7 @@ These things about the payload are worth calling out: own rules (the **422** above) apply on the direct writes as well. - **For a caller it knows, the server writes the committer.** When your login is bound to a demographic `PERSON` (see - [`[authz.party_binding]`](../installation/config-auth.md#authzparty_binding)), + [`[authz.party_binding]`](../installation/config-authz.md#authzparty_binding)), every commit, attestation and CONTRIBUTION records a `PARTY_IDENTIFIED` with the `PERSON`'s name, your login identifier (`DV_IDENTIFIER{issuer = token iss, id = , type = "oauth2"}`, or @@ -546,7 +546,7 @@ curl -u ferroehr:ferroehr -X DELETE \ case-sensitive, and AND-combined; an omitted filter constrains nothing. An EHR with no matching tag answers **200** with `[]`, never 404. - `GET|PUT /ehr/{ehr_id}/composition/{uid_based_id}/tags` and the same pair - under `…/ehr_status/{uid_based_id}/tags` — read or **replace** the addressed + under `…/ehr_status/{uid_based_id}/tags`: read or **replace** the addressed collection. The `PUT` body is a bare JSON array of tags (`key` required, `value` and `target_path` optional; `target` and `owner_id` come from the route, and a body that supplies them, or any other undeclared member, is a diff --git a/website/book/src/verifying-releases.md b/website/book/src/verifying-releases.md index 26b44737b4..aa84459a2f 100644 --- a/website/book/src/verifying-releases.md +++ b/website/book/src/verifying-releases.md @@ -12,16 +12,6 @@ checksum alongside each artifact. Provenance is signed through [Sigstore](https://www.sigstore.dev/), so you can verify it yourself, and the signer identity is one you can pin to a single hardened workflow. -The repository moved to the `FerroHEALTH` organization on 2026-10-01, and -v4.3.2 is the first release built there. Releases up to and including v4.3.1 -were built and signed while it was `rubentalstra/FerroEHR`, so their -attestations name that repository: verify them with `-R rubentalstra/FerroEHR` -and `--signer-workflow rubentalstra/FerroEHR/…`. Their images and charts were -published under `ghcr.io/rubentalstra`. The copies of v4.3.1 under -`ghcr.io/ferrohealth` carry the same digests, so `gh attestation verify` accepts -them with the old repository name. Their cosign signatures exist only beside -the originals, so run `cosign verify` against the `ghcr.io/rubentalstra` path. - ## What a release publishes @@ -129,11 +119,11 @@ gh attestation verify ferroehr---unknown-linux-gnu.tar.gz \ That workflow is the reusable release-build lane described under [SLSA levels](#what-slsa-level-each-artifact-reaches) below. -**The binary also describes itself.** From v4.0.1 on, the shipped binary +**The binary also describes itself.** The shipped binary embeds its own compressed dependency list in a `.dep-v0` linker section (built with [`cargo auditable`](https://github.com/rust-secure-code/cargo-auditable); the section is allocated, so it survives the release lane's `strip`). A -scanner that reads binaries — syft, trivy, grype, osv-scanner — recovers the +scanner that reads binaries (syft, trivy, grype, osv-scanner) recovers the crate graph from the artifact itself, even when the release page's SBOM never travelled with it: @@ -141,16 +131,13 @@ travelled with it: syft ferroehr -o cyclonedx-json # the extracted binary, not the tarball ``` -From v4.3.5 on, the binaries inside the `ferroehr` and `ferroehr-viewer` -images are built with `cargo auditable` as well, so a scan of either image -lists the Rust dependencies of the binary it carries, and the +The binaries inside the `ferroehr` and `ferroehr-viewer` images are built with +`cargo auditable` as well, so a scan of either image lists the Rust +dependencies of the binary it carries, and the [exploitability record](#the-exploitability-record) judges them per image. -Images of earlier releases carry no such list: a scan of them sees the -operating-system layer only, and the server's Rust dependencies are visible -through the tarball scan and its SBOM. ```bash -# is v4.3.5 or later, without the v +# is the release version, without the v trivy image --list-all-pkgs --format json ghcr.io/ferrohealth/ferroehr-viewer: \ | jq -r '.Results[] | select(.Type == "rustbinary") | .Packages[] | "\(.Name) \(.Version)"' ``` @@ -208,10 +195,10 @@ gh attestation verify oci://ghcr.io/ferrohealth/ferroehr:5.7.1-rc1 \ ``` > [!IMPORTANT] -> **Image tags carry no `v` prefix.** A release publishes `4.0.0`, `3.20` and -> `latest` (plus a `sha-…` tag per commit), while the release *assets* are named -> after the `v4.0.1` git tag. Using `v4.0.1` as an image reference will simply -> not resolve. +> **Image tags carry no `v` prefix.** A release publishes, for example, +> `6.0.0`, `6.0` and `latest` (plus a `sha-…` tag per commit), while the +> release *assets* are named after the `v6.0.0` git tag. `v6.0.0` as an image +> reference does not resolve. The development tags (`ghcr.io/ferrohealth/ferroehr:main` and its two siblings) are signed the same way, so you can rehearse the command against them @@ -223,7 +210,7 @@ workflow in this repository. **Verify by digest where it matters.** A tag is mutable, so anything that GATES on verification (admission control, a deploy script) should resolve the -tag once and verify the digest it resolved — otherwise the bytes verified and +tag once and verify the digest it resolved; otherwise the bytes verified and the bytes pulled can differ: ```bash @@ -336,7 +323,7 @@ chart SBOM must resolve to a `sha256` digest before the chart is pushed. The levels are the [SLSA v1.2 Build track](https://slsa.dev/spec/v1.2/build-requirements) (the current spec; v1.0 is marked Retired, and the Build-track requirements -are unchanged across those versions — GitHub's own documentation still +are unchanged across those versions; GitHub's own documentation still phrases the same construction against "SLSA v1.0"). They differ per artifact, so a table is the honest form: @@ -346,10 +333,8 @@ so a table is the honest form: | container images | **Build L3** | built, pushed and attested inside a reusable workflow (`build-image.yml`); the calling jobs pass names and label text, never steps | | the Helm chart | **Build L3** | packaged, pushed, signed and attested inside a reusable workflow (`build-chart.yml`); the caller carries only triggers | -Images and the chart reach L3 from the first publish after v4.0.1; earlier -artifacts were attested at Build L2 (in the job that built them), and their -attestations verify with the repository-scoped command, not the pinned -signer. +Older releases have their own book at `/docs//`, which says how their +artifacts verify. Build L3's distinguishing requirement is that secret material used for authenticating the provenance "MUST NOT be accessible to the environment @@ -374,7 +359,7 @@ long-lived crates.io token exists anywhere. Be precise about what that does and does not give you: it is **authentication, not provenance**. crates.io records and displays nothing about how a crate was built, and the Rust RFC that introduced Trusted Publishing lists provenance verification as -explicitly out of scope — there is no registry-side attestation to verify, +explicitly out of scope: there is no registry-side attestation to verify, from this project or any other. `cargo` checks the crate's checksum against the registry index, and that is the whole registry-side story. The crates' source of truth is this repository: the publishing lane, the tags, and the diff --git a/website/book/src/viewer/access-control.md b/website/book/src/viewer/access-control.md index 6fcde7e658..f3fd516356 100644 --- a/website/book/src/viewer/access-control.md +++ b/website/book/src/viewer/access-control.md @@ -13,7 +13,7 @@ account read. **Access policy**, in the sidebar's console group, reads the controller's `ACCESS_POLICY` in force (`GET {ext}/admin/access_policy`, see -[Operational policy](../operational-policy.md#the-access-policy)) and draws it +[The access policy](../access-policy.md#the-access-policy)) and draws it by section: - **Classifications:** which data carry which sensitivities and diff --git a/website/book/src/why-ferroehr.md b/website/book/src/why-ferroehr.md index 241d359b32..eb4857be0a 100644 --- a/website/book/src/why-ferroehr.md +++ b/website/book/src/why-ferroehr.md @@ -179,8 +179,8 @@ maintainer documents say so plainly. The same honesty covers how the code gets written: substantial parts of FerroEHR are built with AI coding tools, directed and reviewed by the maintainer, with every change held to the machine-enforced gates described -above. The full statement — what that means, what bounds it, and what you -can verify instead of trusting it — is the repository's +above. The full statement (what that means, what bounds it, and what you +can verify instead of trusting it) is the repository's [AI statement](https://github.com/FerroHEALTH/FerroEHR/blob/main/AI_STATEMENT.md). --- diff --git a/website/book/src/xshare-yellow-button.md b/website/book/src/xshare-yellow-button.md index 617f919655..c91e352509 100644 --- a/website/book/src/xshare-yellow-button.md +++ b/website/book/src/xshare-yellow-button.md @@ -73,7 +73,7 @@ login: - Only the EHR whose subject is the person's `PERSON` answers. Any other EHR is refused `403` with `refused-not-subject`. -- A composition the [access delay](security.md#delayed-access-by-the-person-ehds-art-33) +- A composition the [access delay](access-control.md#delayed-access-by-the-person-ehds-art-33) holds is left out of the summary until a professional releases it or its limit passes (EHDS Art. 3(3)). - Every read is an access record naming the person, FerroBRIDGE as the