Skip to main content

coqui_peer/
key.rs

1use crate::error::Error;
2use crate::id::PeerId;
3
4/// The most key material a store holds for one peer.
5pub const MAX_KEY_BYTES: usize = 64 * 1024;
6
7/// The public key material a method gives the trust store for one peer, with the name of the
8/// method that understands it.
9///
10/// The store keeps the bytes as they are and never interprets them: a PEM certificate's DER
11/// for `tls`, a raw public key for a key-based method. The peer's id is the SHA-256 of
12/// `bytes` ([`id`](KeyMaterial::id)); a method whose ids use another algorithm does not store
13/// its keys here.
14///
15/// Plain data: build it with [`new`](KeyMaterial::new) or the public fields.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct KeyMaterial {
18    /// The method name, lowercase letters, digits and `-`, 1 to 32 characters: `tls`.
19    pub method: String,
20    /// The PEM label the bytes are stored under, uppercase letters, digits and spaces:
21    /// `CERTIFICATE`. A standard label keeps the file readable by standard tools.
22    pub label: String,
23    /// The key bytes, at most [`MAX_KEY_BYTES`].
24    pub bytes: Vec<u8>,
25}
26
27impl KeyMaterial {
28    /// Checked key material.
29    ///
30    /// # Errors
31    ///
32    /// [`Error::Material`] when the method or label has characters outside the allowed set,
33    /// or `bytes` is empty or longer than [`MAX_KEY_BYTES`].
34    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    /// The id of the peer holding this key: the SHA-256 of the bytes.
71    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}