Skip to main content

safelog/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3// @@ begin lint list maintained by maint/add_warning @@
4#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6#![warn(missing_docs)]
7#![warn(noop_method_call)]
8#![warn(unreachable_pub)]
9#![warn(clippy::all)]
10#![deny(clippy::await_holding_lock)]
11#![deny(clippy::cargo_common_metadata)]
12#![deny(clippy::cast_lossless)]
13#![deny(clippy::checked_conversions)]
14#![allow(clippy::cognitive_complexity)] // See arti#2556
15#![deny(clippy::debug_assert_with_mut_call)]
16#![deny(clippy::exhaustive_enums)]
17#![deny(clippy::exhaustive_structs)]
18#![deny(clippy::expl_impl_clone_on_copy)]
19#![deny(clippy::fallible_impl_from)]
20#![deny(clippy::implicit_clone)]
21#![deny(clippy::large_stack_arrays)]
22#![warn(clippy::manual_ok_or)]
23#![deny(clippy::missing_docs_in_private_items)]
24#![warn(clippy::needless_borrow)]
25#![warn(clippy::needless_pass_by_value)]
26#![warn(clippy::option_option)]
27#![warn(clippy::or_fun_call)]
28#![deny(clippy::print_stderr)]
29#![deny(clippy::print_stdout)]
30#![warn(clippy::rc_buffer)]
31#![deny(clippy::ref_option_ref)]
32#![warn(clippy::semicolon_if_nothing_returned)]
33#![warn(clippy::trait_duplication_in_bounds)]
34#![deny(clippy::unchecked_time_subtraction)]
35#![deny(clippy::unnecessary_wraps)]
36#![warn(clippy::unseparated_literal_suffix)]
37#![deny(clippy::unwrap_used)]
38#![deny(clippy::mod_module_files)]
39#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
40#![allow(clippy::uninlined_format_args)]
41#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
42#![allow(clippy::result_large_err)] // temporary workaround for arti#587
43#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
44#![allow(clippy::needless_lifetimes)] // See arti#1765
45#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
46#![allow(clippy::collapsible_if)] // See arti#2342
47#![deny(clippy::unused_async)]
48#![deny(clippy::string_slice)] // See arti#2571
49#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
50//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
51
52// TODO: add to the list maintained by maint/add_warning once it's available on all crates
53#![warn(unnameable_types)]
54
55// TODO: Try making it not Deref and having expose+expose_mut instead; how bad is it?
56
57use educe::Educe;
58#[cfg(feature = "serde")]
59use serde::{Deserialize, Serialize};
60
61mod err;
62mod flags;
63mod impls;
64pub mod util;
65
66pub use err::Error;
67pub use flags::{Guard, disable_safe_logging, enforce_safe_logging, with_safe_logging_suppressed};
68
69use std::ops::Deref;
70
71/// A `Result` returned by the flag-manipulation functions in `safelog`.
72pub type Result<T> = std::result::Result<T, Error>;
73
74// Re-exported for macros.
75#[doc(hidden)]
76pub use flags::unsafe_logging_enabled;
77
78/// A wrapper type for a sensitive value.
79///
80/// By default, a `Sensitive<T>` behaves the same as a regular `T`, except that
81/// attempts to turn it into a string (via `Display`, `Debug`, etc) all produce
82/// the string `[scrubbed]`.
83///
84/// This behavior can be overridden locally by using
85/// [`with_safe_logging_suppressed`] and globally with [`disable_safe_logging`].
86#[derive(Educe, Clone, Copy)]
87#[educe(
88    Default(bound),
89    Deref,
90    DerefMut,
91    Eq(bound),
92    Hash(bound),
93    Ord(bound),
94    PartialEq(bound),
95    PartialOrd(bound)
96)]
97#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
98#[cfg_attr(feature = "serde", serde(transparent))]
99pub struct Sensitive<T>(T);
100
101impl<T> Sensitive<T> {
102    /// Create a new `Sensitive<T>`, wrapping a provided `value`.
103    pub fn new(value: T) -> Self {
104        Sensitive(value)
105    }
106
107    /// Extract the inner value from this `Sensitive<T>`.
108    pub fn into_inner(self) -> T {
109        self.0
110    }
111
112    /// Extract the inner value from this `Sensitive<T>`.
113    #[deprecated = "Use the new into_inner method instead"]
114    pub fn unwrap(sensitive: Sensitive<T>) -> T {
115        sensitive.into_inner()
116    }
117
118    /// Converts `&Sensitive<T>` to `Sensitive<&T>`
119    pub fn as_ref(&self) -> Sensitive<&T> {
120        Sensitive(&self.0)
121    }
122
123    /// Return a reference to the inner value
124    //
125    // This isn't `AsRef` or `as_ref` because we don't want to offer "de-sensitivisation"
126    // via what is usually a semantically-neutral interface.
127    pub fn as_inner(&self) -> &T {
128        &self.0
129    }
130}
131
132/// Wrap a value as `Sensitive`.
133///
134/// This function is an alias for [`Sensitive::new`].
135pub fn sensitive<T>(value: T) -> Sensitive<T> {
136    Sensitive(value)
137}
138
139impl<T> From<T> for Sensitive<T> {
140    fn from(value: T) -> Self {
141        Sensitive::new(value)
142    }
143}
144
145/// Helper: Declare one or more Display-like implementations for a
146/// Sensitive-like type.  These implementations will delegate to their std::fmt
147/// types if safe logging is disabled, and write `[scrubbed]` otherwise.
148macro_rules! impl_display_traits {
149    { $($trait:ident),* } => {
150    $(
151        impl<T: std::fmt::$trait> std::fmt::$trait for Sensitive<T> {
152            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153                if flags::unsafe_logging_enabled() {
154                    std::fmt::$trait::fmt(&self.0, f)
155                } else {
156                    write!(f, "[scrubbed]")
157                }
158            }
159        }
160
161        impl<T: std::fmt::$trait> std::fmt::$trait for BoxSensitive<T> {
162            #[inline]
163            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
164                std::fmt::$trait::fmt(&*self.0, f)
165            }
166        }
167   )*
168   }
169}
170
171/// A wrapper suitable for logging and including in errors
172///
173/// This is a newtype around `Box<Sensitive<T>>`.
174///
175/// This is useful particularly in errors,
176/// where the box can help reduce the size of error variants
177/// (for example ones containing large values like an `OwnedChanTarget`).
178///
179/// `BoxSensitive<T>` dereferences to [`Sensitive<T>`].
180//
181// Making it be a newtype rather than a type alias allows us to implement
182// `into_inner` and `From<T>` and so on.
183#[derive(Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
184pub struct BoxSensitive<T>(Box<Sensitive<T>>);
185
186impl<T> From<T> for BoxSensitive<T> {
187    fn from(t: T) -> BoxSensitive<T> {
188        BoxSensitive(Box::new(sensitive(t)))
189    }
190}
191
192impl<T> BoxSensitive<T> {
193    /// Return the innermost `T`
194    pub fn into_inner(self) -> T {
195        // TODO want unstable Box::into_inner(self.0) rust-lang/rust/issues/80437
196        let unboxed = *self.0;
197        unboxed.into_inner()
198    }
199}
200
201impl<T> Deref for BoxSensitive<T> {
202    type Target = Sensitive<T>;
203
204    fn deref(&self) -> &Sensitive<T> {
205        &self.0
206    }
207}
208
209impl_display_traits! {
210    Display, Debug, Binary, Octal, LowerHex, UpperHex, LowerExp, UpperExp, Pointer
211}
212
213/// An object that may or may not be sensitive.
214///
215/// See [`Sensitive`] for the guarantees it provides for the sensitive case.
216#[derive(Clone, derive_more::Display)]
217pub struct MaybeSensitive<T>(either::Either<T, Sensitive<T>>);
218
219impl<T> MaybeSensitive<T> {
220    /// Build a sensitive container.
221    pub fn sensitive(t: T) -> Self {
222        Self(either::Either::Right(Sensitive::new(t)))
223    }
224
225    /// Build a non sensitive container.
226    pub fn not_sensitive(t: T) -> Self {
227        Self(either::Either::Left(t))
228    }
229
230    /// Return the innermost `T`
231    pub fn inner(self) -> T {
232        match self.0 {
233            either::Either::Left(t) => t,
234            either::Either::Right(s) => s.into_inner(),
235        }
236    }
237
238    /// Map a `MaybeSensitive<T>` to a `MaybeSensitive<U>`
239    /// by applying the supplied function `f` to the inner `T`
240    pub fn map<U, F>(self, f: F) -> MaybeSensitive<U>
241    where
242        F: FnOnce(T) -> U,
243    {
244        match self.0 {
245            either::Either::Left(t) => MaybeSensitive(either::Either::Left(f(t))),
246            either::Either::Right(s) => {
247                let new_inner = f(s.into_inner());
248                MaybeSensitive(either::Either::Right(Sensitive::new(new_inner)))
249            }
250        }
251    }
252}
253
254impl<T: std::fmt::Debug> std::fmt::Debug for MaybeSensitive<T> {
255    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
256        use std::fmt::Debug;
257        match &self.0 {
258            either::Either::Left(v) => Debug::fmt(v, f),
259            either::Either::Right(v) => Debug::fmt(v, f),
260        }
261    }
262}
263
264impl<T> Deref for MaybeSensitive<T> {
265    type Target = T;
266
267    fn deref(&self) -> &T {
268        match &self.0 {
269            either::Either::Left(t) => t,
270            either::Either::Right(s) => s.as_inner(),
271        }
272    }
273}
274
275/// A `redactable` object is one where we know a way to display _part_ of it
276/// when we are running with safe logging enabled.
277///
278/// For example, instead of referring to a user as `So-and-So` or `[scrubbed]`,
279/// this trait would allow referring to the user as `S[...]`.
280///
281/// # Privacy notes
282///
283/// Displaying some information about an object is always less safe than
284/// displaying no information about it!
285///
286/// For example, in an environment with only a small number of users, the first
287/// letter of a user's name might be plenty of information to identify them
288/// uniquely.
289///
290/// Even if a piece of redacted information is safe on its own, several pieces
291/// of redacted information, when taken together, can be enough for an adversary
292/// to infer more than you want.  For example, if you log somebody's first
293/// initial, month of birth, and last-two-digits of ID number, you have just
294/// discarded 99.9% of potential individuals from the attacker's consideration.
295pub trait Redactable: std::fmt::Display + std::fmt::Debug {
296    /// As `Display::fmt`, but produce a redacted representation.
297    fn display_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
298    /// As `Debug::fmt`, but produce a redacted representation.
299    fn debug_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
300        self.display_redacted(f)
301    }
302    /// Return a smart pointer that will display or debug this object as its
303    /// redacted form.
304    fn redacted(&self) -> Redacted<&Self> {
305        Redacted(self)
306    }
307    /// Return a smart pointer that redacts this object if `redact` is true.
308    fn maybe_redacted(&self, redact: bool) -> MaybeRedacted<&Self> {
309        if redact {
310            MaybeRedacted(either::Either::Right(Redacted(self)))
311        } else {
312            MaybeRedacted(either::Either::Left(self))
313        }
314    }
315}
316
317impl<'a, T: Redactable + ?Sized> Redactable for &'a T {
318    fn display_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
319        (*self).display_redacted(f)
320    }
321
322    fn debug_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
323        (*self).debug_redacted(f)
324    }
325
326    // The default implementations for redacted() and maybe_redacted() are okay unconditionally.
327}
328
329/// A wrapper around a `Redactable` that displays it in redacted format.
330#[derive(Educe, Clone, Copy)]
331#[educe(
332    Default(bound),
333    Deref,
334    DerefMut,
335    Eq(bound),
336    Hash(bound),
337    Ord(bound),
338    PartialEq(bound),
339    PartialOrd(bound)
340)]
341#[derive(derive_more::From)]
342#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
343#[cfg_attr(feature = "serde", serde(transparent))]
344pub struct Redacted<T: Redactable>(T);
345
346impl<T: Redactable> Redacted<T> {
347    /// Create a new `Redacted`.
348    pub fn new(value: T) -> Self {
349        Self(value)
350    }
351
352    /// Consume this wrapper and return its inner value.
353    pub fn unwrap(self) -> T {
354        self.0
355    }
356
357    /// Converts `&Redacted<T>` to `Redacted<&T>`
358    pub fn as_ref(&self) -> Redacted<&T> {
359        Redacted(&self.0)
360    }
361
362    /// Return a reference to the inner value
363    //
364    // This isn't `AsRef` or `as_ref` because we don't want to offer "de-redaction"
365    // via what is usually a semantically-neutral interface.
366    pub fn as_inner(&self) -> &T {
367        &self.0
368    }
369}
370
371impl<T: Redactable> std::fmt::Display for Redacted<T> {
372    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
373        if flags::unsafe_logging_enabled() {
374            std::fmt::Display::fmt(&self.0, f)
375        } else {
376            self.0.display_redacted(f)
377        }
378    }
379}
380
381impl<T: Redactable> std::fmt::Debug for Redacted<T> {
382    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
383        if flags::unsafe_logging_enabled() {
384            std::fmt::Debug::fmt(&self.0, f)
385        } else {
386            self.0.debug_redacted(f)
387        }
388    }
389}
390
391/// An object that may or may not be redacted.
392///
393/// Used to implement conditional redaction
394#[derive(Clone, derive_more::Display)]
395pub struct MaybeRedacted<T: Redactable>(either::Either<T, Redacted<T>>);
396
397impl<T: Redactable> std::fmt::Debug for MaybeRedacted<T> {
398    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
399        use std::fmt::Debug;
400        match &self.0 {
401            either::Either::Left(v) => Debug::fmt(v, f),
402            either::Either::Right(v) => Debug::fmt(v, f),
403        }
404    }
405}
406
407/// A type that can be displayed in a redacted or un-redacted form,
408/// but which forces the caller to choose.
409///
410/// See [`Redactable`] for more discussion on redaction.
411///
412/// Unlike [`Redactable`], this type is "inherently sensitive":
413/// Types implementing `DisplayRedacted` should not typically implement
414/// [`Display`](std::fmt::Display).
415///
416/// For external types that implement `Display`,
417/// or for types which are usually _not_ sensitive,
418/// `Redacted` is likely a better choice.
419pub trait DisplayRedacted {
420    /// As [`Display::fmt`](std::fmt::Display::fmt), but write this object
421    /// in its redacted form.
422    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
423    /// As [`Display::fmt`](std::fmt::Display::fmt), but write this object
424    /// in its un-redacted form.
425    fn fmt_unredacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
426
427    // TODO: At some point in the future, when default values are supported for GATs,
428    // it might be good to turn these RPIT functions into associated types.
429
430    /// Return a pointer wrapping this object that can be Displayed in redacted form
431    /// if safe-logging is enabled.
432    ///
433    /// (If safe-logging is not enabled, it will de displayed in its unredacted form.)
434    fn display_redacted(&self) -> impl std::fmt::Display + '_ {
435        DispRedacted(self)
436    }
437    /// Return a pointer wrapping this object that can be Displayed in unredacted form.
438    fn display_unredacted(&self) -> impl std::fmt::Display + '_ {
439        DispUnredacted(self)
440    }
441}
442
443impl<'a, T> DisplayRedacted for &'a T
444where
445    T: DisplayRedacted + ?Sized,
446{
447    fn display_redacted(&self) -> impl std::fmt::Display + '_ {
448        (*self).display_redacted()
449    }
450    fn display_unredacted(&self) -> impl std::fmt::Display + '_ {
451        (*self).display_unredacted()
452    }
453    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
454        (*self).fmt_redacted(f)
455    }
456    fn fmt_unredacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
457        (*self).fmt_unredacted(f)
458    }
459}
460
461/// A wrapper around a [`DisplayRedacted`] that implements [`Display`](std::fmt::Display)
462/// by displaying the object in its redacted form
463/// if safe-logging is enabled.
464///
465/// (If safe-logging is not enabled, it will de displayed in its unredacted form.)
466#[allow(clippy::exhaustive_structs)]
467#[derive(derive_more::AsRef)]
468pub struct DispRedacted<T: ?Sized>(pub T);
469
470/// A wrapper around a [`DisplayRedacted`] that implements [`Display`](std::fmt::Display)
471/// by displaying the object in its un-redacted form.
472#[allow(clippy::exhaustive_structs)]
473#[derive(derive_more::AsRef)]
474pub struct DispUnredacted<T: ?Sized>(pub T);
475
476impl<T> std::fmt::Display for DispRedacted<T>
477where
478    T: DisplayRedacted + ?Sized,
479{
480    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
481        if crate::flags::unsafe_logging_enabled() {
482            self.0.fmt_unredacted(f)
483        } else {
484            self.0.fmt_redacted(f)
485        }
486    }
487}
488
489impl<T> std::fmt::Display for DispUnredacted<T>
490where
491    T: DisplayRedacted + ?Sized,
492{
493    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
494        self.0.fmt_unredacted(f)
495    }
496}
497
498/// A type that can be debugged in a redacted or un-redacted form,
499/// but which forces the caller to choose.
500///
501/// See [`Redactable`] for more discussion on redaction.
502///
503/// Unlike [`Redactable`], this type is "inherently sensitive":
504/// [`Debug`](std::fmt::Debug) will display it in redacted or un-redacted format
505/// depending on whether safe logging is enabled.
506///
507/// For external types that implement `Debug`,
508/// or for types which are usually _not_ sensitive,
509/// `Redacted` is likely a better choice.
510pub trait DebugRedacted {
511    /// As [`Debug::fmt`](std::fmt::Debug::fmt), but write this object
512    /// in its redacted form.
513    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
514    /// As [`Debug::fmt`](std::fmt::Debug::fmt), but write this object
515    /// in its unredacted form.
516    fn fmt_unredacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
517}
518
519/// Implement [`std::fmt::Debug`] for a type that implements [`DebugRedacted`].
520///
521/// The implementation will use fmt_redacted() when safe-logging is enabled,
522/// and fmt_unredacted() otherwise.
523///
524/// (NOTE we can't just write 'impl<T:DebugRedacted> Debug for T`;
525/// Rust doesn't like it.)
526#[macro_export]
527macro_rules! derive_redacted_debug {
528    {$t:ty} => {
529    impl std::fmt::Debug for $t {
530        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
531            if $crate::unsafe_logging_enabled() {
532                $crate::DebugRedacted::fmt_unredacted(self, f)
533            } else {
534                $crate::DebugRedacted::fmt_redacted(self, f)
535            }
536        }
537    }
538}}
539
540#[cfg(test)]
541mod test {
542    // @@ begin test lint list maintained by maint/add_warning @@
543    #![allow(clippy::bool_assert_comparison)]
544    #![allow(clippy::clone_on_copy)]
545    #![allow(clippy::dbg_macro)]
546    #![allow(clippy::mixed_attributes_style)]
547    #![allow(clippy::print_stderr)]
548    #![allow(clippy::print_stdout)]
549    #![allow(clippy::single_char_pattern)]
550    #![allow(clippy::unwrap_used)]
551    #![allow(clippy::unchecked_time_subtraction)]
552    #![allow(clippy::useless_vec)]
553    #![allow(clippy::needless_pass_by_value)]
554    #![allow(clippy::string_slice)] // See arti#2571
555    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
556
557    use super::*;
558    use serial_test::serial;
559    use static_assertions::{assert_impl_all, assert_not_impl_any};
560
561    #[test]
562    fn clone_bound() {
563        // Here we'll make sure that educe bounds work about the way we expect.
564        #[derive(Clone)]
565        struct A;
566        struct B;
567
568        let _x = Sensitive(A).clone();
569        let _y = Sensitive(B);
570
571        assert_impl_all!(Sensitive<A> : Clone);
572        assert_not_impl_any!(Sensitive<B> : Clone);
573    }
574
575    #[test]
576    #[serial]
577    fn debug_vec() {
578        type SVec = Sensitive<Vec<u32>>;
579
580        let mut sv = SVec::default();
581        assert!(sv.is_empty());
582        sv.push(104);
583        sv.push(49);
584        assert_eq!(sv.len(), 2);
585
586        assert!(!flags::unsafe_logging_enabled());
587        assert_eq!(format!("{:?}", sv), "[scrubbed]");
588        assert_eq!(format!("{:?}", sv.as_ref()), "[scrubbed]");
589        assert_eq!(format!("{:?}", sv.as_inner()), "[104, 49]");
590        let normal = with_safe_logging_suppressed(|| format!("{:?}", sv));
591        assert_eq!(normal, "[104, 49]");
592
593        let _g = disable_safe_logging().unwrap();
594        assert_eq!(format!("{:?}", sv), "[104, 49]");
595
596        assert_eq!(sv, SVec::from(vec![104, 49]));
597        assert_eq!(sv.clone().into_inner(), vec![104, 49]);
598        assert_eq!(*sv, vec![104, 49]);
599    }
600
601    #[test]
602    #[serial]
603    #[allow(deprecated)]
604    fn deprecated() {
605        type SVec = Sensitive<Vec<u32>>;
606        let sv = Sensitive(vec![104, 49]);
607
608        assert_eq!(SVec::unwrap(sv), vec![104, 49]);
609    }
610
611    #[test]
612    #[serial]
613    fn display_various() {
614        let val = Sensitive::<u32>::new(0x0ed19a);
615
616        let closure1 = || {
617            format!(
618                "{:?}, {}, {:o}, {:x}, {:X}, {:b}",
619                val, val, val, val, val, val,
620            )
621        };
622        let s1 = closure1();
623        let s2 = with_safe_logging_suppressed(closure1);
624        assert_eq!(
625            s1,
626            "[scrubbed], [scrubbed], [scrubbed], [scrubbed], [scrubbed], [scrubbed]"
627        );
628        assert_eq!(
629            s2,
630            "971162, 971162, 3550632, ed19a, ED19A, 11101101000110011010"
631        );
632
633        let n = 1.0E32;
634        let val = Sensitive::<f64>::new(n);
635        let expect = format!("{:?}, {}, {:e}, {:E}", n, n, n, n);
636        let closure2 = || format!("{:?}, {}, {:e}, {:E}", val, val, val, val);
637        let s1 = closure2();
638        let s2 = with_safe_logging_suppressed(closure2);
639        assert_eq!(s1, "[scrubbed], [scrubbed], [scrubbed], [scrubbed]");
640        assert_eq!(s2, expect);
641
642        let ptr: *const u8 = std::ptr::null();
643        let val = Sensitive::new(ptr);
644        let expect = format!("{:?}, {:p}", ptr, ptr);
645        let closure3 = || format!("{:?}, {:p}", val, val);
646        let s1 = closure3();
647        let s2 = with_safe_logging_suppressed(closure3);
648        assert_eq!(s1, "[scrubbed], [scrubbed]");
649        assert_eq!(s2, expect);
650    }
651
652    #[test]
653    #[serial]
654    fn box_sensitive() {
655        let b: BoxSensitive<_> = "hello world".into();
656
657        assert_eq!(b.clone().into_inner(), "hello world");
658
659        let closure = || format!("{} {:?}", b, b);
660        assert_eq!(closure(), "[scrubbed] [scrubbed]");
661        assert_eq!(
662            with_safe_logging_suppressed(closure),
663            r#"hello world "hello world""#
664        );
665
666        assert_eq!(b.len(), 11);
667    }
668
669    #[test]
670    #[serial]
671    fn test_redacted() {
672        let localhost = std::net::Ipv4Addr::LOCALHOST;
673        let closure = || format!("{} {:?}", localhost.redacted(), localhost.redacted());
674
675        assert_eq!(closure(), "127.x.x.x 127.x.x.x");
676        assert_eq!(with_safe_logging_suppressed(closure), "127.0.0.1 127.0.0.1");
677
678        let closure = |b| {
679            format!(
680                "{} {:?}",
681                localhost.maybe_redacted(b),
682                localhost.maybe_redacted(b)
683            )
684        };
685        assert_eq!(closure(true), "127.x.x.x 127.x.x.x");
686        assert_eq!(closure(false), "127.0.0.1 127.0.0.1");
687
688        assert_eq!(Redacted::new(localhost).unwrap(), localhost);
689    }
690
691    struct RedactionCheck(u32);
692    impl DisplayRedacted for RedactionCheck {
693        fn fmt_unredacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
694            write!(f, "{}", self.0)
695        }
696
697        fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
698            let v = self.0.to_string();
699            write!(f, "{}xxx", v.chars().next().unwrap())
700        }
701    }
702    impl DebugRedacted for RedactionCheck {
703        fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
704            write!(f, "Num({})", self.display_redacted())
705        }
706
707        fn fmt_unredacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
708            write!(f, "Num({})", self.display_unredacted())
709        }
710    }
711    derive_redacted_debug!(RedactionCheck);
712
713    #[test]
714    #[serial]
715    fn display_redacted() {
716        let n = RedactionCheck(999);
717        assert_eq!(&n.display_unredacted().to_string(), "999");
718        assert_eq!(&n.display_redacted().to_string(), "9xxx");
719        with_safe_logging_suppressed(|| assert_eq!(&n.display_redacted().to_string(), "999"));
720
721        assert_eq!(DispRedacted(&n).to_string(), "9xxx");
722        assert_eq!(DispUnredacted(&n).to_string(), "999");
723
724        assert_eq!(&format!("{n:?}"), "Num(9xxx)");
725        with_safe_logging_suppressed(|| assert_eq!(&format!("{n:?}"), "Num(999)"));
726    }
727}