Skip to main content

coqui_peer/
pem.rs

1//! PEM blocks as the trust store writes them: header lines, then one block with
2//! 64-character base64 lines and LF line endings.
3
4/// One PEM block and the header lines before it.
5#[derive(Debug, Clone, PartialEq, Eq)]
6#[non_exhaustive]
7pub struct Block<'a> {
8    /// The lines before `-----BEGIN`, trimmed, in order.
9    pub headers: Vec<&'a str>,
10    /// The label: `CERTIFICATE` in `-----BEGIN CERTIFICATE-----`.
11    pub label: String,
12    /// The decoded bytes.
13    pub bytes: Vec<u8>,
14}
15
16/// Encodes `bytes` as a PEM block labelled `label`, with 64-character lines and LF line
17/// endings, ending in a newline.
18pub fn encode(label: &str, bytes: &[u8]) -> String {
19    let encoded = data_encoding::BASE64.encode(bytes);
20    let mut pem = format!("-----BEGIN {label}-----\n");
21    for chunk in encoded.as_bytes().chunks(64) {
22        pem.push_str(core::str::from_utf8(chunk).unwrap_or_default());
23        pem.push('\n');
24    }
25    pem.push_str(&format!("-----END {label}-----\n"));
26    pem
27}
28
29/// The first PEM block in `text` and the header lines before it; `None` when there is no
30/// complete block or its body is not base64.
31pub fn decode(text: &str) -> Option<Block<'_>> {
32    let mut headers = Vec::new();
33    let mut lines = text.lines();
34    let label = loop {
35        let line = lines.next()?.trim();
36        if let Some(label) = line
37            .strip_prefix("-----BEGIN ")
38            .and_then(|rest| rest.strip_suffix("-----"))
39        {
40            break label.to_owned();
41        }
42        headers.push(line);
43    };
44    let end = format!("-----END {label}-----");
45    let mut body = String::new();
46    loop {
47        let line = lines.next()?.trim();
48        if line == end {
49            break;
50        }
51        body.push_str(line);
52    }
53    let bytes = data_encoding::BASE64.decode(body.as_bytes()).ok()?;
54    Some(Block {
55        headers,
56        label,
57        bytes,
58    })
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn a_block_round_trips_with_its_headers() {
67        let pem = format!("Method: tls\n{}", encode("CERTIFICATE", &[7; 100]));
68        let block = decode(&pem).expect("a block");
69        assert_eq!(block.headers, ["Method: tls"]);
70        assert_eq!(block.label, "CERTIFICATE");
71        assert_eq!(block.bytes, vec![7; 100]);
72        assert!(pem.lines().all(|line| line.len() <= 64));
73        assert!(decode("-----BEGIN X-----\nAAAA\n").is_none());
74    }
75}