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