Files
CustosPublic/crates/custos-vault/src/secret.rs
T

112 lines
2.8 KiB
Rust

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use zeroize::Zeroizing;
/// A string that is wiped from memory when dropped and never printed.
/// `Debug` and `Display` give `[redacted]`; read it with [`SecretString::expose`].
#[derive(Clone, Default, PartialEq, Eq)]
pub struct SecretString(Zeroizing<String>);
impl SecretString {
pub fn new(s: String) -> Self {
Self(Zeroizing::new(s))
}
/// The plaintext. Keep the borrow short and do not copy it into ordinary `String`s.
pub fn expose(&self) -> &str {
&self.0
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl From<&str> for SecretString {
fn from(s: &str) -> Self {
Self::new(s.to_owned())
}
}
impl From<String> for SecretString {
fn from(s: String) -> Self {
Self::new(s)
}
}
impl fmt::Debug for SecretString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
impl fmt::Display for SecretString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
impl Serialize for SecretString {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&self.0)
}
}
impl<'de> Deserialize<'de> for SecretString {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
String::deserialize(d).map(Self::new)
}
}
/// Bytes that are wiped from memory when dropped and never printed (an attachment's content).
/// `Debug` gives `[redacted]`; serialized as base64.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct SecretBytes(Zeroizing<Vec<u8>>);
impl SecretBytes {
pub fn new(b: Vec<u8>) -> Self {
Self(Zeroizing::new(b))
}
/// The content. Keep the borrow short.
pub fn expose(&self) -> &[u8] {
&self.0
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl From<&[u8]> for SecretBytes {
fn from(b: &[u8]) -> Self {
Self::new(b.to_vec())
}
}
impl fmt::Debug for SecretBytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
impl Serialize for SecretBytes {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&Zeroizing::new(data_encoding::BASE64.encode(&self.0)))
}
}
impl<'de> Deserialize<'de> for SecretBytes {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = Zeroizing::new(String::deserialize(d)?);
data_encoding::BASE64
.decode(s.as_bytes())
.map(Self::new)
.map_err(|_| serde::de::Error::custom("attachment data is not base64"))
}
}