hl7_2_redact/lib.rs
1//! Redaction for HL7 v2 messages in ER7 (pipe-hat) encoding, in either
2//! direction: reject by default and name what survives, or accept by
3//! default and name what does not.
4//!
5//! An HL7 v2 message is almost entirely patient detail. A process that logs
6//! one — to find a failure, to trace a flow, to answer "what happened to
7//! the message the ward is asking about?" — is putting clinical data into a
8//! store that is queried far more widely, and retained far longer, than the
9//! message store it came from. This crate is what goes between.
10//!
11//! # Two dispositions, and which one to pick
12//!
13//! Every field is either **accepted** — it survives into the output — or
14//! **rejected** — it is replaced by a mask. A [`Policy`] decides which,
15//! starting from a default disposition and applying whatever exceptions you
16//! name.
17//!
18//! | | Starts from | You name | Use when |
19//! |---|---|---|---|
20//! | [`Policy::reject_all`] | reject everything | what to **accept** | the payload is clinical and you are publishing a little of it |
21//! | [`Policy::accept_all`] | accept everything | what to **reject** | the payload is already known-safe and you are removing a few known fields |
22//!
23//! **Reject by default is the safer of the two, and it is the default.**
24//! The difference is what happens when a sender adds a field nobody
25//! anticipated: rejecting by default masks it, accepting by default
26//! publishes it. Reach for [`Policy::accept_all`] when you genuinely know
27//! the whole shape of what you are handling — a synthetic corpus, a message
28//! that has already been through a redactor, a feed with no patient
29//! content — and not merely because it is fewer lines to write.
30//!
31//! [`Policy::routing_metadata`] is the built-in reject-by-default answer:
32//! ten `MSH` fields — the routing and metadata a support engineer needs to
33//! find one message among millions — and nothing else, from any segment.
34//!
35//! # Shape survives, content does not
36//!
37//! Field *positions* are preserved: an empty field stays empty and a
38//! populated one becomes the mask. Segment identifiers are structural and
39//! are always emitted.
40//!
41//! ```
42//! use hl7_2_redact::redact;
43//!
44//! // PID-2 is empty and PID-3 is not; both stay where they are.
45//! assert_eq!(redact("MSH|^~\\&|A\rPID|1||X"), "MSH|^~\\&|A\rPID|***||***");
46//! ```
47//!
48//! That keeps visible which segments arrived, how many fields each carried,
49//! and where the gaps are — which is most of what a structural problem
50//! looks like, without any of the content.
51//!
52//! # What this is not
53//!
54//! **Not a de-identification tool.** It is a positional editor. It cannot
55//! find an identifier written into a free-text `NTE` segment that a policy
56//! accepts, and it has no opinion about whether what survives is anonymous
57//! enough for a given purpose — that is a judgement about a whole data set,
58//! made by a person.
59//!
60//! **Not a parser.** It never allocates proportional to a declared length,
61//! and never panics on arbitrary bytes. Anything it cannot recognise as ER7
62//! is handled whole rather than inspected, because the content of an
63//! unrecognised payload is by definition unknown. Those properties matter
64//! because the caller is usually an ingress process logging whatever
65//! arrived on a socket.
66//!
67//! # An invalid payload: mask it, pass it, or refuse it
68//!
69//! [`Unrecognised`] decides what happens to a payload that is not readable
70//! as ER7 at all:
71//!
72//! | | What comes out | Use when |
73//! |---|---|---|
74//! | [`Unrecognised::Reject`] | the mask, in place of the whole payload | the default: safe, and always produces a log line |
75//! | [`Unrecognised::Accept`] | the payload, unchanged | you already know it is not clinical |
76//! | [`Unrecognised::Refuse`] | nothing — [`Policy::try_redact`] returns [`Refused`] | a placeholder is not good enough and the caller must decide |
77//!
78//! Refusal is the one that needs the fallible API. `***` in a log line
79//! cannot distinguish "this was masked" from "this could not be read", and
80//! for a caller that must fail the operation, raise an alert, or route the
81//! payload somewhere it can be inspected safely, that distinction is the
82//! whole point.
83//!
84//! ```
85//! use hl7_2_redact::{Policy, Refusal, Unrecognised};
86//!
87//! let policy = Policy::routing_metadata().on_unrecognised(Unrecognised::Refuse);
88//!
89//! // A real message is redacted as usual.
90//! let redacted = policy.try_redact("MSH|^~\\&|A\rPID|1||SECRET")?;
91//! assert_eq!(redacted, "MSH|^~\\&|A\rPID|***||***");
92//!
93//! // A payload that is invalid is refused.
94//! let error = policy.try_redact(r#"{"nhsNumber": "4444444444"}"#).unwrap_err();
95//! assert_eq!(error.reason(), Refusal::NotAMessageHeader);
96//!
97//! // The error names no content — only why, and how many bytes.
98//! assert!(!error.to_string().contains("4444444444"));
99//! # Ok::<(), hl7_2_redact::Refused>(())
100//! ```
101//!
102//! An empty payload is returned unchanged under every setting, refusal
103//! included: there is nothing to hide, and refusing it would turn "the
104//! payload was empty" — itself the diagnosis — into an error a caller has
105//! to unpick.
106//!
107//! # Examples
108//!
109//! The default policy, which is what most callers want:
110//!
111//! ```
112//! use hl7_2_redact::redact;
113//!
114//! let message = "MSH|^~\\&|252|252|100|100|20260729095037|SEC|ADT^A28^ADT_A05|MSG1|P|2.5\r\
115//! PID|1||B0000010612^^^328^PI||SURNAME^FORENAME||20010909|M";
116//!
117//! let redacted = redact(message);
118//!
119//! // Routing metadata is accepted, so the message is still findable.
120//! assert!(redacted.contains("|252|252|100|100|20260729095037|"));
121//! assert!(redacted.contains("ADT^A28^ADT_A05"));
122//! // The patient is not.
123//! assert!(!redacted.contains("SURNAME"));
124//! assert!(!redacted.contains("B0000010612"));
125//! // MSH-8, the security field, is not accepted.
126//! assert!(!redacted.contains("SEC"));
127//! ```
128//!
129//! Reject by default, additionally accepting the event type in `EVN-1`:
130//!
131//! ```
132//! use hl7_2_redact::Policy;
133//!
134//! let policy = Policy::routing_metadata().accept("EVN", [1]);
135//! let redacted = policy.redact("MSH|^~\\&|A\rEVN|A28|20260729095037");
136//!
137//! assert!(redacted.contains("EVN|A28|***"));
138//! ```
139//!
140//! Accept by default, rejecting two segments outright and one field
141//! elsewhere:
142//!
143//! ```
144//! use hl7_2_redact::Policy;
145//!
146//! let policy = Policy::accept_all()
147//! .reject_segment("PID")
148//! .reject_segment("NK1")
149//! .reject("PV1", [7]);
150//!
151//! let redacted = policy.redact("MSH|^~\\&|A\rPID|1||SECRET\rPV1|1|I|||||DOCTOR");
152//!
153//! assert!(redacted.contains("MSH|^~\\&|A"), "{redacted}");
154//! assert!(!redacted.contains("SECRET"), "{redacted}");
155//! assert!(!redacted.contains("DOCTOR"), "{redacted}");
156//! assert!(redacted.contains("PV1|1|I"), "{redacted}");
157//! ```
158
159#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
160
161use std::borrow::Cow;
162use std::collections::BTreeMap;
163
164/// What a rejected value is replaced with, unless a policy says otherwise.
165///
166/// Three asterisks. Short enough not to bloat a log line, and distinct
167/// enough from a real value to be obvious at a glance.
168pub const DEFAULT_MASK: &str = "***";
169
170/// The `MSH` field numbers [`Policy::routing_metadata`] accepts, in HL7's
171/// own 1-based numbering.
172///
173/// Chosen for being routing and metadata rather than content:
174///
175/// | | |
176/// |---|---|
177/// | `MSH-2` | encoding characters — needed to parse the message at all |
178/// | `MSH-3`, `MSH-4` | sending application and facility |
179/// | `MSH-5`, `MSH-6` | receiving application and facility |
180/// | `MSH-7` | date and time of the message |
181/// | `MSH-9` | message type |
182/// | `MSH-10` | message control id |
183/// | `MSH-11` | processing id |
184/// | `MSH-12` | version id |
185///
186/// `MSH-8` (security) is deliberately absent. `MSH-1` is the field
187/// separator itself: structural, and reconstructed when the fields are
188/// rejoined, so it is never a candidate.
189pub const ROUTING_METADATA_MSH_FIELDS: [usize; 10] = [2, 3, 4, 5, 6, 7, 9, 10, 11, 12];
190
191/// The segments whose field 1 **is** the field separator.
192///
193/// In `MSH|^~\&|252`, `MSH-1` is the `|` itself and `MSH-2` is `^~\&`.
194/// Splitting on the separator therefore yields `MSH-2` as the first element
195/// after the identifier, so field numbering for these three segments is one
196/// higher than for every other segment. Getting this wrong shifts an entire
197/// policy by one, which publishes the field next to the one you meant to
198/// publish.
199pub const SEPARATOR_IS_FIELD_ONE: [&str; 3] = ["MSH", "BHS", "FHS"];
200
201/// The shortest header that can be read: a three-character segment
202/// identifier plus the field separator that follows it.
203const MINIMUM_HEADER_LENGTH: usize = 4;
204
205/// What happens to a field that no exception names.
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
207pub enum Disposition {
208 /// Replace it with the mask.
209 ///
210 /// The default, and the safer of the two: a field nobody anticipated is
211 /// masked rather than published.
212 #[default]
213 Reject,
214 /// Emit it unchanged.
215 Accept,
216}
217
218impl Disposition {
219 /// Whether this disposition emits the value.
220 #[must_use]
221 pub const fn is_accept(self) -> bool {
222 matches!(self, Self::Accept)
223 }
224}
225
226/// What to do with a payload that is not recognisable as ER7.
227#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
228pub enum Unrecognised {
229 /// Replace the whole payload with the mask.
230 ///
231 /// The default, and the safe answer: the content is unknown, so none of
232 /// it is shown. JSON, XML, a truncated frame, binary — all the same.
233 #[default]
234 Reject,
235 /// Return the payload unchanged.
236 ///
237 /// What [`Policy::accept_all`] sets, and otherwise only for a caller
238 /// that already knows the payload is not clinical — a protocol error
239 /// string, say. Choosing it makes this crate's central guarantee
240 /// conditional on the caller being right.
241 Accept,
242 /// Produce no output at all: the payload is refused.
243 ///
244 /// For a caller that must not log a placeholder and carry on — one
245 /// that would rather fail the operation, raise an alert, or route the
246 /// payload somewhere it can be inspected safely. A masked payload and
247 /// a refused one are different facts, and `***` in a log line cannot
248 /// tell them apart.
249 ///
250 /// Only [`Policy::try_redact`] and [`Policy::try_redact_into`] can
251 /// report a refusal. The infallible [`Policy::redact`] masks whole
252 /// instead, which is the same safe output [`Unrecognised::Reject`]
253 /// would produce.
254 Refuse,
255}
256
257/// Why a payload was refused.
258///
259/// Both variants mean "this is not something the crate can read as ER7".
260/// They are separated because the distinction is useful in a log line: one
261/// says a different format arrived, the other says a message arrived
262/// truncated.
263#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
264pub enum Refusal {
265 /// The first segment's identifier is not `MSH`, `BHS` or `FHS`.
266 ///
267 /// JSON, XML, a protocol error string, binary — anything that is not
268 /// an HL7 v2 message at all.
269 NotAMessageHeader,
270 /// The identifier is right but the segment stops before declaring a
271 /// field separator.
272 ///
273 /// A truncated frame: `MSH` and nothing after it. Distinguished from
274 /// [`Refusal::NotAMessageHeader`] because it usually means a transport
275 /// problem rather than a wrong sender.
276 HeaderTooShort,
277}
278
279impl Refusal {
280 /// A short description, without any payload content.
281 #[must_use]
282 pub const fn as_str(self) -> &'static str {
283 match self {
284 Self::NotAMessageHeader => {
285 "the first segment's identifier is not MSH, BHS or FHS"
286 }
287 Self::HeaderTooShort => "the header declares no field separator",
288 }
289 }
290}
291
292impl std::fmt::Display for Refusal {
293 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
294 formatter.write_str(self.as_str())
295 }
296}
297
298/// A payload that [`Unrecognised::Refuse`] declined to redact.
299///
300/// # This error carries no payload content, deliberately
301///
302/// An error type that quoted the offending input would defeat the crate:
303/// the refusal exists precisely because the content is unknown, and the
304/// error is the thing most likely to be logged. What it carries instead is
305/// the [`Refusal`] and the payload's length in bytes — enough to tell a
306/// truncated frame from a wrong format in a log line, and nothing that
307/// could be a patient.
308///
309/// # Examples
310///
311/// ```
312/// use hl7_2_redact::{Policy, Refusal, Unrecognised};
313///
314/// let policy = Policy::routing_metadata().on_unrecognised(Unrecognised::Refuse);
315/// let error = policy.try_redact(r#"{"nhsNumber": "4444444444"}"#).unwrap_err();
316///
317/// assert_eq!(error.reason(), Refusal::NotAMessageHeader);
318/// assert_eq!(error.payload_length(), 27);
319/// assert!(!error.to_string().contains("4444444444"));
320/// ```
321#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
322pub struct Refused {
323 /// What made the payload unreadable.
324 reason: Refusal,
325 /// How long the payload was, in bytes.
326 length: usize,
327}
328
329impl Refused {
330 /// What made the payload unreadable.
331 #[must_use]
332 pub const fn reason(self) -> Refusal {
333 self.reason
334 }
335
336 /// How long the refused payload was, in bytes.
337 ///
338 /// The one measurement of the payload this type will report. Useful for
339 /// telling a five-byte truncation from a five-megabyte wrong format.
340 #[must_use]
341 pub const fn payload_length(self) -> usize {
342 self.length
343 }
344}
345
346impl std::fmt::Display for Refused {
347 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
348 write!(
349 formatter,
350 "refused a payload of {} byte(s): {}",
351 self.length, self.reason
352 )
353 }
354}
355
356impl std::error::Error for Refused {}
357
358/// Which fields of which segments this policy names, and what happens to
359/// everything it does not.
360///
361/// # Order of decision
362///
363/// For each field, in this order:
364///
365/// 1. a **reject** exception naming it wins,
366/// 2. otherwise an **accept** exception naming it wins,
367/// 3. otherwise the policy's [`Disposition`] applies.
368///
369/// Reject beating accept is deliberate. A field named in both lists is a
370/// policy somebody got wrong, and masking it is the direction that fails
371/// safely.
372///
373/// # Examples
374///
375/// ```
376/// use hl7_2_redact::Policy;
377///
378/// // Reject by default: nothing survives but what you accept.
379/// assert_eq!(Policy::reject_all().redact("MSH|^~\\&|A\rPID|1"), "MSH|***|***\rPID|***");
380/// assert_eq!(
381/// Policy::reject_all().accept("MSH", [2]).redact("MSH|^~\\&|A\rPID|1"),
382/// "MSH|^~\\&|***\rPID|***"
383/// );
384///
385/// // Accept by default: everything survives but what you reject.
386/// assert_eq!(Policy::accept_all().redact("MSH|^~\\&|A\rPID|1"), "MSH|^~\\&|A\rPID|1");
387/// assert_eq!(
388/// Policy::accept_all().reject_segment("PID").redact("MSH|^~\\&|A\rPID|1"),
389/// "MSH|^~\\&|A\rPID|***"
390/// );
391/// ```
392#[derive(Debug, Clone, PartialEq, Eq)]
393pub struct Policy {
394 /// What happens to a field no exception names.
395 disposition: Disposition,
396 /// Fields named as accepted.
397 accept: BTreeMap<Cow<'static, str>, FieldSet>,
398 /// Fields named as rejected. Consulted first.
399 reject: BTreeMap<Cow<'static, str>, FieldSet>,
400 /// What a rejected value becomes.
401 mask: Cow<'static, str>,
402 /// What to do with a payload that is not ER7.
403 unrecognised: Unrecognised,
404}
405
406/// Which fields of one segment an exception covers.
407///
408/// A `BTreeMap` of these rather than a `HashMap`: the maps here have a
409/// handful of entries, so lookup cost is identical, and a deterministic
410/// iteration order makes [`Debug`] output stable enough to assert on.
411#[derive(Debug, Clone, PartialEq, Eq)]
412enum FieldSet {
413 /// Every field of the segment.
414 All,
415 /// The listed field numbers, in HL7's own 1-based numbering.
416 Only(Vec<usize>),
417}
418
419impl FieldSet {
420 /// Whether this covers field `number`.
421 fn covers(&self, number: usize) -> bool {
422 match self {
423 Self::All => true,
424 Self::Only(fields) => fields.contains(&number),
425 }
426 }
427
428 /// Add these field numbers, unless this already covers everything.
429 fn extend(&mut self, fields: impl IntoIterator<Item = usize>) {
430 let Self::Only(existing) = self else {
431 return;
432 };
433 for field in fields {
434 if !existing.contains(&field) {
435 existing.push(field);
436 }
437 }
438 existing.sort_unstable();
439 }
440}
441
442impl Default for Policy {
443 fn default() -> Self {
444 Self::routing_metadata()
445 }
446}
447
448impl Policy {
449 /// Reject every field of every segment. The starting point for a policy
450 /// that names what survives.
451 ///
452 /// An unrecognised payload is rejected whole.
453 #[must_use]
454 pub fn reject_all() -> Self {
455 Self {
456 disposition: Disposition::Reject,
457 accept: BTreeMap::new(),
458 reject: BTreeMap::new(),
459 mask: Cow::Borrowed(DEFAULT_MASK),
460 unrecognised: Unrecognised::Reject,
461 }
462 }
463
464 /// Accept every field of every segment. The starting point for a policy
465 /// that names what does not survive.
466 ///
467 /// An unrecognised payload is accepted unchanged, because a policy that
468 /// changes nothing should change nothing. Override with
469 /// [`Policy::on_unrecognised`] if that is not what you want.
470 ///
471 /// See the crate documentation for when this is the right starting
472 /// point and when it is not.
473 #[must_use]
474 pub fn accept_all() -> Self {
475 Self {
476 disposition: Disposition::Accept,
477 accept: BTreeMap::new(),
478 reject: BTreeMap::new(),
479 mask: Cow::Borrowed(DEFAULT_MASK),
480 unrecognised: Unrecognised::Accept,
481 }
482 }
483
484 /// Reject everything except [`ROUTING_METADATA_MSH_FIELDS`].
485 ///
486 /// What [`redact`] uses, and the policy most callers want: enough to
487 /// find one message among millions, and no clinical content from any
488 /// segment.
489 #[must_use]
490 pub fn routing_metadata() -> Self {
491 Self::reject_all().accept("MSH", ROUTING_METADATA_MSH_FIELDS)
492 }
493
494 /// Accept these fields of this segment.
495 ///
496 /// Field numbers are HL7's own, 1-based, and this crate applies the
497 /// [`SEPARATOR_IS_FIELD_ONE`] offset for you — `accept("MSH", [9])`
498 /// accepts the message type, which is what `MSH-9` means to a person
499 /// reading the standard.
500 ///
501 /// Calling this twice for the same segment unions the two lists.
502 ///
503 /// # Examples
504 ///
505 /// ```
506 /// use hl7_2_redact::Policy;
507 ///
508 /// let policy = Policy::reject_all().accept("PID", [3]).accept("PID", [8]);
509 /// let redacted = policy.redact("MSH|^~\\&\rPID|1||X^^^Y||Z||19700101|M");
510 ///
511 /// // PID-3 and PID-8 survive; PID-1, PID-5 and PID-7 do not.
512 /// // MSH-2 is rejected too: this policy names PID only.
513 /// assert_eq!(redacted, "MSH|***\rPID|***||X^^^Y||***||***|M");
514 /// ```
515 #[must_use]
516 pub fn accept(
517 mut self,
518 segment: impl Into<Cow<'static, str>>,
519 fields: impl IntoIterator<Item = usize>,
520 ) -> Self {
521 self.accept
522 .entry(segment.into())
523 .or_insert_with(|| FieldSet::Only(Vec::new()))
524 .extend(fields);
525 self
526 }
527
528 /// Accept every field of this segment.
529 #[must_use]
530 pub fn accept_segment(mut self, segment: impl Into<Cow<'static, str>>) -> Self {
531 self.accept.insert(segment.into(), FieldSet::All);
532 self
533 }
534
535 /// Reject these fields of this segment.
536 ///
537 /// Takes precedence over any accept exception naming the same field.
538 ///
539 /// # Examples
540 ///
541 /// ```
542 /// use hl7_2_redact::Policy;
543 ///
544 /// let policy = Policy::accept_all().reject("PID", [5, 7]);
545 /// let redacted = policy.redact("MSH|^~\\&|A\rPID|1||X||SURNAME||19700101");
546 ///
547 /// assert!(!redacted.contains("SURNAME"), "{redacted}");
548 /// assert!(!redacted.contains("19700101"), "{redacted}");
549 /// assert!(redacted.contains("|X|"), "PID-3 is untouched: {redacted}");
550 /// ```
551 #[must_use]
552 pub fn reject(
553 mut self,
554 segment: impl Into<Cow<'static, str>>,
555 fields: impl IntoIterator<Item = usize>,
556 ) -> Self {
557 self.reject
558 .entry(segment.into())
559 .or_insert_with(|| FieldSet::Only(Vec::new()))
560 .extend(fields);
561 self
562 }
563
564 /// Reject every field of this segment.
565 ///
566 /// The identifier still appears, so the segment's presence and length
567 /// remain visible.
568 #[must_use]
569 pub fn reject_segment(mut self, segment: impl Into<Cow<'static, str>>) -> Self {
570 self.reject.insert(segment.into(), FieldSet::All);
571 self
572 }
573
574 /// Use a different mask.
575 ///
576 /// # Examples
577 ///
578 /// ```
579 /// use hl7_2_redact::Policy;
580 ///
581 /// let policy = Policy::reject_all().mask_with("[redacted]");
582 /// assert_eq!(policy.redact("MSH|^~\\&|A"), "MSH|[redacted]|[redacted]");
583 /// ```
584 #[must_use]
585 pub fn mask_with(mut self, mask: impl Into<Cow<'static, str>>) -> Self {
586 self.mask = mask.into();
587 self
588 }
589
590 /// Change what happens to a payload that is not recognisable as ER7.
591 #[must_use]
592 pub fn on_unrecognised(mut self, unrecognised: Unrecognised) -> Self {
593 self.unrecognised = unrecognised;
594 self
595 }
596
597 /// What happens to a field no exception names.
598 #[must_use]
599 pub const fn disposition(&self) -> Disposition {
600 self.disposition
601 }
602
603 /// What this policy does with a given field of a given segment.
604 ///
605 /// Exposed so that a caller can assert its own policy in a test without
606 /// round-tripping a message through it.
607 ///
608 /// # Examples
609 ///
610 /// ```
611 /// use hl7_2_redact::{Disposition, Policy};
612 ///
613 /// let policy = Policy::accept_all().reject_segment("PID");
614 ///
615 /// assert_eq!(policy.disposition_of("PID", 5), Disposition::Reject);
616 /// assert_eq!(policy.disposition_of("PV1", 5), Disposition::Accept);
617 /// ```
618 #[must_use]
619 pub fn disposition_of(&self, segment: &str, field: usize) -> Disposition {
620 // Reject is consulted first: a field named in both lists is a
621 // policy somebody got wrong, and masking it fails safely.
622 if self
623 .reject
624 .get(segment)
625 .is_some_and(|fields| fields.covers(field))
626 {
627 return Disposition::Reject;
628 }
629 if self
630 .accept
631 .get(segment)
632 .is_some_and(|fields| fields.covers(field))
633 {
634 return Disposition::Accept;
635 }
636 self.disposition
637 }
638
639 /// Whether this policy emits a given field of a given segment.
640 ///
641 /// Shorthand for [`Policy::disposition_of`] when the answer is a yes or
642 /// a no.
643 #[must_use]
644 pub fn accepts(&self, segment: &str, field: usize) -> bool {
645 self.disposition_of(segment, field).is_accept()
646 }
647
648 /// Return a copy of `payload` that is safe to log.
649 ///
650 /// Three cases are worth stating outright:
651 ///
652 /// - **Empty or whitespace-only input is returned unchanged.** There is
653 /// nothing to hide, and masking it would only obscure that the
654 /// payload was empty — which is itself the diagnosis.
655 /// - **Anything not recognisable as an ER7 message is handled by
656 /// [`Unrecognised`]**, which by default rejects it whole.
657 /// - **The field separator is read from the message**, not assumed to
658 /// be `|`.
659 ///
660 /// Both `\r` and `\n` are accepted as segment terminators on input; the
661 /// result always uses `\r`.
662 #[must_use]
663 pub fn redact(&self, payload: &str) -> String {
664 let mut out = String::with_capacity(payload.len());
665 self.redact_into(payload, &mut out);
666 out
667 }
668
669 /// [`Policy::redact`], appending to a buffer you own.
670 ///
671 /// For a caller redacting on a logging hot path: the buffer can be
672 /// reused across calls, so a steady stream of messages does not mean a
673 /// steady stream of allocations.
674 ///
675 /// # Examples
676 ///
677 /// ```
678 /// use hl7_2_redact::Policy;
679 ///
680 /// let policy = Policy::routing_metadata();
681 /// let mut buffer = String::new();
682 ///
683 /// for message in ["MSH|^~\\&|A\rPID|1", "MSH|^~\\&|B\rPID|2"] {
684 /// buffer.clear();
685 /// policy.redact_into(message, &mut buffer);
686 /// assert!(buffer.starts_with("MSH|^~\\&|A") || buffer.starts_with("MSH|^~\\&|B"));
687 /// }
688 /// ```
689 pub fn redact_into(&self, payload: &str, out: &mut String) {
690 if self.try_redact_into(payload, out).is_err() {
691 // This form cannot report a refusal, so it produces the same
692 // safe output `Unrecognised::Reject` would. Nothing leaks; only
693 // the distinction between "masked" and "refused" is lost, which
694 // is what `try_redact_into` is for.
695 out.push_str(&self.mask);
696 }
697 }
698
699 /// [`Policy::redact`], reporting a refusal rather than masking it.
700 ///
701 /// Identical to [`Policy::redact`] in every case except one: when the
702 /// policy is [`Unrecognised::Refuse`] and the payload is not readable
703 /// as ER7, this returns [`Refused`] instead of producing output.
704 ///
705 /// Under the other two [`Unrecognised`] settings this never fails, so a
706 /// caller that has not opted into refusal can use either form.
707 ///
708 /// # Errors
709 ///
710 /// [`Refused`] when the policy refuses invalid payloads and this one is
711 /// invalid. The error names the [`Refusal`] and the payload's length,
712 /// and carries no payload content.
713 ///
714 /// # Examples
715 ///
716 /// ```
717 /// use hl7_2_redact::{Policy, Refusal, Unrecognised};
718 ///
719 /// let policy = Policy::routing_metadata().on_unrecognised(Unrecognised::Refuse);
720 ///
721 /// // A real message is redacted as usual.
722 /// assert!(policy.try_redact("MSH|^~\\&|A\rPID|1").is_ok());
723 ///
724 /// // A truncated frame is refused rather than masked.
725 /// let error = policy.try_redact("MSH").unwrap_err();
726 /// assert_eq!(error.reason(), Refusal::HeaderTooShort);
727 /// ```
728 pub fn try_redact(&self, payload: &str) -> Result<String, Refused> {
729 let mut out = String::with_capacity(payload.len());
730 self.try_redact_into(payload, &mut out)?;
731 Ok(out)
732 }
733
734 /// [`Policy::try_redact`], appending to a buffer you own.
735 ///
736 /// On refusal the buffer is left as it was found: nothing is appended,
737 /// so a caller reusing one buffer across many messages cannot end up
738 /// logging a half-written message.
739 ///
740 /// # Errors
741 ///
742 /// [`Refused`], as [`Policy::try_redact`].
743 pub fn try_redact_into(&self, payload: &str, out: &mut String) -> Result<(), Refused> {
744 if payload.trim().is_empty() {
745 // Empty is empty under every setting, refusal included. There
746 // is nothing to hide, and refusing it would turn "the payload
747 // was empty" — itself the diagnosis — into an error a caller
748 // has to unpick.
749 out.push_str(payload);
750 return Ok(());
751 }
752
753 let separator = match read_separator(payload) {
754 Ok(separator) => separator,
755 Err(reason) => {
756 match self.unrecognised {
757 Unrecognised::Reject => out.push_str(&self.mask),
758 Unrecognised::Accept => out.push_str(payload),
759 Unrecognised::Refuse => {
760 return Err(Refused {
761 reason,
762 length: payload.len(),
763 });
764 }
765 }
766 return Ok(());
767 }
768 };
769
770 let mut first = true;
771 for segment in payload
772 .split(['\r', '\n'])
773 .filter(|segment| !segment.is_empty())
774 {
775 if !first {
776 out.push('\r');
777 }
778 first = false;
779 self.redact_segment(segment, separator, out);
780 }
781 Ok(())
782 }
783
784 /// Redact one segment into `out`.
785 ///
786 /// The index arithmetic is the fiddly part, and it is fiddly because
787 /// `MSH` is. Splitting `MSH|^~\&|252|…` on the separator gives
788 /// `["MSH", "^~\&", "252", …]`, so element 0 is the segment identifier,
789 /// element 1 is `MSH-2`, and element *n* is `MSH-(n + 1)`. For every
790 /// other segment element *n* is simply field *n*. See
791 /// [`SEPARATOR_IS_FIELD_ONE`].
792 fn redact_segment(&self, segment: &str, separator: char, out: &mut String) {
793 let mut fields = segment.split(separator);
794
795 let Some(identifier) = fields.next() else {
796 return;
797 };
798 out.push_str(identifier);
799
800 // The identifier may be a partial or malformed segment header; that
801 // is fine, it just means no exception matches and the policy's
802 // disposition applies throughout.
803 let offset = usize::from(SEPARATOR_IS_FIELD_ONE.contains(&identifier));
804
805 for (index, field) in fields.enumerate() {
806 out.push(separator);
807
808 // `index` is 0-based over the fields after the identifier, so
809 // the field number is `index + 1`, plus one again for the
810 // segments whose field 1 is the separator itself.
811 let number = index + 1 + offset;
812
813 if field.is_empty() {
814 // An empty field carries nothing about a patient, and
815 // preserving it is what keeps a redacted message's shape
816 // readable. The asymmetry is deliberate.
817 continue;
818 }
819 if self.accepts(identifier, number) {
820 out.push_str(field);
821 } else {
822 out.push_str(&self.mask);
823 }
824 }
825 }
826}
827
828/// The field separator a message declares, if it declares one readably.
829///
830/// The separator is whatever the sender put in field 1 of the header: the
831/// fourth *character* of the first segment. `|` in practice, but not by
832/// assumption.
833///
834/// Taking the fourth **byte** — `&header[3..4]` — panics when that byte is
835/// in the middle of a multi-byte character, which a three-character
836/// identifier followed by any non-ASCII character produces. A fuzzer finds
837/// it in seconds with a five-byte input, and an ingress process takes
838/// whatever arrives on a socket, so a five-byte frame must not be able to
839/// stop one.
840///
841/// # Examples
842///
843/// ```
844/// use hl7_2_redact::separator_of;
845///
846/// assert_eq!(separator_of("MSH|^~\\&|A"), Some('|'));
847/// assert_eq!(separator_of("MSH#^~\\&#A"), Some('#'));
848/// assert_eq!(separator_of(r#"{"nhsNumber": "4444444444"}"#), None);
849/// assert_eq!(separator_of("MSH"), None);
850/// ```
851#[must_use]
852pub fn separator_of(payload: &str) -> Option<char> {
853 read_separator(payload).ok()
854}
855
856/// [`separator_of`], saying why when there is no answer.
857///
858/// The private form, because the [`Refusal`] is only meaningful to a policy
859/// that refuses; a caller asking the public question wants a `char` or
860/// nothing.
861fn read_separator(payload: &str) -> Result<char, Refusal> {
862 let Some(header) = payload.split(['\r', '\n']).find(|s| !s.is_empty()) else {
863 return Err(Refusal::NotAMessageHeader);
864 };
865
866 let mut characters = header.chars();
867 let identifier: String = characters.by_ref().take(3).collect();
868 if !SEPARATOR_IS_FIELD_ONE.contains(&identifier.as_str()) {
869 return Err(Refusal::NotAMessageHeader);
870 }
871 if header.chars().count() < MINIMUM_HEADER_LENGTH {
872 return Err(Refusal::HeaderTooShort);
873 }
874
875 characters.next().ok_or(Refusal::HeaderTooShort)
876}
877
878/// Redact a payload under [`Policy::routing_metadata`].
879///
880/// The one-call form, for the common case. Construct a [`Policy`] when you
881/// need different exceptions, the other default disposition, a different
882/// mask, or a different answer for an unrecognised payload.
883///
884/// # Examples
885///
886/// ```
887/// use hl7_2_redact::redact;
888///
889/// assert_eq!(redact(""), "");
890/// assert_eq!(redact(" "), " ");
891/// assert_eq!(redact(r#"{"nhsNumber": "4444444444"}"#), "***");
892/// assert_eq!(redact("<Patient><name>Jones</name></Patient>"), "***");
893/// ```
894#[must_use]
895pub fn redact(payload: &str) -> String {
896 Policy::routing_metadata().redact(payload)
897}
898
899#[cfg(test)]
900mod tests {
901 use super::*;
902
903 /// A message carrying values distinctive enough that finding any of
904 /// them in an output is unambiguous.
905 const MESSAGE: &str = concat!(
906 "MSH|^~\\&|252|252|100|100|20260729095037|SECRET|ADT^A28^ADT_A05|MSG1|P|2.5|||AL|NE\r",
907 "EVN|A28|20260729095037\r",
908 "PID|1||NEEDLE0612^^^328^PI||NEEDLESURNAME^NEEDLEFORENAME||20010909|M\r",
909 "PD1|||^^UNK|UNK\r",
910 "PV1||N"
911 );
912
913 #[test]
914 fn no_patient_marker_survives() {
915 // The test the whole crate is for.
916 let redacted = redact(MESSAGE);
917 assert!(!redacted.contains("NEEDLE"), "{redacted}");
918 assert!(!redacted.contains("20010909"), "{redacted}");
919 }
920
921 #[test]
922 fn routing_metadata_is_accepted() {
923 let redacted = redact(MESSAGE);
924 assert!(
925 redacted.contains("|252|252|100|100|20260729095037|"),
926 "{redacted}"
927 );
928 assert!(redacted.contains("ADT^A28^ADT_A05"), "{redacted}");
929 assert!(redacted.contains("MSG1"), "{redacted}");
930 }
931
932 #[test]
933 fn msh_8_the_security_field_is_not_accepted() {
934 // The exception list is ten fields and MSH-8 is the one in the
935 // middle that is left out; an off-by-one in either direction shows
936 // up here and nowhere else.
937 assert!(!redact(MESSAGE).contains("SECRET"), "{}", redact(MESSAGE));
938 }
939
940 #[test]
941 fn empty_input_is_returned_unchanged() {
942 // Masking an empty payload would obscure that it was empty, which
943 // is itself the diagnosis.
944 assert_eq!(redact(""), "");
945 assert_eq!(redact(" "), " ");
946 assert_eq!(redact("\r\n"), "\r\n");
947 }
948
949 #[test]
950 fn an_unrecognised_payload_is_rejected_whole() {
951 assert_eq!(redact(r#"{"nhsNumber": "4444444444"}"#), "***");
952 assert_eq!(redact("<Patient><name>Jones</name></Patient>"), "***");
953 assert_eq!(redact("PID|1||NEEDLE"), "***", "no MSH means not readable");
954 }
955
956 #[test]
957 fn accepting_an_unrecognised_payload_is_available_but_not_the_reject_all_default() {
958 let policy = Policy::reject_all().on_unrecognised(Unrecognised::Accept);
959 assert_eq!(policy.redact("not a message"), "not a message");
960 assert_eq!(Policy::reject_all().redact("not a message"), "***");
961 }
962
963 #[test]
964 fn accept_all_passes_an_unrecognised_payload_through() {
965 // A policy that changes nothing should change nothing.
966 assert_eq!(Policy::accept_all().redact("not a message"), "not a message");
967 assert_eq!(Policy::accept_all().redact(r#"{"a": 1}"#), r#"{"a": 1}"#);
968 }
969
970 #[test]
971 fn empty_fields_stay_empty_so_the_shape_survives() {
972 assert_eq!(
973 redact("MSH|^~\\&|A\rPID|1||X"),
974 "MSH|^~\\&|A\rPID|***||***"
975 );
976 }
977
978 #[test]
979 fn the_separator_is_read_from_the_message() {
980 let redacted = redact("MSH#^~\\ü#252#100#100#20260729#SEC#ADT^A28#M1");
981 assert!(redacted.contains("#252#252#"), "{redacted}");
982 assert!(!redacted.contains("SEC"), "{redacted}");
983 assert!(
984 !redacted.contains('|'),
985 "the separator is not rewritten: {redacted}"
986 );
987 }
988
989 #[test]
990 fn both_terminators_are_accepted_and_the_output_uses_carriage_return() {
991 assert_eq!(redact("MSH|^~\\&|A\nPID|1"), "MSH|^~\\&|A\rPID|***");
992 assert_eq!(redact("MSH|^~\\&|A\r\nPID|1"), "MSH|^~\\&|A\rPID|***");
993 }
994
995 #[test]
996 fn a_multi_byte_character_where_the_separator_goes_does_not_panic() {
997 // The fuzzer's finding: taking the fourth *byte* of `MSH…` panics
998 // when that byte is mid-character. Five bytes is enough to do it.
999 for payload in [
1000 "MSH£",
1001 "MSH£|A",
1002 "MSH\u{1F600}|A",
1003 "BHS\u{4e2d}",
1004 "FHS\u{0301}|X",
1005 ] {
1006 let _ = redact(payload);
1007 let _ = Policy::accept_all().redact(payload);
1008 }
1009 }
1010
1011 #[test]
1012 fn arbitrary_input_never_panics() {
1013 for payload in [
1014 "M",
1015 "MS",
1016 "MSH",
1017 "MSH|",
1018 "|||",
1019 "\r\r\r",
1020 "MSH|^~\\&|\r\r\r",
1021 "\u{0}\u{0}\u{0}\u{0}",
1022 "MSH\u{0}A",
1023 "MSH||||||||||||||||||||",
1024 ] {
1025 let _ = redact(payload);
1026 let _ = Policy::accept_all().redact(payload);
1027 }
1028 }
1029
1030 #[test]
1031 fn the_msh_offset_is_applied_and_other_segments_are_not_offset() {
1032 // `accept("MSH", [9])` must accept the message type, which is what
1033 // a person reading the standard means by MSH-9. `accept("PID", [3])`
1034 // must accept the third field of PID, with no offset.
1035 let policy = Policy::reject_all().accept("MSH", [9]).accept("PID", [3]);
1036 let redacted = policy.redact("MSH|^~\\&|A|B|C|D|E|F|ADT^A28|M1\rPID|1||THIRD|4");
1037
1038 assert!(redacted.contains("ADT^A28"), "{redacted}");
1039 assert!(!redacted.contains("M1"), "MSH-10 is not accepted: {redacted}");
1040 assert!(redacted.contains("|THIRD|"), "{redacted}");
1041 assert!(!redacted.contains("|4"), "PID-4 is not accepted: {redacted}");
1042 }
1043
1044 #[test]
1045 fn the_msh_offset_applies_to_reject_exceptions_too() {
1046 // The same offset, from the other direction: an accept-by-default
1047 // policy rejecting MSH-9 must hit the message type, not MSH-8.
1048 let policy = Policy::accept_all().reject("MSH", [9]);
1049 let redacted = policy.redact("MSH|^~\\&|A|B|C|D|E|SECRET|ADT^A28|M1");
1050
1051 assert!(!redacted.contains("ADT^A28"), "{redacted}");
1052 assert!(redacted.contains("SECRET"), "MSH-8 is untouched: {redacted}");
1053 assert!(redacted.contains("M1"), "MSH-10 is untouched: {redacted}");
1054 }
1055
1056 #[test]
1057 fn bhs_and_fhs_carry_the_same_offset_as_msh() {
1058 // A batch header is read the same way, and a policy written against
1059 // the standard's numbering must not shift by one here either.
1060 let policy = Policy::reject_all().accept("BHS", [2]);
1061 assert_eq!(policy.redact("BHS|^~\\&|SENDER"), "BHS|^~\\&|***");
1062 }
1063
1064 #[test]
1065 fn reject_all_keeps_nothing_at_all() {
1066 assert_eq!(
1067 Policy::reject_all().redact("MSH|^~\\&|A\rPID|1"),
1068 "MSH|***|***\rPID|***"
1069 );
1070 }
1071
1072 #[test]
1073 fn accept_all_changes_nothing_at_all() {
1074 assert_eq!(Policy::accept_all().redact(MESSAGE), MESSAGE);
1075 }
1076
1077 #[test]
1078 fn accept_by_default_with_segment_exceptions() {
1079 let policy = Policy::accept_all().reject_segment("PID").reject("PV1", [7]);
1080 let redacted = policy.redact("MSH|^~\\&|A\rPID|1||SECRET\rPV1|1|I|||||DOCTOR");
1081
1082 assert!(redacted.contains("MSH|^~\\&|A"), "{redacted}");
1083 assert_eq!(
1084 redacted,
1085 "MSH|^~\\&|A\rPID|***||***\rPV1|1|I|||||***",
1086 "the identifier and the empty fields survive; the content does not"
1087 );
1088 }
1089
1090 #[test]
1091 fn accept_segment_is_the_mirror_of_reject_segment() {
1092 let policy = Policy::reject_all().accept_segment("EVN");
1093 let redacted = policy.redact("MSH|^~\\&|A\rEVN|A28|20260729");
1094
1095 assert_eq!(redacted, "MSH|***|***\rEVN|A28|20260729");
1096 }
1097
1098 #[test]
1099 fn reject_beats_accept_for_the_same_field() {
1100 // A field named in both lists is a policy somebody got wrong, and
1101 // masking it is the direction that fails safely.
1102 let policy = Policy::accept_all().accept("PID", [3]).reject("PID", [3]);
1103
1104 assert_eq!(policy.disposition_of("PID", 3), Disposition::Reject);
1105 assert!(!policy.redact("MSH|^~\\&|A\rPID|1||X").contains("|X"));
1106 }
1107
1108 #[test]
1109 fn reject_segment_beats_a_narrower_accept() {
1110 let policy = Policy::reject_all().accept("PID", [3]).reject_segment("PID");
1111 assert!(!policy.accepts("PID", 3));
1112 }
1113
1114 #[test]
1115 fn exceptions_union_rather_than_replacing() {
1116 let policy = Policy::reject_all().accept("PID", [3]).accept("PID", [8]);
1117 assert!(policy.accepts("PID", 3));
1118 assert!(policy.accepts("PID", 8));
1119 assert!(!policy.accepts("PID", 5));
1120 assert!(!policy.accepts("PV1", 3));
1121 }
1122
1123 #[test]
1124 fn a_segment_wide_exception_is_not_narrowed_by_a_later_field_list() {
1125 // `accept_segment` then `accept` must not quietly demote the
1126 // segment-wide rule to a two-element list.
1127 let policy = Policy::reject_all().accept_segment("PID").accept("PID", [3]);
1128 assert!(policy.accepts("PID", 3));
1129 assert!(policy.accepts("PID", 99), "still segment-wide");
1130 }
1131
1132 #[test]
1133 fn the_mask_is_configurable() {
1134 let policy = Policy::reject_all().mask_with("[redacted]");
1135 assert_eq!(policy.redact("MSH|^~\\&|A"), "MSH|[redacted]|[redacted]");
1136 assert_eq!(policy.redact("not a message"), "[redacted]");
1137 }
1138
1139 #[test]
1140 fn redact_into_appends_and_can_reuse_a_buffer() {
1141 let policy = Policy::routing_metadata();
1142 let mut buffer = String::new();
1143
1144 policy.redact_into("MSH|^~\\&|A", &mut buffer);
1145 let after_first = buffer.clone();
1146
1147 buffer.clear();
1148 policy.redact_into("MSH|^~\\&|A", &mut buffer);
1149
1150 assert_eq!(buffer, after_first, "a reused buffer gives the same answer");
1151 }
1152
1153 #[test]
1154 fn an_unknown_segment_follows_the_default_disposition() {
1155 // The property that makes reject-by-default worth having: a segment
1156 // nobody anticipated is masked, not published.
1157 assert_eq!(
1158 redact("MSH|^~\\&|A\rZZZ|surprise|content"),
1159 "MSH|^~\\&|A\rZZZ|***|***"
1160 );
1161 // And the mirror, which is the risk accept-by-default carries.
1162 assert_eq!(
1163 Policy::accept_all()
1164 .reject_segment("PID")
1165 .redact("MSH|^~\\&|A\rZZZ|surprise|content"),
1166 "MSH|^~\\&|A\rZZZ|surprise|content"
1167 );
1168 }
1169
1170 /// A policy that refuses whatever it cannot read.
1171 fn refusing() -> Policy {
1172 Policy::routing_metadata().on_unrecognised(Unrecognised::Refuse)
1173 }
1174
1175 #[test]
1176 fn a_payload_that_is_invalid_is_refused() {
1177 for payload in [
1178 r#"{"nhsNumber": "4444444444"}"#,
1179 "<Patient><name>Jones</name></Patient>",
1180 "PID|1||NEEDLE",
1181 "connection reset by peer",
1182 ] {
1183 let error = refusing()
1184 .try_redact(payload)
1185 .expect_err("not an HL7 v2 message");
1186 assert_eq!(error.reason(), Refusal::NotAMessageHeader, "{payload}");
1187 assert_eq!(error.payload_length(), payload.len(), "{payload}");
1188 }
1189 }
1190
1191 #[test]
1192 fn a_truncated_header_is_refused_as_such() {
1193 // The distinction worth keeping: a wrong format and a truncated
1194 // frame usually have different causes, and a log line saying which
1195 // is the difference between suspecting a sender and suspecting a
1196 // socket.
1197 for payload in ["MSH", "BHS", "FHS", "MS", "M"] {
1198 let error = refusing().try_redact(payload).expect_err("truncated");
1199 let expected = if payload.len() == 3 {
1200 Refusal::HeaderTooShort
1201 } else {
1202 Refusal::NotAMessageHeader
1203 };
1204 assert_eq!(error.reason(), expected, "{payload}");
1205 }
1206 }
1207
1208 #[test]
1209 fn a_valid_payload_is_not_refused() {
1210 // Refusal changes nothing about a message the crate can read.
1211 assert_eq!(refusing().try_redact(MESSAGE).unwrap(), redact(MESSAGE));
1212 assert_eq!(
1213 refusing().try_redact("MSH|^~\\&|A\rPID|1||SECRET").unwrap(),
1214 "MSH|^~\\&|A\rPID|***||***"
1215 );
1216 }
1217
1218 #[test]
1219 fn an_empty_payload_is_never_refused() {
1220 // Refusing it would turn "the payload was empty" — itself the
1221 // diagnosis — into an error a caller has to unpick.
1222 for payload in ["", " ", "\r\n"] {
1223 assert_eq!(refusing().try_redact(payload).unwrap(), payload);
1224 }
1225 }
1226
1227 #[test]
1228 fn a_refusal_names_no_payload_content() {
1229 // The property that makes this error type safe to log: it exists
1230 // because the content is unknown, so it must not quote it.
1231 let secret = "NEEDLESURNAME and 4444444444 and B0000010612";
1232 let error = refusing().try_redact(secret).expect_err("not a message");
1233 let rendered = error.to_string();
1234
1235 assert!(!rendered.contains("NEEDLE"), "{rendered}");
1236 assert!(!rendered.contains("4444444444"), "{rendered}");
1237 assert!(!rendered.contains("B0000010612"), "{rendered}");
1238 assert!(rendered.contains(&secret.len().to_string()), "{rendered}");
1239 assert!(rendered.contains("MSH"), "the reason names the identifiers it wanted");
1240 }
1241
1242 #[test]
1243 fn the_infallible_form_masks_where_the_fallible_one_refuses() {
1244 // `redact` cannot report a refusal, so it produces the same safe
1245 // output `Reject` would. Nothing leaks; only the distinction is
1246 // lost.
1247 let policy = refusing();
1248 assert_eq!(policy.redact(r#"{"a": 1}"#), "***");
1249 assert!(policy.try_redact(r#"{"a": 1}"#).is_err());
1250 }
1251
1252 #[test]
1253 fn a_refusal_leaves_a_reused_buffer_untouched() {
1254 // A caller reusing one buffer across many messages must not end up
1255 // logging a half-written message.
1256 let policy = refusing();
1257 let mut buffer = String::from("previous contents");
1258
1259 let error = policy.try_redact_into("not a message", &mut buffer);
1260
1261 assert!(error.is_err());
1262 assert_eq!(buffer, "previous contents");
1263 }
1264
1265 #[test]
1266 fn the_other_two_settings_never_refuse() {
1267 // A caller that has not opted into refusal can use either form.
1268 for policy in [
1269 Policy::reject_all(),
1270 Policy::accept_all(),
1271 Policy::routing_metadata(),
1272 ] {
1273 assert!(policy.try_redact("not a message").is_ok());
1274 assert!(policy.try_redact(MESSAGE).is_ok());
1275 }
1276 }
1277
1278 #[test]
1279 fn refusing_arbitrary_input_never_panics() {
1280 for payload in [
1281 "M", "MS", "MSH", "MSH|", "|||", "\r\r\r", "MSH£", "MSH\u{1F600}|A",
1282 "\u{0}\u{0}\u{0}\u{0}", "MSH\u{0}A",
1283 ] {
1284 let _ = refusing().try_redact(payload);
1285 let _ = refusing().redact(payload);
1286 }
1287 }
1288
1289 #[test]
1290 fn a_refusal_is_a_std_error() {
1291 // So it composes with `?`, `Box<dyn Error>` and anyhow without the
1292 // caller writing an adapter.
1293 fn boxed(payload: &str) -> Result<String, Box<dyn std::error::Error>> {
1294 Ok(refusing().try_redact(payload)?)
1295 }
1296
1297 assert!(boxed("MSH|^~\\&|A").is_ok());
1298 assert!(boxed("not a message").is_err());
1299 }
1300
1301 #[test]
1302 fn the_default_policy_is_routing_metadata() {
1303 assert_eq!(Policy::default(), Policy::routing_metadata());
1304 assert_eq!(Policy::default().disposition(), Disposition::Reject);
1305 for field in ROUTING_METADATA_MSH_FIELDS {
1306 assert!(Policy::default().accepts("MSH", field));
1307 }
1308 assert!(!Policy::default().accepts("MSH", 8));
1309 assert!(!Policy::default().accepts("MSH", 1));
1310 }
1311
1312 #[test]
1313 fn the_two_dispositions_report_themselves() {
1314 assert_eq!(Policy::reject_all().disposition(), Disposition::Reject);
1315 assert_eq!(Policy::accept_all().disposition(), Disposition::Accept);
1316 assert!(Disposition::Accept.is_accept());
1317 assert!(!Disposition::Reject.is_accept());
1318 assert_eq!(Disposition::default(), Disposition::Reject);
1319 assert_eq!(Unrecognised::default(), Unrecognised::Reject);
1320 }
1321}