Skip to main content

fhir_store/
lib.rs

1//! `fhir-store` — the engine-agnostic half of FHIR® persistence.
2//!
3//! Everything about storing FHIR that is **not** specific to one SQL engine:
4//! the tamper-evident audit chain, the attribution and disclosure records it
5//! commits to, and the value types every port's operations return.
6//!
7//! # Trademarks
8//!
9//! HL7®, and FHIR® are the registered trademarks of Health Level Seven
10//! International and their use of these trademarks does not constitute an
11//! endorsement by HL7.
12//!
13//! # Why this crate exists
14//!
15//! Six ports — `fhir-postgresql`, `fhir-sqlite`, `fhir-mysql`, `fhir-mariadb`,
16//! `fhir-mssql`, `fhir-oracle` — each carried their own copy of this code.
17//! `chain.rs` alone was **618 lines, byte-identical in all six**, and unlike
18//! the map and generator it was not covered by
19//! `scripts/check-shared-core.sh`: the gate watched `map/` and `gen/` and left
20//! the store's engine-agnostic half unwatched. That is why closing **F-07**
21//! (the hash-chain pre-image was derived from `jsonb`, so chains were not
22//! portable) had to be done six times by hand.
23//!
24//! What stays in a port is what genuinely differs: the driver, transactions,
25//! placeholder syntax, the search-SQL builder, and `StoreError` — which wraps
26//! that port's own `ShredError` and so cannot be lifted here.
27//!
28//! # What this crate does not do
29//!
30//! It does not authenticate. That is the perimeter's job, and this crate holds
31//! the boundary rather than crossing it (§12, `PR12.1`–`PR12.4`): "authentication
32//! is elsewhere" must not become "the record of who did what is nowhere", so
33//! the types below carry attribution and the chain makes it tamper-evident.
34//!
35//! It also opens no sockets and speaks no HTTP. The RESTful surface is
36//! `fhir-loco`.
37// Nothing here has any business dereferencing a raw pointer: this code
38// parses and reshapes untrusted clinical data, and memory safety is the
39// property that keeps a malformed resource from becoming a vulnerability.
40#![forbid(unsafe_code)]
41
42pub mod chain;
43
44use serde_json::Value;
45
46#[derive(Debug)]
47pub struct PutOutcome {
48    pub id: String,
49    pub version_id: i64,
50    pub created: bool,
51}
52
53/// Who is responsible for a change, and how we know (spec M3.15, PR12.1–4).
54///
55/// fhir does not authenticate — that is the perimeter's job (plan D13) —
56/// but "authentication is elsewhere" cannot mean "the record of who did what
57/// is nowhere" (D15). The perimeter knows the identity; only the store knows
58/// which rows were touched, so only the store can join the two.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct Audit {
61    /// The authenticated principal, or `unauthenticated`.
62    pub actor: String,
63    /// How the principal was established, e.g. `header:X-Fhir-Principal`
64    /// or `cli`. Recorded so a reader can weigh how much the actor is worth.
65    pub actor_source: Option<String>,
66    /// Source address as the server observed it.
67    pub client: Option<String>,
68    /// The value echoed in `X-Request-Id`, tying this row to the logs.
69    pub request_id: Option<String>,
70    /// Caller-supplied purpose of use.
71    pub reason: Option<String>,
72}
73
74impl Default for Audit {
75    fn default() -> Self {
76        Self::unattributed()
77    }
78}
79
80impl Audit {
81    /// A write with no identity behind it. Recorded as such rather than left
82    /// blank: "we do not know who did this" is itself an audit finding.
83    #[must_use]
84    pub fn unattributed() -> Self {
85        Audit {
86            actor: "unauthenticated".to_string(),
87            actor_source: None,
88            client: None,
89            request_id: None,
90            reason: None,
91        }
92    }
93
94    /// A write by the operator running the CLI on this host.
95    #[must_use]
96    pub fn cli() -> Self {
97        Self::cli_as(std::env::var("USER").ok(), std::env::var("USERNAME").ok())
98    }
99
100    /// [`Self::cli`] given `USER` and `USERNAME`: the first present wins.
101    fn cli_as(user: Option<String>, username: Option<String>) -> Self {
102        // RCA-IN-3: absent only (no USER/USERNAME: the actor is "unknown")
103        let who = user.or(username).unwrap_or_else(|| "unknown".to_string());
104        Audit {
105            actor: format!("cli:{who}"),
106            actor_source: Some("cli".to_string()),
107            client: None,
108            request_id: None,
109            reason: None,
110        }
111    }
112
113    /// A write attributed to a principal the perimeter vouched for.
114    #[must_use]
115    pub fn principal(actor: impl Into<String>, source: impl Into<String>) -> Self {
116        Audit {
117            actor: actor.into(),
118            actor_source: Some(source.into()),
119            client: None,
120            request_id: None,
121            reason: None,
122        }
123    }
124
125    #[must_use]
126    pub fn with_client(mut self, client: Option<String>) -> Self {
127        self.client = client;
128        self
129    }
130
131    #[must_use]
132    pub fn with_request_id(mut self, request_id: Option<String>) -> Self {
133        self.request_id = request_id;
134        self
135    }
136
137    #[must_use]
138    pub fn with_reason(mut self, reason: Option<String>) -> Self {
139        self.reason = reason;
140        self
141    }
142}
143
144/// One disclosure record (spec PR12.5).
145#[derive(Debug, Clone)]
146pub struct AccessRecord {
147    pub audit: Audit,
148    /// `read`, `vread`, `history`, `search`, `export`.
149    pub interaction: String,
150    pub rtype: Option<String>,
151    pub id: Option<String>,
152    pub version_id: Option<i64>,
153    /// `ok`, `not-found`, `denied`, `error`.
154    pub outcome: String,
155    pub result_count: Option<i64>,
156}
157
158/// What an erasure removed (spec M3.18).
159#[derive(Debug, PartialEq, Eq)]
160pub struct PurgeReport {
161    /// History rows removed, not counting the tombstone left behind.
162    pub versions_erased: u64,
163    /// Whether the resource was known at all.
164    pub existed: bool,
165}
166
167/// A break in one resource's hash chain (spec M3.16, M3.16a).
168///
169/// One break per algorithm, never merged: a regime that recognises only
170/// SHA-3 must be able to see the SHA-3 verdict on its own, and a break that
171/// appears under one algorithm but not the other is itself worth seeing —
172/// it means the stored digests disagree about the same bytes.
173/// `#[non_exhaustive]` so that a future algorithm or field is a patch, not a
174/// break: adding a public field to a struct callers can build or destructure
175/// exhaustively is a breaking change, and this type gained `algorithm`
176/// exactly that way.
177#[non_exhaustive]
178#[derive(Debug, Clone)]
179pub struct ChainBreak {
180    pub rtype: String,
181    pub id: String,
182    pub version_id: i64,
183    /// `"sha256"` or `"sha3-256"`.
184    pub algorithm: &'static str,
185    pub detail: String,
186}
187
188impl ChainBreak {
189    /// Record a break.
190    ///
191    /// A constructor rather than a struct literal because this type is
192    /// `#[non_exhaustive]`: it gained `algorithm` after release, and keeping
193    /// that freedom is the point. A literal can only be written inside this
194    /// crate, and the ports that detect breaks are outside it, so without this
195    /// they would have to choose between constructing the type and keeping the
196    /// guarantee.
197    #[must_use]
198    pub fn new(
199        rtype: impl Into<String>,
200        id: impl Into<String>,
201        version_id: i64,
202        algorithm: &'static str,
203        detail: impl Into<String>,
204    ) -> Self {
205        Self {
206            rtype: rtype.into(),
207            id: id.into(),
208            version_id,
209            algorithm,
210            detail: detail.into(),
211        }
212    }
213}
214
215#[derive(Debug)]
216pub struct UpgradeReport {
217    pub additive: usize,
218    pub destructive: usize,
219    /// Distinct string values folded into new search columns (P6.6).
220    pub folded: usize,
221    /// Resources carried across a table-shape change by the `O10.4c`
222    /// re-shred migration: reconstructed under the stored old map, shredded
223    /// under the new, verified byte-identical. Zero on every upgrade that
224    /// relocated nothing.
225    pub reshredded: usize,
226}
227
228/// Options for `upgrade_with`.
229#[derive(Debug, Clone, Copy, Default)]
230pub struct UpgradeOpts {
231    /// Acknowledge genuinely destructive changes (`O10.4`): dropped tables,
232    /// dropped columns whose element left the map.
233    pub allow_destructive: bool,
234    /// Carry data across relocated columns by re-shredding each affected
235    /// resource (`O10.4c`) instead of refusing the move (`O10.4b`). The
236    /// drops that remain still require `allow_destructive`.
237    pub reshred_moved: bool,
238}
239
240#[derive(Debug)]
241pub struct SearchOutcome {
242    pub ids: Vec<String>,
243    pub total: Option<i64>,
244}
245
246/// The result of a conditional create (`If-None-Exist`).
247#[derive(Debug)]
248pub enum CondCreate {
249    /// No match: the resource was created.
250    Created(PutOutcome),
251    /// Exactly one match: it is returned unchanged, per FHIR.
252    Existing(String),
253    /// More than one match: the criteria are not selective enough (412).
254    Multiple,
255}
256
257/// The result of a conditional delete.
258#[derive(Debug, PartialEq, Eq)]
259pub enum CondDelete {
260    Deleted,
261    NoMatch,
262    Multiple,
263}
264
265#[derive(Debug)]
266pub struct Got {
267    pub resource: Value,
268    pub version_id: i64,
269}
270
271/// One write inside a FHIR transaction Bundle.
272#[derive(Debug)]
273pub enum TxOp {
274    Put {
275        resource: Value,
276        expected: Option<i64>,
277    },
278    Delete {
279        rtype: String,
280        id: String,
281    },
282}
283
284#[derive(Debug)]
285pub enum TxOutcome {
286    Put(PutOutcome),
287    Delete(bool),
288}
289
290#[derive(Debug, PartialEq, Eq)]
291pub enum ResourceStatus {
292    Active(i64),
293    /// Deleted; carries the delete marker's version.
294    Deleted(i64),
295    Unknown,
296}
297
298#[derive(Debug)]
299pub struct HistEntry {
300    pub version_id: i64,
301    pub last_updated: String,
302    /// 'C' create, 'U' update, 'D' delete.
303    pub op: char,
304    pub resource: Option<Value>,
305}
306
307#[cfg(test)]
308mod tests {
309    use super::Audit;
310
311    /// `USER` wins over `USERNAME`; with neither, the actor is
312    /// `cli:unknown` rather than an empty or invented name.
313    #[test]
314    fn cli_actor_prefers_user_then_username_then_unknown() {
315        let a = Audit::cli_as(Some("u".into()), Some("n".into()));
316        assert_eq!(a.actor, "cli:u");
317        assert_eq!(a.actor_source.as_deref(), Some("cli"));
318        assert_eq!(Audit::cli_as(None, Some("n".into())).actor, "cli:n");
319        assert_eq!(Audit::cli_as(None, None).actor, "cli:unknown");
320    }
321}