1use core::fmt;
2
3use std::ops::{Deref, DerefMut};
4use std::sync::atomic::{compiler_fence, Ordering};
5
6use crate::error::{Result, SecurityError};
7
8pub(crate) struct Zeroizing(Vec<u8>);
9
10impl Zeroizing {
11 pub(crate) fn new(bytes: Vec<u8>) -> Self {
12 Self(bytes)
13 }
14}
15
16impl Deref for Zeroizing {
17 type Target = Vec<u8>;
18
19 fn deref(&self) -> &Self::Target {
20 &self.0
21 }
22}
23
24impl DerefMut for Zeroizing {
25 fn deref_mut(&mut self) -> &mut Self::Target {
26 &mut self.0
27 }
28}
29
30impl Drop for Zeroizing {
31 fn drop(&mut self) {
32 for index in 0..self.0.capacity() {
33 unsafe {
34 self.0.as_mut_ptr().add(index).write_volatile(0);
35 }
36 }
37 compiler_fence(Ordering::SeqCst);
38 }
39}
40
41pub struct SecretBytes(Zeroizing);
42
43impl SecretBytes {
44 pub(crate) fn new(bytes: Zeroizing) -> Self {
45 Self(bytes)
46 }
47
48 pub fn as_bytes(&self) -> &[u8] {
49 &self.0
50 }
51
52 pub fn as_str(&self) -> Result<&str> {
53 std::str::from_utf8(&self.0)
54 .map_err(|_| SecurityError::InvalidArgument("secret is not valid UTF-8".to_owned()))
55 }
56
57 pub fn len(&self) -> usize {
58 self.0.len()
59 }
60
61 pub fn is_empty(&self) -> bool {
62 self.0.is_empty()
63 }
64}
65
66impl AsRef<[u8]> for SecretBytes {
67 fn as_ref(&self) -> &[u8] {
68 &self.0
69 }
70}
71
72impl fmt::Debug for SecretBytes {
73 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74 f.write_str("SecretBytes(<redacted>)")
75 }
76}
77
78#[cfg(test)]
79mod tests {
80 use super::*;
81
82 #[test]
83 fn debug_output_never_contains_the_secret() {
84 let secret = SecretBytes::new(Zeroizing::new(b"hunter2".to_vec()));
85 let rendered = format!("{secret:?} {secret:#?}");
86 assert!(!rendered.contains("hunter2"));
87 assert!(!rendered.contains("104"));
88 assert_eq!(rendered, "SecretBytes(<redacted>) SecretBytes(<redacted>)");
89 }
90
91 #[test]
92 fn exposes_bytes_and_utf8_views() {
93 let secret = SecretBytes::new(Zeroizing::new(vec![0xff, 0x00]));
94 assert_eq!(secret.as_bytes(), &[0xff, 0x00]);
95 assert_eq!(secret.len(), 2);
96 assert!(!secret.is_empty());
97 assert!(secret.as_str().is_err());
98 let text = SecretBytes::new(Zeroizing::new(b"secret".to_vec()));
99 assert_eq!(text.as_str().unwrap(), "secret");
100 }
101}