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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
use std::{
    borrow::Cow,
    fmt::{Debug, Formatter},
};

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

use crate::core::{AString, IString, Literal};

#[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, Hash)]
pub struct Secret<T>(T);

/// A trait to ensure that secrets are neither logged nor compared in non-constant time.
impl<T> Secret<T> {
    /// Crate a new secret.
    pub fn new(inner: T) -> Self {
        Self(inner)
    }

    /// Expose the inner secret (opting-out of all guarantees).
    pub fn declassify(&self) -> &T {
        &self.0
    }
}

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

impl<T> Secret<T>
where
    T: AsRef<[u8]>,
{
    /// Compare this secret value with another value in constant time.
    ///
    /// Note: The comparison is made by converting both values as bytes first.
    pub fn compare_with<B>(&self, other: B) -> bool
    where
        B: AsRef<[u8]>,
    {
        self.declassify().as_ref().ct_eq(other.as_ref()).unwrap_u8() == 1
    }
}

impl<T> PartialEq for Secret<T>
where
    T: CompareCT<T>,
{
    fn eq(&self, other: &Self) -> bool {
        self.declassify().compare_ct(&other.0)
    }
}

impl<T> Eq for Secret<T> where T: CompareCT<T> {}

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);
    }
}

pub trait CompareCT<T> {
    #[must_use]
    fn compare_ct(&self, other: &T) -> bool;
}

impl<'a, T> CompareCT<T> for Cow<'a, [u8]>
where
    T: AsRef<[u8]>,
{
    fn compare_ct(&self, other: &T) -> bool {
        self.as_ref().ct_eq(other.as_ref()).unwrap_u8() == 1
    }
}

impl<T> CompareCT<T> for Vec<u8>
where
    T: AsRef<[u8]>,
{
    fn compare_ct(&self, other: &T) -> bool {
        self.as_slice().ct_eq(other.as_ref()).unwrap_u8() == 1
    }
}

impl<'a> CompareCT<AString<'a>> for AString<'a> {
    fn compare_ct(&self, other: &AString<'a>) -> bool {
        match (self, other) {
            (AString::Atom(lhs), AString::Atom(rhs)) => {
                lhs.as_ref()
                    .as_bytes()
                    .ct_eq(rhs.as_ref().as_bytes())
                    .unwrap_u8()
                    == 1
            }
            (AString::String(lhs), AString::String(rhs)) => lhs.compare_ct(rhs),
            _ => false,
        }
    }
}

impl<'a> CompareCT<IString<'a>> for IString<'a> {
    fn compare_ct(&self, other: &IString<'a>) -> bool {
        match (self, other) {
            (IString::Quoted(lhs), IString::Quoted(rhs)) => {
                lhs.as_ref()
                    .as_bytes()
                    .ct_eq(rhs.as_ref().as_bytes())
                    .unwrap_u8()
                    == 1
            }
            (IString::Literal(lhs), IString::Literal(rhs)) => lhs.compare_ct(rhs),
            _ => false,
        }
    }
}

impl<'a> CompareCT<Literal<'a>> for Literal<'a> {
    fn compare_ct(&self, other: &Literal<'a>) -> bool {
        #[cfg(not(feature = "ext_literal"))]
        return self.as_ref().ct_eq(other.as_ref()).unwrap_u8() == 1;
        #[cfg(feature = "ext_literal")]
        return self.as_ref().ct_eq(other.as_ref()).unwrap_u8() == 1 && self.sync == other.sync;
    }
}

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

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

        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(AuthMechanism::Plain, Some(b"xyz123"))
                .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"));
        }
    }

    /// A best effort test to ensure that constant-time comparison works.
    #[test]
    #[allow(clippy::redundant_clone)]
    fn test_that_eq_is_constant_time() {
        let took_constant = {
            fn compare_eq(a: Secret<AString>, b: Secret<AString>) -> u128 {
                let tik = std::time::Instant::now();
                assert_eq!(a, b);
                let tok = std::time::Instant::now();

                tok.duration_since(tik).as_nanos()
            }

            fn compare_ne(a: Secret<AString>, b: Secret<AString>) -> u128 {
                let tik = std::time::Instant::now();
                assert_ne!(a, b);
                let tok = std::time::Instant::now();

                tok.duration_since(tik).as_nanos()
            }

            let a = Secret::new(AString::from(Atom::unchecked(str::repeat(
                "A",
                1024 * 1024,
            ))));
            let b = Secret::new(AString::from(Atom::unchecked(str::repeat(
                "B",
                1024 * 1024,
            ))));

            let took1 = compare_eq(a.clone(), a.clone());
            println!("{}", took1);
            let took2 = compare_ne(a.clone(), b.clone());
            println!("{}", took2);
            let took3 = compare_ne(b.clone(), a.clone());
            println!("{}", took3);
            let took4 = compare_eq(b.clone(), b.clone());
            println!("{}", took4);

            (took1 + took2 + took3 + took4) / 4
        };

        let took_variable = {
            fn compare_eq(a: String, b: String) -> u128 {
                let tik = std::time::Instant::now();
                assert_eq!(a, b);
                let tok = std::time::Instant::now();

                tok.duration_since(tik).as_nanos()
            }

            fn compare_ne(a: String, b: String) -> u128 {
                let tik = std::time::Instant::now();
                assert_ne!(a, b);
                let tok = std::time::Instant::now();

                tok.duration_since(tik).as_nanos()
            }

            let a = str::repeat("A", 1024 * 1024);
            let b = str::repeat("B", 1024 * 1024);

            let took1 = compare_eq(a.clone(), a.clone());
            println!("{}", took1);
            let took2 = compare_ne(a.clone(), b.clone());
            println!("{}", took2);
            let took3 = compare_ne(b.clone(), a.clone());
            println!("{}", took3);
            let took4 = compare_eq(b.clone(), b.clone());
            println!("{}", took4);

            (took1 + took2 + took3 + took4) / 4
        };

        let times = took_constant / took_variable;
        println!("{took_constant} vs {took_variable} ({times} times slower)");
        if times < 10 {
            panic!("expected slowdown >= 10, got {}", times);
        }
    }

    #[test]
    fn test_that_secret_has_no_side_effects_on_eq() {
        assert_ne!(
            Command::new(
                "A",
                CommandBody::login(
                    AString::from(Atom::unchecked("user")),
                    AString::from(Atom::unchecked("pass")),
                )
                .unwrap(),
            ),
            Command::new(
                "A",
                CommandBody::login(
                    AString::from(Atom::unchecked("user")),
                    AString::from(Quoted::unchecked("pass")),
                )
                .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(),
            )
        );
    }
}