use std::borrow::Borrow;
use std::{fmt, io};
use crate::envelope::{self, Context, Key, KeyError};
use crate::ids::{KeyId, TenantId};
pub mod blob;
use blob::{Blob, BlobError, WrapRef};
#[derive(Debug)]
#[non_exhaustive]
pub enum WrapError {
Damaged,
Memory(io::Error),
Elsewhere {
wrap_ref: Option<String>,
},
Blob(BlobError),
}
impl fmt::Display for WrapError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
WrapError::Damaged => f.write_str("a wrapped tenant key did not open"),
WrapError::Memory(_) => {
f.write_str("the key's memory could not be locked or kept out of core dumps")
}
WrapError::Elsewhere { wrap_ref: None } => f.write_str(
"the key is wrapped under the master key file, not under the key backend's key",
),
WrapError::Elsewhere {
wrap_ref: Some(wrap_ref),
} => write!(
f,
"the key is wrapped under the key backend key {wrap_ref}, not under this \
backend's key"
),
WrapError::Blob(_) => f.write_str("a key-wrap blob could not be read or made"),
}
}
}
impl std::error::Error for WrapError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
WrapError::Memory(e) => Some(e),
WrapError::Blob(e) => Some(e),
WrapError::Damaged | WrapError::Elsewhere { .. } => None,
}
}
}
fn from_key_error(e: KeyError) -> WrapError {
match e {
KeyError::Memory(e) => WrapError::Memory(e),
KeyError::Damaged | KeyError::Read(_) | KeyError::Refused(_) | KeyError::WrongSize => {
WrapError::Damaged
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct WrappedKek {
pub wrap_ref: String,
pub blob: Vec<u8>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Wrapped {
pub key: Vec<u8>,
pub kek: Option<WrappedKek>,
}
pub trait KeyWrap: Send + Sync + fmt::Debug {
fn key_id(&self) -> KeyId;
fn root(&self) -> &Key;
fn wrap(&self, tenant: TenantId, key: &Key) -> Result<Wrapped, WrapError>;
fn unwrap(
&self,
tenant: TenantId,
wrapped: &[u8],
kek: Option<&WrappedKek>,
) -> Result<Key, WrapError>;
}
#[derive(Debug)]
pub struct FileWrap<K = Key> {
master: K,
}
impl FileWrap {
#[must_use]
pub fn new(master: Key) -> FileWrap {
FileWrap { master }
}
}
impl<'a> FileWrap<&'a Key> {
#[must_use]
pub fn borrowing(master: &'a Key) -> FileWrap<&'a Key> {
FileWrap { master }
}
}
impl<K: Borrow<Key> + Send + Sync + fmt::Debug> KeyWrap for FileWrap<K> {
fn key_id(&self) -> KeyId {
self.master.borrow().id()
}
fn root(&self) -> &Key {
self.master.borrow()
}
fn wrap(&self, tenant: TenantId, key: &Key) -> Result<Wrapped, WrapError> {
Ok(Wrapped {
key: envelope::wrap(self.master.borrow(), &Context::Tenant { tenant }, key),
kek: None,
})
}
fn unwrap(
&self,
tenant: TenantId,
wrapped: &[u8],
kek: Option<&WrappedKek>,
) -> Result<Key, WrapError> {
if let Some(kek) = kek {
return Err(WrapError::Elsewhere {
wrap_ref: Some(kek.wrap_ref.clone()),
});
}
envelope::unwrap(self.master.borrow(), &Context::Tenant { tenant }, wrapped)
.map_err(from_key_error)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum WrapContext {
Registry,
Tenant(TenantId),
}
pub trait Backend: Send + Sync + fmt::Debug {
fn reference(&self) -> WrapRef;
fn wrap(&self, ctx: WrapContext, key: &Key) -> Result<Vec<u8>, WrapError>;
fn unwrap(&self, ctx: WrapContext, blob: &Blob) -> Result<Key, WrapError>;
}
#[derive(Debug)]
pub struct BackendWrap<B> {
backend: B,
reference: WrapRef,
root: Key,
}
impl<B: Backend> BackendWrap<B> {
pub fn create(backend: B) -> Result<(BackendWrap<B>, Vec<u8>), WrapError> {
let root = Key::generate().map_err(from_key_error)?;
let reference = backend.reference();
let ciphertext = backend.wrap(WrapContext::Registry, &root)?;
let blob = Blob::new(reference.clone(), ciphertext).map_err(WrapError::Blob)?;
Ok((
BackendWrap {
backend,
reference,
root,
},
blob.encode(),
))
}
pub fn open(backend: B, root_blob: &[u8]) -> Result<BackendWrap<B>, WrapError> {
let reference = backend.reference();
let blob = under(&reference, root_blob)?;
let root = backend.unwrap(WrapContext::Registry, &blob)?;
Ok(BackendWrap {
backend,
reference,
root,
})
}
}
fn under(reference: &WrapRef, bytes: &[u8]) -> Result<Blob, WrapError> {
let blob = Blob::decode(bytes).map_err(WrapError::Blob)?;
if blob.reference() != reference {
return Err(WrapError::Elsewhere {
wrap_ref: Some(blob.reference().to_string()),
});
}
Ok(blob)
}
impl<B: Backend> KeyWrap for BackendWrap<B> {
fn key_id(&self) -> KeyId {
self.root.id()
}
fn root(&self) -> &Key {
&self.root
}
fn wrap(&self, tenant: TenantId, key: &Key) -> Result<Wrapped, WrapError> {
let kek = Key::generate().map_err(from_key_error)?;
let wrapped = envelope::wrap(&kek, &Context::Tenant { tenant }, key);
let ciphertext = self.backend.wrap(WrapContext::Tenant(tenant), &kek)?;
let blob = Blob::new(self.reference.clone(), ciphertext).map_err(WrapError::Blob)?;
Ok(Wrapped {
key: wrapped,
kek: Some(WrappedKek {
wrap_ref: self.reference.to_string(),
blob: blob.encode(),
}),
})
}
fn unwrap(
&self,
tenant: TenantId,
wrapped: &[u8],
kek: Option<&WrappedKek>,
) -> Result<Key, WrapError> {
let kek = kek.ok_or(WrapError::Elsewhere { wrap_ref: None })?;
let blob = under(&self.reference, &kek.blob)?;
if blob.reference().to_string() != kek.wrap_ref {
return Err(WrapError::Damaged);
}
let kek = self.backend.unwrap(WrapContext::Tenant(tenant), &blob)?;
envelope::unwrap(&kek, &Context::Tenant { tenant }, wrapped).map_err(from_key_error)
}
}
#[cfg(test)]
pub(crate) mod testing;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod backend_tests;