Skip to main content

security/
secret.rs

1use core::fmt;
2
3use zeroize::Zeroizing;
4
5use crate::error::{Result, SecurityError};
6
7pub struct SecretBytes(Zeroizing<Vec<u8>>);
8
9impl SecretBytes {
10    pub(crate) fn new(bytes: Zeroizing<Vec<u8>>) -> Self {
11        Self(bytes)
12    }
13
14    pub fn as_bytes(&self) -> &[u8] {
15        &self.0
16    }
17
18    pub fn as_str(&self) -> Result<&str> {
19        std::str::from_utf8(&self.0)
20            .map_err(|_| SecurityError::InvalidArgument("secret is not valid UTF-8".to_owned()))
21    }
22
23    pub fn len(&self) -> usize {
24        self.0.len()
25    }
26
27    pub fn is_empty(&self) -> bool {
28        self.0.is_empty()
29    }
30}
31
32impl AsRef<[u8]> for SecretBytes {
33    fn as_ref(&self) -> &[u8] {
34        &self.0
35    }
36}
37
38impl fmt::Debug for SecretBytes {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        f.write_str("SecretBytes(<redacted>)")
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47
48    #[test]
49    fn debug_output_never_contains_the_secret() {
50        let secret = SecretBytes::new(Zeroizing::new(b"hunter2".to_vec()));
51        let rendered = format!("{secret:?} {secret:#?}");
52        assert!(!rendered.contains("hunter2"));
53        assert!(!rendered.contains("104"));
54        assert_eq!(rendered, "SecretBytes(<redacted>) SecretBytes(<redacted>)");
55    }
56
57    #[test]
58    fn exposes_bytes_and_utf8_views() {
59        let secret = SecretBytes::new(Zeroizing::new(vec![0xff, 0x00]));
60        assert_eq!(secret.as_bytes(), &[0xff, 0x00]);
61        assert_eq!(secret.len(), 2);
62        assert!(!secret.is_empty());
63        assert!(secret.as_str().is_err());
64        let text = SecretBytes::new(Zeroizing::new(b"secret".to_vec()));
65        assert_eq!(text.as_str().unwrap(), "secret");
66    }
67}