1use crate::error::Error;
2use crate::id::PeerId;
3
4pub const MAX_KEY_BYTES: usize = 64 * 1024;
6
7#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct KeyMaterial {
18 pub method: String,
20 pub label: String,
23 pub bytes: Vec<u8>,
25}
26
27impl KeyMaterial {
28 pub fn new(
35 method: impl Into<String>,
36 label: impl Into<String>,
37 bytes: impl Into<Vec<u8>>,
38 ) -> Result<Self, Error> {
39 let key = Self {
40 method: method.into(),
41 label: label.into(),
42 bytes: bytes.into(),
43 };
44 key.check()?;
45 Ok(key)
46 }
47
48 pub(crate) fn check(&self) -> Result<(), Error> {
49 let method = !self.method.is_empty()
50 && self.method.len() <= 32
51 && self
52 .method
53 .bytes()
54 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
55 let label = !self.label.is_empty()
56 && self.label.len() <= 64
57 && !self.label.starts_with(' ')
58 && !self.label.ends_with(' ')
59 && self
60 .label
61 .bytes()
62 .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b' ');
63 if method && label && !self.bytes.is_empty() && self.bytes.len() <= MAX_KEY_BYTES {
64 Ok(())
65 } else {
66 Err(Error::Material)
67 }
68 }
69
70 pub fn id(&self) -> PeerId {
72 PeerId::of(&self.bytes)
73 }
74}
75
76#[cfg(test)]
77mod tests {
78 use super::*;
79
80 #[test]
81 fn material_is_checked() {
82 assert!(KeyMaterial::new("tls", "CERTIFICATE", [1]).is_ok());
83 for (method, label, bytes) in [
84 ("TLS", "CERTIFICATE", vec![1]),
85 ("", "CERTIFICATE", vec![1]),
86 ("tls", "certificate", vec![1]),
87 ("tls", "CERTIFICATE", vec![]),
88 ("tls", "CERTIFICATE", vec![0; MAX_KEY_BYTES + 1]),
89 ] {
90 assert!(KeyMaterial::new(method, label, bytes).is_err());
91 }
92 }
93}