1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3#![allow(renamed_and_removed_lints)] #![allow(unknown_lints)] #![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#![warn(clippy::cognitive_complexity)]
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#![deny(clippy::print_stderr)]
28#![deny(clippy::print_stdout)]
29#![warn(clippy::rc_buffer)]
30#![deny(clippy::ref_option_ref)]
31#![warn(clippy::semicolon_if_nothing_returned)]
32#![warn(clippy::trait_duplication_in_bounds)]
33#![deny(clippy::unchecked_time_subtraction)]
34#![deny(clippy::unnecessary_wraps)]
35#![warn(clippy::unseparated_literal_suffix)]
36#![deny(clippy::unwrap_used)]
37#![deny(clippy::mod_module_files)]
38#![allow(clippy::let_unit_value)] #![allow(clippy::uninlined_format_args)]
40#![allow(clippy::significant_drop_in_scrutinee)] #![allow(clippy::result_large_err)] #![allow(clippy::needless_raw_string_hashes)] #![allow(clippy::needless_lifetimes)] #![allow(mismatched_lifetime_syntaxes)] #![allow(clippy::collapsible_if)] #![deny(clippy::unused_async)]
47use educe::Educe;
52#[cfg(feature = "serde")]
53use serde::{Deserialize, Serialize};
54
55mod err;
56mod flags;
57mod impls;
58
59pub use err::Error;
60pub use flags::{Guard, disable_safe_logging, enforce_safe_logging, with_safe_logging_suppressed};
61
62use std::ops::Deref;
63
64pub type Result<T> = std::result::Result<T, Error>;
66
67#[doc(hidden)]
69pub use flags::unsafe_logging_enabled;
70
71#[derive(Educe, Clone, Copy)]
80#[educe(
81 Default(bound),
82 Deref,
83 DerefMut,
84 Eq(bound),
85 Hash(bound),
86 Ord(bound),
87 PartialEq(bound),
88 PartialOrd(bound)
89)]
90#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
91#[cfg_attr(feature = "serde", serde(transparent))]
92pub struct Sensitive<T>(T);
93
94impl<T> Sensitive<T> {
95 pub fn new(value: T) -> Self {
97 Sensitive(value)
98 }
99
100 pub fn into_inner(self) -> T {
102 self.0
103 }
104
105 #[deprecated = "Use the new into_inner method instead"]
107 pub fn unwrap(sensitive: Sensitive<T>) -> T {
108 sensitive.into_inner()
109 }
110
111 pub fn as_ref(&self) -> Sensitive<&T> {
113 Sensitive(&self.0)
114 }
115
116 pub fn as_inner(&self) -> &T {
121 &self.0
122 }
123}
124
125pub fn sensitive<T>(value: T) -> Sensitive<T> {
129 Sensitive(value)
130}
131
132impl<T> From<T> for Sensitive<T> {
133 fn from(value: T) -> Self {
134 Sensitive::new(value)
135 }
136}
137
138macro_rules! impl_display_traits {
142 { $($trait:ident),* } => {
143 $(
144 impl<T: std::fmt::$trait> std::fmt::$trait for Sensitive<T> {
145 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
146 if flags::unsafe_logging_enabled() {
147 std::fmt::$trait::fmt(&self.0, f)
148 } else {
149 write!(f, "[scrubbed]")
150 }
151 }
152 }
153
154 impl<T: std::fmt::$trait> std::fmt::$trait for BoxSensitive<T> {
155 #[inline]
156 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157 std::fmt::$trait::fmt(&*self.0, f)
158 }
159 }
160 )*
161 }
162}
163
164#[derive(Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
177pub struct BoxSensitive<T>(Box<Sensitive<T>>);
178
179impl<T> From<T> for BoxSensitive<T> {
180 fn from(t: T) -> BoxSensitive<T> {
181 BoxSensitive(Box::new(sensitive(t)))
182 }
183}
184
185impl<T> BoxSensitive<T> {
186 pub fn into_inner(self) -> T {
188 let unboxed = *self.0;
190 unboxed.into_inner()
191 }
192}
193
194impl<T> Deref for BoxSensitive<T> {
195 type Target = Sensitive<T>;
196
197 fn deref(&self) -> &Sensitive<T> {
198 &self.0
199 }
200}
201
202impl_display_traits! {
203 Display, Debug, Binary, Octal, LowerHex, UpperHex, LowerExp, UpperExp, Pointer
204}
205
206#[derive(Clone, derive_more::Display)]
210pub struct MaybeSensitive<T>(either::Either<T, Sensitive<T>>);
211
212impl<T> MaybeSensitive<T> {
213 pub fn sensitive(t: T) -> Self {
215 Self(either::Either::Right(Sensitive::new(t)))
216 }
217
218 pub fn not_sensitive(t: T) -> Self {
220 Self(either::Either::Left(t))
221 }
222
223 pub fn inner(self) -> T {
225 match self.0 {
226 either::Either::Left(t) => t,
227 either::Either::Right(s) => s.into_inner(),
228 }
229 }
230}
231
232impl<T: std::fmt::Debug> std::fmt::Debug for MaybeSensitive<T> {
233 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
234 use std::fmt::Debug;
235 match &self.0 {
236 either::Either::Left(v) => Debug::fmt(v, f),
237 either::Either::Right(v) => Debug::fmt(v, f),
238 }
239 }
240}
241
242impl<T> Deref for MaybeSensitive<T> {
243 type Target = T;
244
245 fn deref(&self) -> &T {
246 match &self.0 {
247 either::Either::Left(t) => t,
248 either::Either::Right(s) => s.as_inner(),
249 }
250 }
251}
252
253pub trait Redactable: std::fmt::Display + std::fmt::Debug {
274 fn display_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
276 fn debug_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278 self.display_redacted(f)
279 }
280 fn redacted(&self) -> Redacted<&Self> {
283 Redacted(self)
284 }
285 fn maybe_redacted(&self, redact: bool) -> MaybeRedacted<&Self> {
287 if redact {
288 MaybeRedacted(either::Either::Right(Redacted(self)))
289 } else {
290 MaybeRedacted(either::Either::Left(self))
291 }
292 }
293}
294
295impl<'a, T: Redactable + ?Sized> Redactable for &'a T {
296 fn display_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
297 (*self).display_redacted(f)
298 }
299}
300
301#[derive(Educe, Clone, Copy)]
303#[educe(
304 Default(bound),
305 Deref,
306 DerefMut,
307 Eq(bound),
308 Hash(bound),
309 Ord(bound),
310 PartialEq(bound),
311 PartialOrd(bound)
312)]
313#[derive(derive_more::From)]
314#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
315#[cfg_attr(feature = "serde", serde(transparent))]
316pub struct Redacted<T: Redactable>(T);
317
318impl<T: Redactable> Redacted<T> {
319 pub fn new(value: T) -> Self {
321 Self(value)
322 }
323
324 pub fn unwrap(self) -> T {
326 self.0
327 }
328
329 pub fn as_ref(&self) -> Redacted<&T> {
331 Redacted(&self.0)
332 }
333
334 pub fn as_inner(&self) -> &T {
339 &self.0
340 }
341}
342
343impl<T: Redactable> std::fmt::Display for Redacted<T> {
344 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
345 if flags::unsafe_logging_enabled() {
346 std::fmt::Display::fmt(&self.0, f)
347 } else {
348 self.0.display_redacted(f)
349 }
350 }
351}
352
353impl<T: Redactable> std::fmt::Debug for Redacted<T> {
354 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
355 if flags::unsafe_logging_enabled() {
356 std::fmt::Debug::fmt(&self.0, f)
357 } else {
358 self.0.debug_redacted(f)
359 }
360 }
361}
362
363#[derive(Clone, derive_more::Display)]
367pub struct MaybeRedacted<T: Redactable>(either::Either<T, Redacted<T>>);
368
369impl<T: Redactable> std::fmt::Debug for MaybeRedacted<T> {
370 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
371 use std::fmt::Debug;
372 match &self.0 {
373 either::Either::Left(v) => Debug::fmt(v, f),
374 either::Either::Right(v) => Debug::fmt(v, f),
375 }
376 }
377}
378
379pub trait DisplayRedacted {
392 fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
395 fn fmt_unredacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
398
399 fn display_redacted(&self) -> impl std::fmt::Display + '_ {
407 DispRedacted(self)
408 }
409 fn display_unredacted(&self) -> impl std::fmt::Display + '_ {
411 DispUnredacted(self)
412 }
413}
414
415impl<'a, T> DisplayRedacted for &'a T
416where
417 T: DisplayRedacted + ?Sized,
418{
419 fn display_redacted(&self) -> impl std::fmt::Display + '_ {
420 (*self).display_redacted()
421 }
422 fn display_unredacted(&self) -> impl std::fmt::Display + '_ {
423 (*self).display_unredacted()
424 }
425 fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
426 (*self).fmt_redacted(f)
427 }
428 fn fmt_unredacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
429 (*self).fmt_unredacted(f)
430 }
431}
432
433#[allow(clippy::exhaustive_structs)]
439#[derive(derive_more::AsRef)]
440pub struct DispRedacted<T: ?Sized>(pub T);
441
442#[allow(clippy::exhaustive_structs)]
445#[derive(derive_more::AsRef)]
446pub struct DispUnredacted<T: ?Sized>(pub T);
447
448impl<T> std::fmt::Display for DispRedacted<T>
449where
450 T: DisplayRedacted + ?Sized,
451{
452 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
453 if crate::flags::unsafe_logging_enabled() {
454 self.0.fmt_unredacted(f)
455 } else {
456 self.0.fmt_redacted(f)
457 }
458 }
459}
460
461impl<T> std::fmt::Display for DispUnredacted<T>
462where
463 T: DisplayRedacted + ?Sized,
464{
465 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
466 self.0.fmt_unredacted(f)
467 }
468}
469
470pub trait DebugRedacted {
483 fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
486 fn fmt_unredacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
489}
490
491#[macro_export]
499macro_rules! derive_redacted_debug {
500 {$t:ty} => {
501 impl std::fmt::Debug for $t {
502 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
503 if $crate::unsafe_logging_enabled() {
504 $crate::DebugRedacted::fmt_unredacted(self, f)
505 } else {
506 $crate::DebugRedacted::fmt_redacted(self, f)
507 }
508 }
509 }
510}}
511
512#[cfg(test)]
513mod test {
514 #![allow(clippy::bool_assert_comparison)]
516 #![allow(clippy::clone_on_copy)]
517 #![allow(clippy::dbg_macro)]
518 #![allow(clippy::mixed_attributes_style)]
519 #![allow(clippy::print_stderr)]
520 #![allow(clippy::print_stdout)]
521 #![allow(clippy::single_char_pattern)]
522 #![allow(clippy::unwrap_used)]
523 #![allow(clippy::unchecked_time_subtraction)]
524 #![allow(clippy::useless_vec)]
525 #![allow(clippy::needless_pass_by_value)]
526 use super::*;
529 use serial_test::serial;
530 use static_assertions::{assert_impl_all, assert_not_impl_any};
531
532 #[test]
533 fn clone_bound() {
534 #[derive(Clone)]
536 struct A;
537 struct B;
538
539 let _x = Sensitive(A).clone();
540 let _y = Sensitive(B);
541
542 assert_impl_all!(Sensitive<A> : Clone);
543 assert_not_impl_any!(Sensitive<B> : Clone);
544 }
545
546 #[test]
547 #[serial]
548 fn debug_vec() {
549 type SVec = Sensitive<Vec<u32>>;
550
551 let mut sv = SVec::default();
552 assert!(sv.is_empty());
553 sv.push(104);
554 sv.push(49);
555 assert_eq!(sv.len(), 2);
556
557 assert!(!flags::unsafe_logging_enabled());
558 assert_eq!(format!("{:?}", &sv), "[scrubbed]");
559 assert_eq!(format!("{:?}", sv.as_ref()), "[scrubbed]");
560 assert_eq!(format!("{:?}", sv.as_inner()), "[104, 49]");
561 let normal = with_safe_logging_suppressed(|| format!("{:?}", &sv));
562 assert_eq!(normal, "[104, 49]");
563
564 let _g = disable_safe_logging().unwrap();
565 assert_eq!(format!("{:?}", &sv), "[104, 49]");
566
567 assert_eq!(sv, SVec::from(vec![104, 49]));
568 assert_eq!(sv.clone().into_inner(), vec![104, 49]);
569 assert_eq!(*sv, vec![104, 49]);
570 }
571
572 #[test]
573 #[serial]
574 #[allow(deprecated)]
575 fn deprecated() {
576 type SVec = Sensitive<Vec<u32>>;
577 let sv = Sensitive(vec![104, 49]);
578
579 assert_eq!(SVec::unwrap(sv), vec![104, 49]);
580 }
581
582 #[test]
583 #[serial]
584 fn display_various() {
585 let val = Sensitive::<u32>::new(0x0ed19a);
586
587 let closure1 = || {
588 format!(
589 "{:?}, {}, {:o}, {:x}, {:X}, {:b}",
590 &val, &val, &val, &val, &val, &val,
591 )
592 };
593 let s1 = closure1();
594 let s2 = with_safe_logging_suppressed(closure1);
595 assert_eq!(
596 s1,
597 "[scrubbed], [scrubbed], [scrubbed], [scrubbed], [scrubbed], [scrubbed]"
598 );
599 assert_eq!(
600 s2,
601 "971162, 971162, 3550632, ed19a, ED19A, 11101101000110011010"
602 );
603
604 let n = 1.0E32;
605 let val = Sensitive::<f64>::new(n);
606 let expect = format!("{:?}, {}, {:e}, {:E}", n, n, n, n);
607 let closure2 = || format!("{:?}, {}, {:e}, {:E}", &val, &val, &val, &val);
608 let s1 = closure2();
609 let s2 = with_safe_logging_suppressed(closure2);
610 assert_eq!(s1, "[scrubbed], [scrubbed], [scrubbed], [scrubbed]");
611 assert_eq!(s2, expect);
612
613 let ptr: *const u8 = std::ptr::null();
614 let val = Sensitive::new(ptr);
615 let expect = format!("{:?}, {:p}", ptr, ptr);
616 let closure3 = || format!("{:?}, {:p}", val, val);
617 let s1 = closure3();
618 let s2 = with_safe_logging_suppressed(closure3);
619 assert_eq!(s1, "[scrubbed], [scrubbed]");
620 assert_eq!(s2, expect);
621 }
622
623 #[test]
624 #[serial]
625 fn box_sensitive() {
626 let b: BoxSensitive<_> = "hello world".into();
627
628 assert_eq!(b.clone().into_inner(), "hello world");
629
630 let closure = || format!("{} {:?}", b, b);
631 assert_eq!(closure(), "[scrubbed] [scrubbed]");
632 assert_eq!(
633 with_safe_logging_suppressed(closure),
634 r#"hello world "hello world""#
635 );
636
637 assert_eq!(b.len(), 11);
638 }
639
640 #[test]
641 #[serial]
642 fn test_redacted() {
643 let localhost = std::net::Ipv4Addr::LOCALHOST;
644 let closure = || format!("{} {:?}", localhost.redacted(), localhost.redacted());
645
646 assert_eq!(closure(), "127.x.x.x 127.x.x.x");
647 assert_eq!(with_safe_logging_suppressed(closure), "127.0.0.1 127.0.0.1");
648
649 let closure = |b| {
650 format!(
651 "{} {:?}",
652 localhost.maybe_redacted(b),
653 localhost.maybe_redacted(b)
654 )
655 };
656 assert_eq!(closure(true), "127.x.x.x 127.x.x.x");
657 assert_eq!(closure(false), "127.0.0.1 127.0.0.1");
658
659 assert_eq!(Redacted::new(localhost).unwrap(), localhost);
660 }
661
662 struct RedactionCheck(u32);
663 impl DisplayRedacted for RedactionCheck {
664 fn fmt_unredacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
665 write!(f, "{}", self.0)
666 }
667
668 fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
669 let v = self.0.to_string();
670 write!(f, "{}xxx", v.chars().next().unwrap())
671 }
672 }
673 impl DebugRedacted for RedactionCheck {
674 fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
675 write!(f, "Num({})", self.display_redacted())
676 }
677
678 fn fmt_unredacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
679 write!(f, "Num({})", self.display_unredacted())
680 }
681 }
682 derive_redacted_debug!(RedactionCheck);
683
684 #[test]
685 #[serial]
686 fn display_redacted() {
687 let n = RedactionCheck(999);
688 assert_eq!(&n.display_unredacted().to_string(), "999");
689 assert_eq!(&n.display_redacted().to_string(), "9xxx");
690 with_safe_logging_suppressed(|| assert_eq!(&n.display_redacted().to_string(), "999"));
691
692 assert_eq!(DispRedacted(&n).to_string(), "9xxx");
693 assert_eq!(DispUnredacted(&n).to_string(), "999");
694
695 assert_eq!(&format!("{n:?}"), "Num(9xxx)");
696 with_safe_logging_suppressed(|| assert_eq!(&format!("{n:?}"), "Num(999)"));
697 }
698}