use crate::error::Error;
use crate::id::PeerId;
pub const MAX_KEY_BYTES: usize = 64 * 1024;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyMaterial {
pub method: String,
pub label: String,
pub bytes: Vec<u8>,
}
impl KeyMaterial {
pub fn new(
method: impl Into<String>,
label: impl Into<String>,
bytes: impl Into<Vec<u8>>,
) -> Result<Self, Error> {
let key = Self {
method: method.into(),
label: label.into(),
bytes: bytes.into(),
};
key.check()?;
Ok(key)
}
pub(crate) fn check(&self) -> Result<(), Error> {
let method = !self.method.is_empty()
&& self.method.len() <= 32
&& self
.method
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
let label = !self.label.is_empty()
&& self.label.len() <= 64
&& !self.label.starts_with(' ')
&& !self.label.ends_with(' ')
&& self
.label
.bytes()
.all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b' ');
if method && label && !self.bytes.is_empty() && self.bytes.len() <= MAX_KEY_BYTES {
Ok(())
} else {
Err(Error::Material)
}
}
pub fn id(&self) -> PeerId {
PeerId::of(&self.bytes)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn material_is_checked() {
assert!(KeyMaterial::new("tls", "CERTIFICATE", [1]).is_ok());
for (method, label, bytes) in [
("TLS", "CERTIFICATE", vec![1]),
("", "CERTIFICATE", vec![1]),
("tls", "certificate", vec![1]),
("tls", "CERTIFICATE", vec![]),
("tls", "CERTIFICATE", vec![0; MAX_KEY_BYTES + 1]),
] {
assert!(KeyMaterial::new(method, label, bytes).is_err());
}
}
}