ihe-atna 0.4.0

The IHE audit trail in Rust: the ATNA Record Audit Event sender (ITI-20) with the DICOM audit message, syslog over TLS, a store-and-forward spool and a forwarder, and the BALP AuditEvent sent over the ATX: FHIR Feed
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
// SPDX-FileCopyrightText: Cadasto B.V.
// SPDX-License-Identifier: BUSL-1.1

//! BALP, the IHE Basic Audit Log Patterns 1.1.4 (feature `balp`): the FHIR R4
//! `AuditEvent` an IHE FHIR transaction is audited as.
//!
//! PIXm, mCSD, PDQm and PMIR each define the audit record of their
//! transactions as an `AuditEvent` profile built on a BALP pattern (PIXm
//! §2:3.83.5.1, mCSD §2:3.90.5.1 and §2:3.91.5.1, PDQm §2:3.78.5.1, PMIR
//! §2:3.93.5.1 and §2:3.94.5.1). A client of those profiles that is
//! [audited](AuditRecorder) hands its recorder one [`Exchange`] per
//! transaction: what the transaction's audit profile fixes ([`EventKind`]),
//! the outcome, the other party, whom the exchange was made for
//! ([`OnBehalfOf`]), and the entities the event concerned.
//! [`Exchange::audit_event`] writes the `AuditEvent` with the
//! [`Observer`] that records it, the system the client runs on, which the
//! client does not know.
//!
//! BALP has its Audit Creator send the record over the ATNA ATX: FHIR Feed
//! Option (BALP §1:52.1.1.1; ITI TF-1 §9.2.7.1 as the `RESTful` ATNA supplement
//! adds it), the `create` of ITI-20 §3.20.4.2 that
//! [`crate::atna::feed`] makes.
//!
//! An `Exchange` may name a patient, in a [`Entity::Patient`] identifier or
//! inside the search request of an [`Entity::Query`], as the audit profiles
//! require: every such value is a [`SecretString`], `Debug` redacts it, and
//! the written record is an [`AuditRecord`], whose bytes `Debug` never shows.
//! A recorder that logs an exchange must leave them out. An `Exchange` made
//! for a user names them too, as the audit record names its requestor (PIXm
//! §2:3.83.5.2.1): `Debug` shows none of the user's values, and a recorder
//! sends them to its Audit Record Repository alone.

use std::borrow::Cow;
use std::fmt;
use std::net::IpAddr;

pub mod recording;
mod write;

use fhir_types::r4::coding::Coding;
use fhir_types::r4::primitives;
use fhir_types::r4::schema::SCHEMAS;
use jiff::Timestamp;
use secrecy::{SecretSlice, SecretString};
use url::Url;

use crate::redact::{REDACTED, RedactedUrl};
use crate::user::OnBehalfOf;

/// A coding: its `system`, `code` and `display`, each fixed text, such as a
/// code a profile fixes, or text known only when the exchange is made, such
/// as an operation id.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Coded {
    /// `system`.
    pub system: Cow<'static, str>,
    /// `code`.
    pub code: Cow<'static, str>,
    /// `display`.
    pub display: Cow<'static, str>,
}

impl Coded {
    /// The coding of fixed text, as the constants of this module are.
    #[must_use]
    pub const fn fixed(system: &'static str, code: &'static str, display: &'static str) -> Self {
        Self {
            system: Cow::Borrowed(system),
            code: Cow::Borrowed(code),
            display: Cow::Borrowed(display),
        }
    }

    /// The coding of `code` in `system`, displayed as `display`.
    #[must_use]
    pub fn new(
        system: impl Into<String>,
        code: impl Into<String>,
        display: impl Into<String>,
    ) -> Self {
        Self {
            system: Cow::Owned(system.into()),
            code: Cow::Owned(code.into()),
            display: Cow::Owned(display.into()),
        }
    }

    fn coding(&self) -> Coding {
        Coding {
            system: Some(primitives::Uri::from(self.system.as_ref())),
            code: Some(primitives::Code::from(self.code.as_ref())),
            display: Some(primitives::String::from(self.display.as_ref())),
            ..Coding::default()
        }
    }
}

/// The code system of IHE transaction codes, the `urn:ihe:event-type-code`
/// subtype every IHE audit profile adds.
pub const IHE_TRANSACTIONS: &str = "urn:ihe:event-type-code";

/// `AuditEvent.type` of every `RESTful` pattern: `rest`
/// (`IHE.BasicAudit.Query`, `.Read`, `.Create`, `.Delete`).
pub const REST: Coded = Coded::fixed(
    "http://terminology.hl7.org/CodeSystem/audit-event-type",
    "rest",
    "Restful Operation",
);

/// The agent type of the side the request flows from: DICOM `110153`.
pub const SOURCE_ROLE: Coded = Coded::fixed(
    "http://dicom.nema.org/resources/ontology/DCM",
    "110153",
    "Source Role ID",
);

/// The agent type of the side the request flows to: DICOM `110152`.
pub const DESTINATION_ROLE: Coded = Coded::fixed(
    "http://dicom.nema.org/resources/ontology/DCM",
    "110152",
    "Destination Role ID",
);

/// The client's agent type of the Delete pattern: DICOM `110150`
/// (`IHE.BasicAudit.Delete`, `agent:client.type`).
pub const APPLICATION: Coded = Coded::fixed(
    "http://dicom.nema.org/resources/ontology/DCM",
    "110150",
    "Application",
);

/// The agent type of the user an exchange is made for: `IRCP`, as every
/// BALP pattern's `agent:user` slice fixes it.
pub const INFORMATION_RECIPIENT: Coded = Coded::fixed(
    "http://terminology.hl7.org/CodeSystem/v3-ParticipationType",
    "IRCP",
    "information recipient",
);

/// The server's agent type of the Delete pattern: `custodian`
/// (`IHE.BasicAudit.Delete`, `agent:server.type`).
pub const CUSTODIAN: Coded = Coded::fixed(
    "http://terminology.hl7.org/CodeSystem/provenance-participant-type",
    "custodian",
    "Custodian",
);

/// The `restful-interaction` subtype `search` (`IHE.BasicAudit.Query`,
/// `subtype:anySearch`).
pub const SEARCH: Coded = Coded::fixed(
    "http://hl7.org/fhir/restful-interaction",
    "search",
    "search",
);

/// The `restful-interaction` subtype `read` (`IHE.BasicAudit.Read`).
pub const READ: Coded = Coded::fixed("http://hl7.org/fhir/restful-interaction", "read", "read");

/// The `restful-interaction` subtype `create` (`IHE.BasicAudit.Create`,
/// `subtype:anyCreate`).
pub const CREATE: Coded = Coded::fixed(
    "http://hl7.org/fhir/restful-interaction",
    "create",
    "create",
);

/// The `restful-interaction` subtype `update`, of the implementation guide's
/// `AllUpdateVS` (BALP 1.1.4 lists `IHE.BasicAudit.Update` beside the other
/// `RESTful` patterns).
pub const UPDATE: Coded = Coded::fixed(
    "http://hl7.org/fhir/restful-interaction",
    "update",
    "update",
);

/// The `restful-interaction` subtype `delete` (`IHE.BasicAudit.Delete`,
/// `subtype:anyDelete`).
pub const DELETE: Coded = Coded::fixed(
    "http://hl7.org/fhir/restful-interaction",
    "delete",
    "delete",
);

/// The `restful-interaction` subtype `history-type` (the mCSD Updates audit
/// profile, `subtype:anyHistoryT`).
pub const HISTORY_TYPE: Coded = Coded::fixed(
    "http://hl7.org/fhir/restful-interaction",
    "history-type",
    "history-type",
);

/// The entity type of a system object: `2` (`audit-entity-type`).
pub const SYSTEM_OBJECT: Coded = Coded::fixed(
    "http://terminology.hl7.org/CodeSystem/audit-entity-type",
    "2",
    "System Object",
);

/// The entity type of anything else: `4` (`audit-entity-type`). No slice of
/// a BALP pattern is discriminated by it, so an entity of this type adds to
/// a record without filling a slice the pattern bounds.
pub const OTHER: Coded = Coded::fixed(
    "http://terminology.hl7.org/CodeSystem/audit-entity-type",
    "4",
    "Other",
);

/// The entity type of the request id, `XrequestId` (`BasicAuditEntityType`),
/// as every `RESTful` pattern's `entity:transaction` slice fixes it.
pub const REQUEST_ID: Coded = Coded::fixed(
    "https://profiles.ihe.net/ITI/BALP/CodeSystem/BasicAuditEntityType",
    "XrequestId",
    "X-Request-Id",
);

/// The entity type of a person: `1` (`audit-entity-type`).
pub const PERSON: Coded = Coded::fixed(
    "http://terminology.hl7.org/CodeSystem/audit-entity-type",
    "1",
    "Person",
);

/// The entity role of a search: `24` (`object-role`).
pub const QUERY_ROLE: Coded = Coded::fixed(
    "http://terminology.hl7.org/CodeSystem/object-role",
    "24",
    "Query",
);

/// The entity role of a resource: `4` (`object-role`), as the BALP and
/// PMIR examples give a resource acted on.
pub const DOMAIN_RESOURCE: Coded = Coded::fixed(
    "http://terminology.hl7.org/CodeSystem/object-role",
    "4",
    "Domain Resource",
);

/// The entity role of a patient: `1` (`object-role`).
pub const PATIENT_ROLE: Coded = Coded::fixed(
    "http://terminology.hl7.org/CodeSystem/object-role",
    "1",
    "Patient",
);

/// The DICOM controlled terminology, the system of the DICOM event codes.
pub const DCM: &str = "http://dicom.nema.org/resources/ontology/DCM";

/// `AuditEvent.type` of a log on or log off: DICOM `110114` (DICOM PS3.15
/// Table A.5.3.12-1, User Authentication).
pub const USER_AUTHENTICATION: Coded = Coded::fixed(DCM, "110114", "User Authentication");

/// The subtype of a log on: DICOM `110122` (DICOM PS3.15 Table A.5.3.12-1).
pub const LOGIN: Coded = Coded::fixed(DCM, "110122", "Login");

/// The subtype of a log off: DICOM `110123` (DICOM PS3.15 Table A.5.3.12-1).
pub const LOGOUT: Coded = Coded::fixed(DCM, "110123", "Logout");

/// `AuditEvent.type` of data leaving the system: DICOM `110106` (DICOM PS3.15
/// Table A.5.3.4-1, Data Export).
pub const EXPORT: Coded = Coded::fixed(DCM, "110106", "Export");

/// `AuditEvent.type` of data entering the system: DICOM `110107` (DICOM
/// PS3.15 Table A.5.3.5-1, Data Import).
pub const IMPORT: Coded = Coded::fixed(DCM, "110107", "Import");

/// The `restful-interaction` subtype `operation`, an operation that is no
/// read, write or search (FHIR R4 `restful-interaction`).
pub const OPERATION: Coded = Coded::fixed(
    "http://hl7.org/fhir/restful-interaction",
    "operation",
    "operation",
);

/// The code system of `AuditEvent.source.type` (FHIR R4).
///
/// FHIR R4 `security-source-type`, which the `RESTful` ATNA mapping carries
/// to and from the DICOM `AuditSourceTypeCode` (`RESTful` ATNA Rev. 3.6
/// Table 3.20.4.2.2.1-1).
pub const SECURITY_SOURCE_TYPE: &str = "http://terminology.hl7.org/CodeSystem/security-source-type";

/// `source.type` `1`, an end-user display device or diagnostic device.
pub const SOURCE_USER_DEVICE: Coded = Coded::fixed(SECURITY_SOURCE_TYPE, "1", "User Device");

/// `source.type` `2`, a data acquisition device or instrument.
pub const SOURCE_DATA_INTERFACE: Coded = Coded::fixed(SECURITY_SOURCE_TYPE, "2", "Data Interface");

/// `source.type` `3`, a web server process or thread.
pub const SOURCE_WEB_SERVER: Coded = Coded::fixed(SECURITY_SOURCE_TYPE, "3", "Web Server");

/// `source.type` `4`, an application server process or thread.
pub const SOURCE_APPLICATION_SERVER: Coded =
    Coded::fixed(SECURITY_SOURCE_TYPE, "4", "Application Server");

/// `source.type` `5`, a database server process or thread.
pub const SOURCE_DATABASE_SERVER: Coded =
    Coded::fixed(SECURITY_SOURCE_TYPE, "5", "Database Server");

/// `source.type` `6`, a security server, such as a domain controller.
pub const SOURCE_SECURITY_SERVER: Coded =
    Coded::fixed(SECURITY_SOURCE_TYPE, "6", "Security Server");

/// `source.type` `7`, an ISO level 1 to 3 network component.
pub const SOURCE_NETWORK_DEVICE: Coded = Coded::fixed(SECURITY_SOURCE_TYPE, "7", "Network Device");

/// `source.type` `8`, ISO level 4 to 6 operating software.
pub const SOURCE_NETWORK_ROUTER: Coded = Coded::fixed(SECURITY_SOURCE_TYPE, "8", "Network Router");

/// `source.type` `9`, any other source.
pub const SOURCE_OTHER: Coded = Coded::fixed(SECURITY_SOURCE_TYPE, "9", "Other");

/// The BALP pattern of an OAuth access token's Comprehensive use.
///
/// Its recorder reads every field of the token; a record claims it when it
/// names the token's `jti` and its client (BALP 1.1.4 §3:5.7.5.4), and its
/// user acts under no other policy, because the pattern fixes
/// `agent:oUser.policy` to the one `jti`.
pub const OAUTH_COMPREHENSIVE: &str = "https://profiles.ihe.net/ITI/BALP/StructureDefinition/IHE.BasicAudit.OAUTHaccessTokenUse.Comprehensive";

/// The `detail` name of the namespace a patient identifier was issued in,
/// when that namespace is no URI (no specification governs the name: our own
/// design).
pub const PATIENT_NAMESPACE: &str = "namespace";

/// What a transaction's audit profile fixes of its records.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EventKind {
    /// The audit profile's canonical URL, written to `meta.profile`; empty
    /// for a record that claims no profile, such as a failed `delete`, which
    /// the Delete pattern, fixing `outcome` to `0`, does not describe.
    pub profile: &'static str,
    /// `type`.
    pub event_type: Coded,
    /// `subtype`, in order: the codes the pattern fixes, then any the
    /// exchange adds, such as an operation id, which the open `subtype`
    /// slicing of every BALP `RESTful` pattern admits.
    pub subtypes: Vec<Coded>,
    /// `action`: `C`, `R`, `U`, `D` or `E`.
    pub action: &'static str,
    /// The type of the agent the request flows from (`agent:client` of a
    /// BALP pattern).
    pub client: Coded,
    /// The type of the agent the request flows to (`agent:server`).
    pub server: Coded,
}

/// How an exchange ended, as `AuditEvent.outcome` codes it (FHIR R4
/// `audit-event-outcome`).
///
/// The codes leave the meaning of a failure to the recording application;
/// an answer and its absence are told apart (no specification governs the
/// choice: our own design, the one the ITI-55 audit message makes).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Outcome {
    /// `0`, success: the answer was read as the transaction's answer.
    Success,
    /// `4`, minor failure: the other party answered with a failure, or with
    /// an answer that does not hold to the transaction.
    MinorFailure,
    /// `8`, serious failure: no answer arrived.
    SeriousFailure,
    /// `12`, major failure: the recording application is now unavailable
    /// (FHIR R4 `audit-event-outcome`; DICOM PS3.15 A.5.1
    /// `EventOutcomeIndicator`).
    MajorFailure,
}

impl Outcome {
    /// The `outcome` code.
    #[must_use]
    pub fn code(self) -> &'static str {
        match self {
            Self::Success => "0",
            Self::MinorFailure => "4",
            Self::SeriousFailure => "8",
            Self::MajorFailure => "12",
        }
    }
}

/// An agent's `network`: its address and the `network.type` code
/// (`network-type`: `1` a machine name, `2` an IP address, `5` a URI).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum NetworkAddress {
    /// A machine (DNS) name, type `1`.
    MachineName(String),
    /// An IP address, type `2`.
    Ip(IpAddr),
    /// A URI, type `5`, without its userinfo, query or fragment.
    Uri(Url),
}

impl NetworkAddress {
    /// The address of `host`: an IP address when it reads as one, and a
    /// machine name otherwise.
    #[must_use]
    pub fn host(host: &str) -> Self {
        host.parse::<IpAddr>()
            .map_or_else(|_| Self::MachineName(host.to_owned()), Self::Ip)
    }

    /// The address of the URI `url`, with its userinfo, query and fragment
    /// left out: a FHIR base or an endpoint names no patient.
    #[must_use]
    pub fn uri(url: &Url) -> Self {
        Self::Uri(bare(url))
    }

    /// `network.type`.
    #[must_use]
    pub fn type_code(&self) -> &'static str {
        match self {
            Self::MachineName(_) => "1",
            Self::Ip(_) => "2",
            Self::Uri(_) => "5",
        }
    }

    /// `network.address`.
    #[must_use]
    pub fn address(&self) -> String {
        match self {
            Self::MachineName(name) => name.clone(),
            Self::Ip(address) => address.to_string(),
            Self::Uri(url) => url.to_string(),
        }
    }
}

/// The request `url` as an audit record writes it in a query entity: its
/// query kept, since that is the search, and its userinfo left out.
#[must_use]
pub fn request_text(url: &Url) -> SecretString {
    let mut shown = url.clone();
    // NOTE: url::Url::set_username and set_password fail only for a URL that
    // cannot carry userinfo, which then has none to remove.
    let _cleared: Result<(), ()> = shown.set_username("");
    let _cleared: Result<(), ()> = shown.set_password(None);
    shown.set_fragment(None);
    SecretString::from(String::from(shown))
}

/// `url` without its userinfo, query and fragment.
fn bare(url: &Url) -> Url {
    let mut shown = url.clone();
    // NOTE: url::Url::set_username and set_password fail only for a URL that
    // cannot carry userinfo, which then has none to remove.
    let _cleared: Result<(), ()> = shown.set_username("");
    let _cleared: Result<(), ()> = shown.set_password(None);
    shown.set_query(None);
    shown.set_fragment(None);
    shown
}

/// A party to an exchange other than the recording system.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Peer {
    /// `agent.who.display`: how the party is known.
    pub who: String,
    /// `agent.network`.
    pub network: NetworkAddress,
}

impl Peer {
    /// The FHIR server at `base`: named and addressed by the URL, without
    /// its userinfo, query or fragment, as the profiles' examples name a
    /// server.
    #[must_use]
    pub fn server(base: &Url) -> Self {
        let shown = bare(base);
        Self {
            who: shown.to_string(),
            network: NetworkAddress::Uri(shown),
        }
    }
}

/// The recording system's part in the exchange.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Direction {
    /// The recording system sent the request to `server`: it is the agent
    /// the request flows from.
    Sent {
        /// The agent the request flows to.
        server: Peer,
    },
    /// `client` sent the request to the recording system, at `endpoint`: the
    /// recording system is the agent the request flows to.
    Received {
        /// The agent the request flows from.
        client: Peer,
        /// The recording system's address the request arrived at: the base
        /// URL it serves, or its host or IP address when it knows only that
        /// (FHIR R4 `network-type`).
        endpoint: NetworkAddress,
    },
}

/// An entity an exchange concerned.
#[derive(Clone)]
#[non_exhaustive]
pub enum Entity {
    /// The request as sent (`entity:query`, BALP Query): type `2`, role
    /// `24`, the request written base64-encoded to `query`. A search request
    /// may name a patient.
    Query(SecretString),
    /// A patient, by an identifier (`entity:patient`): type `1`, role `1`,
    /// the identifier in `what.identifier`.
    Patient {
        /// `what.identifier.system`, a URI (FHIR R4 `Identifier.system`), when
        /// the identifier names one.
        system: Option<String>,
        /// `what.identifier.value`.
        value: SecretString,
        /// The namespace the identifier was issued in, when it is no URI and
        /// so cannot be its `system`, written as a `detail` named
        /// [`PATIENT_NAMESPACE`].
        namespace: Option<String>,
    },
    /// A patient, by a literal reference such as `Patient/<id>`
    /// (`entity:patient`): type `1`, role `1`, the reference in
    /// `what.reference`.
    PatientReference(SecretString),
    /// A resource the exchange acted on (`entity:data` of BALP Read, Create
    /// and Delete, or a profile's own slice): `what`, `type`, `role` when
    /// the profile fixes one, `name` and `query`.
    Resource {
        /// `what.reference`, a literal reference that names no patient, or
        /// `None` when the resource has no id to name, as a create that
        /// failed has none.
        reference: Option<String>,
        /// `what.type`, the resource type.
        resource_type: &'static str,
        /// `type`.
        kind: Coded,
        /// `role`.
        role: Option<Coded>,
        /// `name`.
        name: Option<&'static str>,
        /// `query`, written base64-encoded: text that names no patient,
        /// such as a subscription's criteria.
        query: Option<String>,
    },
    /// An entity the recording system describes beyond its pattern's
    /// slices, with its `detail` entries: see [`Described`].
    Described(Described),
}

/// An entity named by a reference or an identifier, with free details
/// (`entity.detail`): what a record carries beside the slices its pattern
/// fixes.
///
/// A value may say more of a patient than an id should, so `Debug` shows the
/// entity's type, role and detail names, never a value.
#[derive(Clone)]
pub struct Described {
    /// `what`, when the entity has something to name it by.
    pub what: Option<What>,
    /// `type`.
    pub kind: Coded,
    /// `role`.
    pub role: Option<Coded>,
    /// `name`.
    pub name: Option<String>,
    /// `description`.
    pub description: Option<String>,
    /// `detail`, in order, each a `valueString`.
    pub details: Vec<Detail>,
    /// `securityLabel`, in order.
    pub security_labels: Vec<SecurityLabel>,
}

/// What a [`Described`] entity names.
#[derive(Clone)]
#[non_exhaustive]
pub enum What {
    /// `what.reference`, with `what.type` when the type is known.
    ///
    /// The reference is a literal one, which [`is_literal_reference`] holds
    /// to the FHIR R4 form; an object no FHIR server makes available is an
    /// [`Identifier`](Self::Identifier).
    Reference {
        /// `what.reference`.
        reference: String,
        /// `what.type`.
        resource_type: Option<String>,
    },
    /// `what.identifier`.
    Identifier {
        /// `what.identifier.system`.
        system: Option<String>,
        /// `what.identifier.value`.
        value: String,
    },
}

/// Whether `reference` has the form FHIR R4 gives a literal reference
/// (`Reference.reference`, references.html §2.3.0.2).
///
/// That is a relative URL `[type]/[id]`, with `/_history/[vid]` when it
/// names a version, whose type is an R4 resource type and whose id and
/// version are each an R4 `id` (1 to 64 of `A-Z`, `a-z`, `0-9`, `-` and
/// `.`), or an absolute `http` or `https` URL.
///
/// An id that is neither, such as an openEHR version uid, is no location a
/// FHIR server resolves, and FHIR R4 names such an object by
/// `Reference.identifier` (references.html §2.3.0.3): [`What::Identifier`].
/// A local reference to a contained resource (`#id`) is no literal reference
/// here, since an `AuditEvent` entity contains none (invariant `ref-1`).
#[must_use]
pub fn is_literal_reference(reference: &str) -> bool {
    match Url::parse(reference) {
        Ok(url) => matches!(url.scheme(), "http" | "https") && url.has_host(),
        Err(_) => is_relative_reference(reference),
    }
}

/// Whether `reference` is `[type]/[id]` or `[type]/[id]/_history/[vid]` of an
/// R4 resource type (FHIR R4 references.html §2.3.0.2).
fn is_relative_reference(reference: &str) -> bool {
    let mut segments = reference.split('/');
    let (Some(resource_type), Some(id)) = (segments.next(), segments.next()) else {
        return false;
    };
    if !SCHEMAS.is_resource(resource_type) || !is_id(id) {
        return false;
    }
    match (segments.next(), segments.next(), segments.next()) {
        (None, _, _) => true,
        (Some("_history"), Some(version), None) => is_id(version),
        _ => false,
    }
}

/// Whether `value` is a FHIR R4 `id`: 1 to 64 of `A-Z`, `a-z`, `0-9`, `-`
/// and `.` (FHIR R4 datatypes.html#id).
fn is_id(value: &str) -> bool {
    (1..=64).contains(&value.len())
        && value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'.')
}

/// A security label: the `Coding` a record or one of its entities is
/// labelled with, so the repository that holds the record can decide who
/// reads it.
///
/// A record writes its labels to `meta.security`, the "security labels
/// applied to this resource", which "connect specific resources to the overall
/// security policy and infrastructure" (FHIR R4 `Meta.security`, as
/// `fhir_types::r4::meta::Meta::security` documents it), and an entity to
/// `entity.securityLabel`, which the `RESTful` ATNA mapping carries to and from
/// the DICOM `ParticipantObjectSensitivity` (`RESTful` ATNA Rev. 3.6
/// Table 3.20.4.2.2.1-1).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SecurityLabel {
    /// `system`.
    pub system: String,
    /// `version`, when the system's version is known.
    pub version: Option<String>,
    /// `code`.
    pub code: String,
}

/// One `entity.detail`: its `type` and its `valueString`.
#[derive(Clone)]
pub struct Detail {
    /// `type`, the name of the detail.
    pub kind: String,
    /// `valueString`.
    pub value: String,
}

impl Detail {
    /// The detail `kind` with the value `value`.
    #[must_use]
    pub fn new(kind: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            kind: kind.into(),
            value: value.into(),
        }
    }
}

impl fmt::Debug for Described {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let details: Vec<&str> = self
            .details
            .iter()
            .map(|detail| detail.kind.as_str())
            .collect();
        f.debug_struct("Described")
            .field("what", &self.what)
            .field("kind", &self.kind)
            .field("role", &self.role)
            .field("details", &details)
            .field("security_labels", &self.security_labels)
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for What {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Reference { .. } => f.debug_tuple("Reference").field(&REDACTED).finish(),
            Self::Identifier { .. } => f.debug_tuple("Identifier").field(&REDACTED).finish(),
        }
    }
}

impl fmt::Debug for Detail {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Detail")
            .field("kind", &self.kind)
            .field("value", &REDACTED)
            .finish()
    }
}

impl fmt::Debug for Entity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Query(_) => f.debug_tuple("Query").field(&REDACTED).finish(),
            Self::PatientReference(_) => {
                f.debug_tuple("PatientReference").field(&REDACTED).finish()
            }
            Self::Patient {
                system, namespace, ..
            } => f
                .debug_struct("Patient")
                .field("system", system)
                .field("value", &REDACTED)
                .field("namespace", namespace)
                .finish(),
            Self::Resource {
                reference,
                resource_type,
                kind,
                role,
                name,
                query,
            } => f
                .debug_struct("Resource")
                .field("reference", reference)
                .field("resource_type", resource_type)
                .field("kind", kind)
                .field("role", role)
                .field("name", name)
                .field("query", query)
                .finish(),
            Self::Described(described) => described.fmt(f),
        }
    }
}

/// One exchange as the transaction knows it; the [`Observer`] that records
/// it is added by [`Exchange::audit_event`].
///
/// An exchange made for a [`User`](crate::user::User) names them in two agents, as BALP 1.1.4
/// §3:5.7.5.4 maps an OAuth token's fields: the `agent:user` slice every BALP
/// pattern has (`0..1`) with the token's `iss`, `sub` and purposes of use,
/// and the user's name, provider identifier, roles and assurance level when
/// they are known, and an Application agent with its `client_id`. One the system makes on
/// its own behalf names neither. The Delete pattern admits one `110150`
/// agent, its own `agent:client`, so an exchange whose client is of that type
/// names the user's application there alone. A user's organisation, when
/// named, is an agent of its own.
#[derive(Clone)]
pub struct Exchange {
    /// What the transaction's audit profile fixes.
    pub kind: EventKind,
    /// `recorded`: when the exchange ended.
    pub recorded: Timestamp,
    /// `outcome`.
    pub outcome: Outcome,
    /// `outcomeDesc`, a free text description of the outcome (FHIR R4
    /// `AuditEvent.outcomeDesc`), when the system gives one.
    pub outcome_description: Option<String>,
    /// The recording system's part, and the other party.
    pub direction: Direction,
    /// Whom the exchange was made for.
    pub on_behalf: OnBehalfOf,
    /// `entity`, in order.
    pub entities: Vec<Entity>,
    /// `meta.security`, in order: the labels the record as a whole carries.
    pub security: Vec<SecurityLabel>,
}

impl fmt::Debug for Exchange {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let direction = match &self.direction {
            Direction::Sent { server } => format!("sent to {:?}", RedactedUrl(&server.who)),
            Direction::Received { endpoint, .. } => {
                format!("received at {:?}", RedactedUrl(&endpoint.address()))
            }
        };
        f.debug_struct("Exchange")
            .field("profile", &self.kind.profile)
            .field("recorded", &self.recorded)
            .field("outcome", &self.outcome)
            .field("outcome_description", &self.outcome_description.is_some())
            .field("direction", &direction)
            .field("on_behalf", &self.on_behalf)
            .field("entities", &self.entities)
            .field("security", &self.security)
            .finish()
    }
}

/// The system that records an exchange: `source` and its own agent.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Observer {
    /// `source.observer.display`, and the `who.display` of the recording
    /// system's agent.
    pub source_id: String,
    /// `source.site`, when the deployment names one.
    pub site: Option<String>,
    /// The recording system's `network` when it sends a request.
    pub host: NetworkAddress,
    /// `source.type`, in order, such as [`SOURCE_APPLICATION_SERVER`].
    pub source_types: Vec<Coded>,
}

/// One written `AuditEvent`, FHIR JSON (ITI TF-2 Appendix Z.6), held as a
/// secret: it may name a patient.
pub struct AuditRecord(SecretSlice<u8>);

impl AuditRecord {
    /// The JSON bytes.
    #[must_use]
    pub fn into_bytes(self) -> SecretSlice<u8> {
        self.0
    }
}

impl fmt::Debug for AuditRecord {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("AuditRecord").field(&REDACTED).finish()
    }
}

/// One written `AuditEvent` as a JSON value, for a caller that stores the
/// record as JSON rather than as bytes; it may name a patient, so `Debug`
/// shows none of it.
#[expect(
    clippy::disallowed_types,
    reason = "the seam to a caller's JSON store: the record leaves as a value behind this redacting type"
)]
pub struct AuditEventValue(serde_json::Value);

impl AuditEventValue {
    /// The JSON value.
    #[must_use]
    #[expect(
        clippy::disallowed_types,
        reason = "the seam to a caller's JSON store: the record leaves as a value behind this redacting type"
    )]
    pub fn into_value(self) -> serde_json::Value {
        self.0
    }
}

impl fmt::Debug for AuditEventValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("AuditEventValue").field(&REDACTED).finish()
    }
}

/// Why a record could not be written.
#[derive(Debug, thiserror::Error)]
#[error("the AuditEvent could not be written")]
pub struct RecordError(#[source] serde_json::Error);

/// Where an audited client's exchanges go: a deployment's route to its ATNA
/// Audit Record Repository.
///
/// [`AuditRecorder::record`] is awaited once per transaction, before its
/// answer is returned: a recorder that sends over the network stores the
/// record first and delivers it from there, as ITI-20 has a sender do (ITI
/// TF-2 §3.20.4.1.1), and returns once it is stored.
///
/// The audit record is part of the transaction: an exchange the recorder
/// cannot accept fails the transaction, and its answer is never used.
#[async_trait::async_trait]
pub trait AuditRecorder: Send + Sync {
    /// Records `exchange`.
    ///
    /// # Errors
    ///
    /// An [`AuditError`] when the recorder cannot accept the exchange.
    async fn record(&self, exchange: Exchange) -> Result<(), AuditError>;

    /// Takes the place of one record before the exchange it records is
    /// made, so an exchange whose record this recorder could not take is
    /// refused before it reaches the other party.
    ///
    /// `None` says the recorder holds no bounded store, so
    /// [`AuditRecorder::record`] alone decides whether it takes a record;
    /// that is what a recorder that does not override this returns.
    ///
    /// # Errors
    ///
    /// An [`AuditError`] when the recorder has no room for one more record.
    async fn reserve(&self) -> Result<Option<Box<dyn Reserved>>, AuditError> {
        Ok(None)
    }
}

/// The place of one record an [`AuditRecorder`] took before its exchange
/// was made; dropped unfilled, it gives the place back.
#[async_trait::async_trait]
pub trait Reserved: Send + fmt::Debug {
    /// Records `exchange` in this place.
    ///
    /// # Errors
    ///
    /// An [`AuditError`] when the record cannot be stored even so: it could
    /// not be written, or not within the recorder's bound.
    async fn record(self: Box<Self>, exchange: Exchange) -> Result<(), AuditError>;
}

/// Why an audit recorder could not accept an exchange.
#[derive(Debug, thiserror::Error)]
#[error("the audit recorder could not accept the audit record")]
pub struct AuditError(#[source] pub Box<dyn std::error::Error + Send + Sync>);