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#![allow(clippy::cognitive_complexity)] #![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)] #![allow(clippy::uninlined_format_args)]
41#![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)]
48#![deny(clippy::string_slice)] #![allow(recursion_depth_exceeding_limit)] #![warn(unnameable_types)]
54
55use 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
71pub type Result<T> = std::result::Result<T, Error>;
73
74#[doc(hidden)]
76pub use flags::unsafe_logging_enabled;
77
78#[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 pub fn new(value: T) -> Self {
104 Sensitive(value)
105 }
106
107 pub fn into_inner(self) -> T {
109 self.0
110 }
111
112 #[deprecated = "Use the new into_inner method instead"]
114 pub fn unwrap(sensitive: Sensitive<T>) -> T {
115 sensitive.into_inner()
116 }
117
118 pub fn as_ref(&self) -> Sensitive<&T> {
120 Sensitive(&self.0)
121 }
122
123 pub fn as_inner(&self) -> &T {
128 &self.0
129 }
130}
131
132pub 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
145macro_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#[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 pub fn into_inner(self) -> T {
195 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#[derive(Clone, derive_more::Display)]
217pub struct MaybeSensitive<T>(either::Either<T, Sensitive<T>>);
218
219impl<T> MaybeSensitive<T> {
220 pub fn sensitive(t: T) -> Self {
222 Self(either::Either::Right(Sensitive::new(t)))
223 }
224
225 pub fn not_sensitive(t: T) -> Self {
227 Self(either::Either::Left(t))
228 }
229
230 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 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
275pub trait Redactable: std::fmt::Display + std::fmt::Debug {
296 fn display_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
298 fn debug_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
300 self.display_redacted(f)
301 }
302 fn redacted(&self) -> Redacted<&Self> {
305 Redacted(self)
306 }
307 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 }
328
329#[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 pub fn new(value: T) -> Self {
349 Self(value)
350 }
351
352 pub fn unwrap(self) -> T {
354 self.0
355 }
356
357 pub fn as_ref(&self) -> Redacted<&T> {
359 Redacted(&self.0)
360 }
361
362 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#[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
407pub trait DisplayRedacted {
420 fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
423 fn fmt_unredacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
426
427 fn display_redacted(&self) -> impl std::fmt::Display + '_ {
435 DispRedacted(self)
436 }
437 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#[allow(clippy::exhaustive_structs)]
467#[derive(derive_more::AsRef)]
468pub struct DispRedacted<T: ?Sized>(pub T);
469
470#[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
498pub trait DebugRedacted {
511 fn fmt_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
514 fn fmt_unredacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
517}
518
519#[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 #![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)] 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 #[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}