1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
//! Handling of secret values.
//!
//! This module provides a `Secret<T>` ensuring that sensitive values are not
//! `Debug`-printed by accident.

use std::fmt::{Debug, Formatter};

#[cfg(feature = "arbitrary")]
use arbitrary::Arbitrary;
#[cfg(feature = "bounded-static")]
use bounded_static::ToStatic;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// A wrapper to ensure that secrets are redacted during `Debug`-printing.
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
#[cfg_attr(feature = "bounded-static", derive(ToStatic))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
// Note: The implementation of these traits does agree:
//       `PartialEq` is just a thin wrapper that ensures constant-time comparison.
#[allow(clippy::derived_hash_with_manual_eq)]
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct Secret<T>(T);

impl<T> Secret<T> {
    /// Crate a new secret.
    pub fn new(inner: T) -> Self {
        Self(inner)
    }

    /// Expose the inner secret.
    pub fn declassify(&self) -> &T {
        &self.0
    }
}

impl<T> From<T> for Secret<T> {
    fn from(value: T) -> Self {
        Self::new(value)
    }
}

impl<T> Debug for Secret<T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        #[cfg(not(debug_assertions))]
        return write!(f, "/* REDACTED */");
        #[cfg(debug_assertions)]
        return self.0.fmt(f);
    }
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "ext_literal")]
    use crate::core::Literal;
    use crate::{
        command::{Command, CommandBody},
        core::{AString, Atom, Quoted},
    };

    #[test]
    #[cfg(not(debug_assertions))]
    #[allow(clippy::redundant_clone)]
    fn test_that_secret_is_redacted() {
        use super::Secret;
        #[cfg(feature = "ext_sasl_ir")]
        use crate::auth::AuthMechanism;
        use crate::auth::AuthenticateData;

        let secret = Secret("xyz123");
        let got = format!("{:?}", secret);
        println!("{}", got);
        assert!(!got.contains("xyz123"));

        println!("-----");

        let tests = vec![
            CommandBody::login("alice", "xyz123")
                .unwrap()
                .tag("A")
                .unwrap(),
            #[cfg(feature = "ext_sasl_ir")]
            CommandBody::authenticate_with_ir(AuthMechanism::PLAIN, b"xyz123".as_ref())
                .tag("A")
                .unwrap(),
        ];

        for test in tests.into_iter() {
            let got = format!("{:?}", test);
            println!("Debug: {}", got);
            assert!(got.contains("/* REDACTED */"));
            assert!(!got.contains("xyz123"));
            assert!(!got.contains("eHl6MTIz"));

            println!();
        }

        println!("-----");

        let tests = [
            AuthenticateData(Secret::new(b"xyz123".to_vec())),
            AuthenticateData(Secret::from(b"xyz123".to_vec())),
        ];

        for test in tests {
            let got = format!("{:?}", test);
            println!("Debug: {}", got);
            assert!(got.contains("/* REDACTED */"));
            assert!(!got.contains("xyz123"));
            assert!(!got.contains("eHl6MTIz"));
        }
    }

    #[test]
    fn test_that_secret_has_no_side_effects_on_eq() {
        assert_ne!(
            Command::new(
                "A",
                CommandBody::login(
                    AString::from(Atom::try_from("user").unwrap()),
                    AString::from(Atom::try_from("pass").unwrap()),
                )
                .unwrap(),
            ),
            Command::new(
                "A",
                CommandBody::login(
                    AString::from(Atom::try_from("user").unwrap()),
                    AString::from(Quoted::try_from("pass").unwrap()),
                )
                .unwrap(),
            )
        );

        #[cfg(feature = "ext_literal")]
        assert_ne!(
            Command::new(
                "A",
                CommandBody::login(
                    Literal::try_from("").unwrap(),
                    Literal::try_from("A").unwrap(),
                )
                .unwrap(),
            ),
            Command::new(
                "A",
                CommandBody::login(
                    Literal::try_from("").unwrap(),
                    Literal::try_from("A").unwrap().into_non_sync(),
                )
                .unwrap(),
            )
        );
    }
}