use ring::aead::{AES_256_GCM, Aad, LessSafeKey, Nonce, UnboundKey};
use ring::rand::{SecureRandom, SystemRandom};
use super::StorageError;
const V1: &str = "enc:v1:";
const NONCE: usize = 12;
#[derive(Clone, Default)]
pub enum Sealer {
#[default]
Plain,
Aead(std::sync::Arc<Aead>),
}
impl core::fmt::Debug for Sealer {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(match self {
Sealer::Plain => "Sealer::Plain",
Sealer::Aead(_) => "Sealer::Aead(<key>)",
})
}
}
#[allow(missing_debug_implementations)]
pub struct Aead {
key: LessSafeKey,
rng: SystemRandom,
}
impl Sealer {
pub fn plain() -> Self {
Self::Plain
}
pub fn with_key(key: &[u8]) -> Result<Self, StorageError> {
let unbound = UnboundKey::new(&AES_256_GCM, key).map_err(|_| {
StorageError::Unavailable(format!(
"a storage encryption key must be exactly {} bytes; got {}",
AES_256_GCM.key_len(),
key.len()
))
})?;
Ok(Self::Aead(std::sync::Arc::new(Aead {
key: LessSafeKey::new(unbound),
rng: SystemRandom::new(),
})))
}
pub fn is_sealing(&self) -> bool {
matches!(self, Sealer::Aead(_))
}
pub fn seal(&self, plaintext: &str) -> Result<String, StorageError> {
let Sealer::Aead(aead) = self else {
return Ok(plaintext.to_string());
};
let mut nonce = [0u8; NONCE];
aead.rng
.fill(&mut nonce)
.map_err(|_| StorageError::Unavailable("no randomness for a nonce".into()))?;
let mut buffer = plaintext.as_bytes().to_vec();
aead.key
.seal_in_place_append_tag(
Nonce::assume_unique_for_key(nonce),
Aad::empty(),
&mut buffer,
)
.map_err(|_| StorageError::Unavailable("could not seal a stored credential".into()))?;
let mut out = Vec::with_capacity(NONCE + buffer.len());
out.extend_from_slice(&nonce);
out.extend_from_slice(&buffer);
Ok(format!("{V1}{}", base64(&out)))
}
pub fn unseal(&self, stored: &str) -> Result<String, StorageError> {
let Some(encoded) = stored.strip_prefix(V1) else {
return Ok(stored.to_string());
};
let Sealer::Aead(aead) = self else {
return Err(StorageError::Unavailable(
"this row holds a sealed credential and no storage encryption key is configured"
.into(),
));
};
let raw = unbase64(encoded)
.ok_or_else(|| StorageError::Unavailable("a sealed credential is not base64".into()))?;
if raw.len() < NONCE + AES_256_GCM.tag_len() {
return Err(StorageError::Unavailable(
"a sealed credential is too short to be one".into(),
));
}
let (nonce, body) = raw.split_at(NONCE);
let nonce: [u8; NONCE] = nonce.try_into().expect("split at NONCE");
let mut buffer = body.to_vec();
let plaintext = aead
.key
.open_in_place(
Nonce::assume_unique_for_key(nonce),
Aad::empty(),
&mut buffer,
)
.map_err(|_| {
StorageError::Unavailable(
"a sealed credential did not decrypt; the storage encryption key has changed"
.into(),
)
})?;
String::from_utf8(plaintext.to_vec())
.map_err(|_| StorageError::Unavailable("a sealed credential is not UTF-8".into()))
}
pub fn seal_opt(&self, value: Option<&str>) -> Result<Option<String>, StorageError> {
value.map(|v| self.seal(v)).transpose()
}
pub fn unseal_opt(&self, value: Option<String>) -> Result<Option<String>, StorageError> {
value.map(|v| self.unseal(&v)).transpose()
}
}
fn base64(bytes: &[u8]) -> String {
use base64::Engine as _;
base64::engine::general_purpose::STANDARD.encode(bytes)
}
fn unbase64(s: &str) -> Option<Vec<u8>> {
use base64::Engine as _;
base64::engine::general_purpose::STANDARD.decode(s).ok()
}
#[cfg(test)]
mod tests {
use super::*;
fn sealer() -> Sealer {
Sealer::with_key(&[7u8; 32]).unwrap()
}
#[test]
fn a_sealed_value_round_trips() {
let s = sealer();
let sealed = s.seal("super-secret-token").unwrap();
assert_ne!(sealed, "super-secret-token");
assert!(sealed.starts_with(V1));
assert_eq!(s.unseal(&sealed).unwrap(), "super-secret-token");
}
#[test]
fn the_ciphertext_does_not_contain_the_plaintext() {
let sealed = sealer().seal("super-secret-token").unwrap();
assert!(
!sealed.contains("super-secret-token"),
"the point of the exercise"
);
}
#[test]
fn sealing_the_same_value_twice_gives_different_ciphertext() {
let s = sealer();
assert_ne!(s.seal("same").unwrap(), s.seal("same").unwrap());
}
#[test]
fn a_wrong_key_is_an_error_rather_than_a_wrong_answer() {
let sealed = sealer().seal("token").unwrap();
let other = Sealer::with_key(&[9u8; 32]).unwrap();
let err = other.unseal(&sealed).unwrap_err();
assert!(err.to_string().contains("key has changed"));
}
#[test]
fn a_tampered_ciphertext_is_refused() {
let s = sealer();
let sealed = s.seal("token").unwrap();
let mut raw = unbase64(sealed.strip_prefix(V1).unwrap()).unwrap();
let last = raw.len() - 1;
raw[last] ^= 0x01;
let tampered = format!("{V1}{}", base64(&raw));
assert!(s.unseal(&tampered).is_err());
}
#[test]
fn plaintext_passes_through_both_ways_when_no_key_is_configured() {
let s = Sealer::plain();
assert_eq!(s.seal("token").unwrap(), "token");
assert_eq!(s.unseal("token").unwrap(), "token");
assert!(!s.is_sealing());
}
#[test]
fn a_row_written_before_a_key_was_configured_still_reads() {
assert_eq!(
sealer().unseal("legacy-plaintext").unwrap(),
"legacy-plaintext"
);
}
#[test]
fn a_sealed_row_is_refused_rather_than_returned_when_the_key_is_gone() {
let sealed = sealer().seal("token").unwrap();
let err = Sealer::plain().unseal(&sealed).unwrap_err();
assert!(err.to_string().contains("no storage encryption key"));
}
#[test]
fn a_key_of_the_wrong_length_is_refused_by_name() {
let err = Sealer::with_key(&[0u8; 16]).unwrap_err();
assert!(err.to_string().contains("exactly 32 bytes"));
}
#[test]
fn the_key_never_appears_in_debug_output() {
let rendered = format!("{:?}", sealer());
assert_eq!(rendered, "Sealer::Aead(<key>)");
}
#[test]
fn an_optional_value_seals_and_unseals_as_one() {
let s = sealer();
assert_eq!(s.seal_opt(None).unwrap(), None);
let sealed = s.seal_opt(Some("t")).unwrap();
assert_eq!(s.unseal_opt(sealed).unwrap(), Some("t".to_string()));
}
}