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

            
57
use educe::Educe;
58
#[cfg(feature = "serde")]
59
use serde::{Deserialize, Serialize};
60

            
61
mod err;
62
mod flags;
63
mod impls;
64
pub mod util;
65

            
66
pub use err::Error;
67
pub use flags::{Guard, disable_safe_logging, enforce_safe_logging, with_safe_logging_suppressed};
68

            
69
use std::ops::Deref;
70

            
71
/// A `Result` returned by the flag-manipulation functions in `safelog`.
72
pub type Result<T> = std::result::Result<T, Error>;
73

            
74
// Re-exported for macros.
75
#[doc(hidden)]
76
pub 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(Default, Deref, DerefMut, Eq, Hash, Ord, PartialEq, PartialOrd)]
88
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
89
#[cfg_attr(feature = "serde", serde(transparent))]
90
pub struct Sensitive<T>(T);
91

            
92
impl<T> Sensitive<T> {
93
    /// Create a new `Sensitive<T>`, wrapping a provided `value`.
94
71795
    pub fn new(value: T) -> Self {
95
71795
        Sensitive(value)
96
71795
    }
97

            
98
    /// Extract the inner value from this `Sensitive<T>`.
99
765
    pub fn into_inner(self) -> T {
100
765
        self.0
101
765
    }
102

            
103
    /// Extract the inner value from this `Sensitive<T>`.
104
    #[deprecated = "Use the new into_inner method instead"]
105
1
    pub fn unwrap(sensitive: Sensitive<T>) -> T {
106
1
        sensitive.into_inner()
107
1
    }
108

            
109
    /// Converts `&Sensitive<T>` to `Sensitive<&T>`
110
1
    pub fn as_ref(&self) -> Sensitive<&T> {
111
1
        Sensitive(&self.0)
112
1
    }
113

            
114
    /// Return a reference to the inner value
115
    //
116
    // This isn't `AsRef` or `as_ref` because we don't want to offer "de-sensitivisation"
117
    // via what is usually a semantically-neutral interface.
118
160
    pub fn as_inner(&self) -> &T {
119
160
        &self.0
120
160
    }
121
}
122

            
123
/// Wrap a value as `Sensitive`.
124
///
125
/// This function is an alias for [`Sensitive::new`].
126
14
pub fn sensitive<T>(value: T) -> Sensitive<T> {
127
14
    Sensitive(value)
128
14
}
129

            
130
impl<T> From<T> for Sensitive<T> {
131
71787
    fn from(value: T) -> Self {
132
71787
        Sensitive::new(value)
133
71787
    }
134
}
135

            
136
/// Helper: Declare one or more Display-like implementations for a
137
/// Sensitive-like type.  These implementations will delegate to their std::fmt
138
/// types if safe logging is disabled, and write `[scrubbed]` otherwise.
139
macro_rules! impl_display_traits {
140
    { $($trait:ident),* } => {
141
    $(
142
        impl<T: std::fmt::$trait> std::fmt::$trait for Sensitive<T> {
143
46
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144
46
                if flags::unsafe_logging_enabled() {
145
16
                    std::fmt::$trait::fmt(&self.0, f)
146
                } else {
147
30
                    write!(f, "[scrubbed]")
148
                }
149
46
            }
150
        }
151

            
152
        impl<T: std::fmt::$trait> std::fmt::$trait for BoxSensitive<T> {
153
            #[inline]
154
4
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155
4
                std::fmt::$trait::fmt(&*self.0, f)
156
4
            }
157
        }
158
   )*
159
   }
160
}
161

            
162
/// A wrapper suitable for logging and including in errors
163
///
164
/// This is a newtype around `Box<Sensitive<T>>`.
165
///
166
/// This is useful particularly in errors,
167
/// where the box can help reduce the size of error variants
168
/// (for example ones containing large values like an `OwnedChanTarget`).
169
///
170
/// `BoxSensitive<T>` dereferences to [`Sensitive<T>`].
171
//
172
// Making it be a newtype rather than a type alias allows us to implement
173
// `into_inner` and `From<T>` and so on.
174
#[derive(Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
175
pub struct BoxSensitive<T>(Box<Sensitive<T>>);
176

            
177
impl<T> From<T> for BoxSensitive<T> {
178
1
    fn from(t: T) -> BoxSensitive<T> {
179
1
        BoxSensitive(Box::new(sensitive(t)))
180
1
    }
181
}
182

            
183
impl<T> BoxSensitive<T> {
184
    /// Return the innermost `T`
185
1
    pub fn into_inner(self) -> T {
186
        // TODO want unstable Box::into_inner(self.0) rust-lang/rust/issues/80437
187
1
        let unboxed = *self.0;
188
1
        unboxed.into_inner()
189
1
    }
190
}
191

            
192
impl<T> Deref for BoxSensitive<T> {
193
    type Target = Sensitive<T>;
194

            
195
1
    fn deref(&self) -> &Sensitive<T> {
196
1
        &self.0
197
1
    }
198
}
199

            
200
impl_display_traits! {
201
    Display, Debug, Binary, Octal, LowerHex, UpperHex, LowerExp, UpperExp, Pointer
202
}
203

            
204
/// An object that may or may not be sensitive.
205
///
206
/// See [`Sensitive`] for the guarantees it provides for the sensitive case.
207
#[derive(Clone, derive_more::Display)]
208
pub struct MaybeSensitive<T>(either::Either<T, Sensitive<T>>);
209

            
210
impl<T> MaybeSensitive<T> {
211
    /// Build a sensitive container.
212
2
    pub fn sensitive(t: T) -> Self {
213
2
        Self(either::Either::Right(Sensitive::new(t)))
214
2
    }
215

            
216
    /// Build a non sensitive container.
217
317
    pub fn not_sensitive(t: T) -> Self {
218
317
        Self(either::Either::Left(t))
219
317
    }
220

            
221
    /// Return the innermost `T`
222
1
    pub fn inner(self) -> T {
223
1
        match self.0 {
224
            either::Either::Left(t) => t,
225
1
            either::Either::Right(s) => s.into_inner(),
226
        }
227
1
    }
228

            
229
    /// Map a `MaybeSensitive<T>` to a `MaybeSensitive<U>`
230
    /// by applying the supplied function `f` to the inner `T`
231
284
    pub fn map<U, F>(self, f: F) -> MaybeSensitive<U>
232
284
    where
233
284
        F: FnOnce(T) -> U,
234
    {
235
284
        match self.0 {
236
283
            either::Either::Left(t) => MaybeSensitive(either::Either::Left(f(t))),
237
            either::Either::Right(s) => {
238
1
                let new_inner = f(s.into_inner());
239
1
                MaybeSensitive(either::Either::Right(Sensitive::new(new_inner)))
240
            }
241
        }
242
284
    }
243
}
244

            
245
impl<T: std::fmt::Debug> std::fmt::Debug for MaybeSensitive<T> {
246
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
247
        use std::fmt::Debug;
248
        match &self.0 {
249
            either::Either::Left(v) => Debug::fmt(v, f),
250
            either::Either::Right(v) => Debug::fmt(v, f),
251
        }
252
    }
253
}
254

            
255
impl<T> Deref for MaybeSensitive<T> {
256
    type Target = T;
257

            
258
186
    fn deref(&self) -> &T {
259
186
        match &self.0 {
260
35
            either::Either::Left(t) => t,
261
151
            either::Either::Right(s) => s.as_inner(),
262
        }
263
186
    }
264
}
265

            
266
/// A `redactable` object is one where we know a way to display _part_ of it
267
/// when we are running with safe logging enabled.
268
///
269
/// For example, instead of referring to a user as `So-and-So` or `[scrubbed]`,
270
/// this trait would allow referring to the user as `S[...]`.
271
///
272
/// # Privacy notes
273
///
274
/// Displaying some information about an object is always less safe than
275
/// displaying no information about it!
276
///
277
/// For example, in an environment with only a small number of users, the first
278
/// letter of a user's name might be plenty of information to identify them
279
/// uniquely.
280
///
281
/// Even if a piece of redacted information is safe on its own, several pieces
282
/// of redacted information, when taken together, can be enough for an adversary
283
/// to infer more than you want.  For example, if you log somebody's first
284
/// initial, month of birth, and last-two-digits of ID number, you have just
285
/// discarded 99.9% of potential individuals from the attacker's consideration.
286
pub trait Redactable: std::fmt::Display + std::fmt::Debug {
287
    /// As `Display::fmt`, but produce a redacted representation.
288
    fn display_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
289
    /// As `Debug::fmt`, but produce a redacted representation.
290
2
    fn debug_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
291
2
        self.display_redacted(f)
292
2
    }
293
    /// Return a smart pointer that will display or debug this object as its
294
    /// redacted form.
295
19
    fn redacted(&self) -> Redacted<&Self> {
296
19
        Redacted(self)
297
19
    }
298
    /// Return a smart pointer that redacts this object if `redact` is true.
299
60044
    fn maybe_redacted(&self, redact: bool) -> MaybeRedacted<&Self> {
300
60044
        if redact {
301
3
            MaybeRedacted(either::Either::Right(Redacted(self)))
302
        } else {
303
60041
            MaybeRedacted(either::Either::Left(self))
304
        }
305
60044
    }
306
}
307

            
308
impl<'a, T: Redactable + ?Sized> Redactable for &'a T {
309
111
    fn display_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
310
111
        (*self).display_redacted(f)
311
111
    }
312

            
313
2
    fn debug_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
314
2
        (*self).debug_redacted(f)
315
2
    }
316

            
317
    // The default implementations for redacted() and maybe_redacted() are okay unconditionally.
318
}
319

            
320
/// A wrapper around a `Redactable` that displays it in redacted format.
321
#[derive(Educe, Clone, Copy)]
322
#[educe(Default, Deref, DerefMut, Eq, Hash, Ord, PartialEq, PartialOrd)]
323
#[derive(derive_more::From)]
324
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
325
#[cfg_attr(feature = "serde", serde(transparent))]
326
pub struct Redacted<T: Redactable>(T);
327

            
328
impl<T: Redactable> Redacted<T> {
329
    /// Create a new `Redacted`.
330
1
    pub fn new(value: T) -> Self {
331
1
        Self(value)
332
1
    }
333

            
334
    /// Consume this wrapper and return its inner value.
335
1
    pub fn unwrap(self) -> T {
336
1
        self.0
337
1
    }
338

            
339
    /// Converts `&Redacted<T>` to `Redacted<&T>`
340
    pub fn as_ref(&self) -> Redacted<&T> {
341
        Redacted(&self.0)
342
    }
343

            
344
    /// Return a reference to the inner value
345
    //
346
    // This isn't `AsRef` or `as_ref` because we don't want to offer "de-redaction"
347
    // via what is usually a semantically-neutral interface.
348
435
    pub fn as_inner(&self) -> &T {
349
435
        &self.0
350
435
    }
351
}
352

            
353
impl<T: Redactable> std::fmt::Display for Redacted<T> {
354
19
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
355
19
        if flags::unsafe_logging_enabled() {
356
1
            std::fmt::Display::fmt(&self.0, f)
357
        } else {
358
18
            self.0.display_redacted(f)
359
        }
360
19
    }
361
}
362

            
363
impl<T: Redactable> std::fmt::Debug for Redacted<T> {
364
3
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
365
3
        if flags::unsafe_logging_enabled() {
366
1
            std::fmt::Debug::fmt(&self.0, f)
367
        } else {
368
2
            self.0.debug_redacted(f)
369
        }
370
3
    }
371
}
372

            
373
/// An object that may or may not be redacted.
374
///
375
/// Used to implement conditional redaction
376
#[derive(Clone, derive_more::Display)]
377
pub struct MaybeRedacted<T: Redactable>(either::Either<T, Redacted<T>>);
378

            
379
impl<T: Redactable> std::fmt::Debug for MaybeRedacted<T> {
380
2
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
381
        use std::fmt::Debug;
382
2
        match &self.0 {
383
1
            either::Either::Left(v) => Debug::fmt(v, f),
384
1
            either::Either::Right(v) => Debug::fmt(v, f),
385
        }
386
2
    }
387
}
388

            
389
/// A type that can be displayed in a redacted or un-redacted form,
390
/// but which forces the caller to choose.
391
///
392
/// See [`Redactable`] for more discussion on redaction.
393
///
394
/// Unlike [`Redactable`], this type is "inherently sensitive":
395
/// Types implementing `DisplayRedacted` should not typically implement
396
/// [`Display`](std::fmt::Display).
397
///
398
/// For external types that implement `Display`,
399
/// or for types which are usually _not_ sensitive,
400
/// `Redacted` is likely a better choice.
401
pub trait DisplayRedacted {
402
    /// As [`Display::fmt`](std::fmt::Display::fmt), but write this object
403
    /// in its redacted form.
404
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
405
    /// As [`Display::fmt`](std::fmt::Display::fmt), but write this object
406
    /// in its un-redacted form.
407
    fn fmt_unredacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
408

            
409
    // TODO: At some point in the future, when default values are supported for GATs,
410
    // it might be good to turn these RPIT functions into associated types.
411

            
412
    /// Return a pointer wrapping this object that can be Displayed in redacted form
413
    /// if safe-logging is enabled.
414
    ///
415
    /// (If safe-logging is not enabled, it will de displayed in its unredacted form.)
416
2182
    fn display_redacted(&self) -> impl std::fmt::Display + '_ {
417
2182
        DispRedacted(self)
418
2182
    }
419
    /// Return a pointer wrapping this object that can be Displayed in unredacted form.
420
54191
    fn display_unredacted(&self) -> impl std::fmt::Display + '_ {
421
54191
        DispUnredacted(self)
422
54191
    }
423
}
424

            
425
impl<'a, T> DisplayRedacted for &'a T
426
where
427
    T: DisplayRedacted + ?Sized,
428
{
429
    fn display_redacted(&self) -> impl std::fmt::Display + '_ {
430
        (*self).display_redacted()
431
    }
432
    fn display_unredacted(&self) -> impl std::fmt::Display + '_ {
433
        (*self).display_unredacted()
434
    }
435
2182
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
436
2182
        (*self).fmt_redacted(f)
437
2182
    }
438
54193
    fn fmt_unredacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
439
54193
        (*self).fmt_unredacted(f)
440
54193
    }
441
}
442

            
443
/// A wrapper around a [`DisplayRedacted`] that implements [`Display`](std::fmt::Display)
444
/// by displaying the object in its redacted form
445
/// if safe-logging is enabled.
446
///
447
/// (If safe-logging is not enabled, it will de displayed in its unredacted form.)
448
#[allow(clippy::exhaustive_structs)]
449
#[derive(derive_more::AsRef)]
450
pub struct DispRedacted<T: ?Sized>(pub T);
451

            
452
/// A wrapper around a [`DisplayRedacted`] that implements [`Display`](std::fmt::Display)
453
/// by displaying the object in its un-redacted form.
454
#[allow(clippy::exhaustive_structs)]
455
#[derive(derive_more::AsRef)]
456
pub struct DispUnredacted<T: ?Sized>(pub T);
457

            
458
impl<T> std::fmt::Display for DispRedacted<T>
459
where
460
    T: DisplayRedacted + ?Sized,
461
{
462
2907
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
463
2907
        if crate::flags::unsafe_logging_enabled() {
464
1
            self.0.fmt_unredacted(f)
465
        } else {
466
2906
            self.0.fmt_redacted(f)
467
        }
468
2907
    }
469
}
470

            
471
impl<T> std::fmt::Display for DispUnredacted<T>
472
where
473
    T: DisplayRedacted + ?Sized,
474
{
475
54192
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
476
54192
        self.0.fmt_unredacted(f)
477
54192
    }
478
}
479

            
480
/// A type that can be debugged in a redacted or un-redacted form,
481
/// but which forces the caller to choose.
482
///
483
/// See [`Redactable`] for more discussion on redaction.
484
///
485
/// Unlike [`Redactable`], this type is "inherently sensitive":
486
/// [`Debug`](std::fmt::Debug) will display it in redacted or un-redacted format
487
/// depending on whether safe logging is enabled.
488
///
489
/// For external types that implement `Debug`,
490
/// or for types which are usually _not_ sensitive,
491
/// `Redacted` is likely a better choice.
492
pub trait DebugRedacted {
493
    /// As [`Debug::fmt`](std::fmt::Debug::fmt), but write this object
494
    /// in its redacted form.
495
    fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
496
    /// As [`Debug::fmt`](std::fmt::Debug::fmt), but write this object
497
    /// in its unredacted form.
498
    fn fmt_unredacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
499
}
500

            
501
/// Implement [`std::fmt::Debug`] for a type that implements [`DebugRedacted`].
502
///
503
/// The implementation will use fmt_redacted() when safe-logging is enabled,
504
/// and fmt_unredacted() otherwise.
505
///
506
/// (NOTE we can't just write 'impl<T:DebugRedacted> Debug for T`;
507
/// Rust doesn't like it.)
508
#[macro_export]
509
macro_rules! derive_redacted_debug {
510
    {$t:ty} => {
511
    impl std::fmt::Debug for $t {
512
1719
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
513
1719
            if $crate::unsafe_logging_enabled() {
514
2
                $crate::DebugRedacted::fmt_unredacted(self, f)
515
            } else {
516
1717
                $crate::DebugRedacted::fmt_redacted(self, f)
517
            }
518
1719
        }
519
    }
520
}}
521

            
522
#[cfg(test)]
523
mod test {
524
    // @@ begin test lint list maintained by maint/add_warning @@
525
    #![allow(clippy::bool_assert_comparison)]
526
    #![allow(clippy::clone_on_copy)]
527
    #![allow(clippy::dbg_macro)]
528
    #![allow(clippy::mixed_attributes_style)]
529
    #![allow(clippy::print_stderr)]
530
    #![allow(clippy::print_stdout)]
531
    #![allow(clippy::single_char_pattern)]
532
    #![allow(clippy::unwrap_used)]
533
    #![allow(clippy::unchecked_time_subtraction)]
534
    #![allow(clippy::useless_vec)]
535
    #![allow(clippy::needless_pass_by_value)]
536
    #![allow(clippy::string_slice)] // See arti#2571
537
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
538

            
539
    use super::*;
540
    use serial_test::serial;
541
    use static_assertions::{assert_impl_all, assert_not_impl_any};
542

            
543
    #[test]
544
    fn clone_bound() {
545
        // Here we'll make sure that educe bounds work about the way we expect.
546
        #[derive(Clone)]
547
        struct A;
548
        struct B;
549

            
550
        let _x = Sensitive(A).clone();
551
        let _y = Sensitive(B);
552

            
553
        assert_impl_all!(Sensitive<A> : Clone);
554
        assert_not_impl_any!(Sensitive<B> : Clone);
555
    }
556

            
557
    #[test]
558
    #[serial]
559
    fn debug_vec() {
560
        type SVec = Sensitive<Vec<u32>>;
561

            
562
        let mut sv = SVec::default();
563
        assert!(sv.is_empty());
564
        sv.push(104);
565
        sv.push(49);
566
        assert_eq!(sv.len(), 2);
567

            
568
        assert!(!flags::unsafe_logging_enabled());
569
        assert_eq!(format!("{:?}", sv), "[scrubbed]");
570
        assert_eq!(format!("{:?}", sv.as_ref()), "[scrubbed]");
571
        assert_eq!(format!("{:?}", sv.as_inner()), "[104, 49]");
572
        let normal = with_safe_logging_suppressed(|| format!("{:?}", sv));
573
        assert_eq!(normal, "[104, 49]");
574

            
575
        let _g = disable_safe_logging().unwrap();
576
        assert_eq!(format!("{:?}", sv), "[104, 49]");
577

            
578
        assert_eq!(sv, SVec::from(vec![104, 49]));
579
        assert_eq!(sv.clone().into_inner(), vec![104, 49]);
580
        assert_eq!(*sv, vec![104, 49]);
581
    }
582

            
583
    #[test]
584
    #[serial]
585
    #[allow(deprecated)]
586
    fn deprecated() {
587
        type SVec = Sensitive<Vec<u32>>;
588
        let sv = Sensitive(vec![104, 49]);
589

            
590
        assert_eq!(SVec::unwrap(sv), vec![104, 49]);
591
    }
592

            
593
    #[test]
594
    #[serial]
595
    fn display_various() {
596
        let val = Sensitive::<u32>::new(0x0ed19a);
597

            
598
        let closure1 = || {
599
            format!(
600
                "{:?}, {}, {:o}, {:x}, {:X}, {:b}",
601
                val, val, val, val, val, val,
602
            )
603
        };
604
        let s1 = closure1();
605
        let s2 = with_safe_logging_suppressed(closure1);
606
        assert_eq!(
607
            s1,
608
            "[scrubbed], [scrubbed], [scrubbed], [scrubbed], [scrubbed], [scrubbed]"
609
        );
610
        assert_eq!(
611
            s2,
612
            "971162, 971162, 3550632, ed19a, ED19A, 11101101000110011010"
613
        );
614

            
615
        let n = 1.0E32;
616
        let val = Sensitive::<f64>::new(n);
617
        let expect = format!("{:?}, {}, {:e}, {:E}", n, n, n, n);
618
        let closure2 = || format!("{:?}, {}, {:e}, {:E}", val, val, val, val);
619
        let s1 = closure2();
620
        let s2 = with_safe_logging_suppressed(closure2);
621
        assert_eq!(s1, "[scrubbed], [scrubbed], [scrubbed], [scrubbed]");
622
        assert_eq!(s2, expect);
623

            
624
        let ptr: *const u8 = std::ptr::null();
625
        let val = Sensitive::new(ptr);
626
        let expect = format!("{:?}, {:p}", ptr, ptr);
627
        let closure3 = || format!("{:?}, {:p}", val, val);
628
        let s1 = closure3();
629
        let s2 = with_safe_logging_suppressed(closure3);
630
        assert_eq!(s1, "[scrubbed], [scrubbed]");
631
        assert_eq!(s2, expect);
632
    }
633

            
634
    #[test]
635
    #[serial]
636
    fn box_sensitive() {
637
        let b: BoxSensitive<_> = "hello world".into();
638

            
639
        assert_eq!(b.clone().into_inner(), "hello world");
640

            
641
        let closure = || format!("{} {:?}", b, b);
642
        assert_eq!(closure(), "[scrubbed] [scrubbed]");
643
        assert_eq!(
644
            with_safe_logging_suppressed(closure),
645
            r#"hello world "hello world""#
646
        );
647

            
648
        assert_eq!(b.len(), 11);
649
    }
650

            
651
    #[test]
652
    #[serial]
653
    fn test_redacted() {
654
        let localhost = std::net::Ipv4Addr::LOCALHOST;
655
        let closure = || format!("{} {:?}", localhost.redacted(), localhost.redacted());
656

            
657
        assert_eq!(closure(), "127.x.x.x 127.x.x.x");
658
        assert_eq!(with_safe_logging_suppressed(closure), "127.0.0.1 127.0.0.1");
659

            
660
        let closure = |b| {
661
            format!(
662
                "{} {:?}",
663
                localhost.maybe_redacted(b),
664
                localhost.maybe_redacted(b)
665
            )
666
        };
667
        assert_eq!(closure(true), "127.x.x.x 127.x.x.x");
668
        assert_eq!(closure(false), "127.0.0.1 127.0.0.1");
669

            
670
        assert_eq!(Redacted::new(localhost).unwrap(), localhost);
671
    }
672

            
673
    struct RedactionCheck(u32);
674
    impl DisplayRedacted for RedactionCheck {
675
        fn fmt_unredacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
676
            write!(f, "{}", self.0)
677
        }
678

            
679
        fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
680
            let v = self.0.to_string();
681
            write!(f, "{}xxx", v.chars().next().unwrap())
682
        }
683
    }
684
    impl DebugRedacted for RedactionCheck {
685
        fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
686
            write!(f, "Num({})", self.display_redacted())
687
        }
688

            
689
        fn fmt_unredacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
690
            write!(f, "Num({})", self.display_unredacted())
691
        }
692
    }
693
    derive_redacted_debug!(RedactionCheck);
694

            
695
    #[test]
696
    #[serial]
697
    fn display_redacted() {
698
        let n = RedactionCheck(999);
699
        assert_eq!(&n.display_unredacted().to_string(), "999");
700
        assert_eq!(&n.display_redacted().to_string(), "9xxx");
701
        with_safe_logging_suppressed(|| assert_eq!(&n.display_redacted().to_string(), "999"));
702

            
703
        assert_eq!(DispRedacted(&n).to_string(), "9xxx");
704
        assert_eq!(DispUnredacted(&n).to_string(), "999");
705

            
706
        assert_eq!(&format!("{n:?}"), "Num(9xxx)");
707
        with_safe_logging_suppressed(|| assert_eq!(&format!("{n:?}"), "Num(999)"));
708
    }
709
}