Skip to main content

securer_string/secure_types/
string.rs

1use core::fmt;
2use std::str::FromStr;
3
4use crate::SecureVec;
5use crate::secure_utils::memlock;
6
7/// Wrapper for a vector that stores a valid UTF-8 string
8#[derive(Clone)]
9pub struct SecureString(SecureVec<u8>);
10
11impl SecureString {
12    /// Borrow the contents of the string.
13    #[must_use]
14    pub fn unsecure(&self) -> &str {
15        // SAFETY: SecureString can only be constructed from valid UTF-8 (String or
16        // &str), and the contents cannot be modified as non-UTF-8, so they
17        // remain valid UTF-8.
18        unsafe { std::str::from_utf8_unchecked(self.0.unsecure()) }
19    }
20
21    /// Mutably borrow the contents of the string.
22    pub fn unsecure_mut(&mut self) -> &mut str {
23        // SAFETY: Same as `unsecure` - contents are always valid UTF-8.
24        unsafe { std::str::from_utf8_unchecked_mut(self.0.unsecure_mut()) }
25    }
26
27    /// Turn the string into a regular `String` again.
28    #[must_use]
29    pub fn into_unsecure(mut self) -> String {
30        memlock::munlock(self.0.content.as_mut_ptr(), self.0.content.capacity());
31        let content = std::mem::take(&mut self.0.content);
32        std::mem::forget(self);
33        // SAFETY: Same as `unsecure` - contents are always valid UTF-8.
34        unsafe { String::from_utf8_unchecked(content) }
35    }
36
37    /// Overwrite the string with zeros. This is automatically called in the
38    /// destructor.
39    ///
40    /// This also sets the length to `0`.
41    pub fn zero_out(&mut self) {
42        self.0.zero_out();
43    }
44}
45
46impl PartialEq for SecureString {
47    fn eq(&self, other: &SecureString) -> bool {
48        // use constant-time implementation of SecureVec
49        self.0 == other.0
50    }
51}
52
53impl Eq for SecureString {}
54
55impl fmt::Debug for SecureString {
56    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
57        f.write_str("***SECRET***").map_err(|_| fmt::Error)
58    }
59}
60
61impl fmt::Display for SecureString {
62    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
63        f.write_str("***SECRET***").map_err(|_| fmt::Error)
64    }
65}
66
67impl<U> From<U> for SecureString
68where
69    U: Into<String>,
70{
71    fn from(s: U) -> SecureString {
72        SecureString(SecureVec::new(s.into().into_bytes()))
73    }
74}
75
76impl FromStr for SecureString {
77    type Err = std::convert::Infallible;
78
79    fn from_str(s: &str) -> Result<Self, Self::Err> {
80        Ok(SecureString(SecureVec::new(s.into())))
81    }
82}
83
84#[cfg(feature = "serde")]
85impl serde::Serialize for SecureString {
86    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
87    where
88        S: serde::Serializer,
89    {
90        serializer.serialize_str(self.unsecure())
91    }
92}
93
94#[cfg(feature = "serde")]
95impl<'de> serde::Deserialize<'de> for SecureString {
96    fn deserialize<D>(deserializer: D) -> Result<SecureString, D::Error>
97    where
98        D: serde::Deserializer<'de>,
99    {
100        struct SecureStringVisitor;
101        impl<'de> serde::de::Visitor<'de> for SecureStringVisitor {
102            type Value = SecureString;
103            fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
104                write!(formatter, "an utf-8 encoded string")
105            }
106            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
107            where
108                E: serde::de::Error,
109            {
110                Ok(SecureString::from(v.to_string()))
111            }
112        }
113        deserializer.deserialize_string(SecureStringVisitor)
114    }
115}