Skip to main content

coqui_peer_tls/
settings.rs

1//! The settings of the configuration builders as one value type, and the application protocol
2//! name they hold.
3
4use alloc::string::String;
5use alloc::vec::Vec;
6use core::fmt;
7use core::str::FromStr;
8
9use coqui_builder::{Describe, Leaf};
10
11use crate::error::PeerError;
12use crate::policy::Policy;
13
14/// The longest application protocol name, in bytes.
15const ALPN_MAX: usize = 255;
16
17/// An application protocol name (ALPN) of 1 to 255 bytes, held as text (`h2`, `coqui/1`).
18///
19/// A name that is not UTF-8 cannot be held. Its text form is the name itself.
20#[derive(Debug, Clone, PartialEq, Eq, Hash, Leaf)]
21pub struct Alpn(String);
22
23impl Alpn {
24    /// The name as the bytes a configuration carries.
25    pub fn as_bytes(&self) -> &[u8] {
26        self.0.as_bytes()
27    }
28
29    /// The name as text.
30    pub fn as_str(&self) -> &str {
31        &self.0
32    }
33}
34
35impl fmt::Display for Alpn {
36    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
37        formatter.write_str(&self.0)
38    }
39}
40
41impl FromStr for Alpn {
42    type Err = PeerError;
43
44    fn from_str(text: &str) -> Result<Self, Self::Err> {
45        if text.is_empty() || text.len() > ALPN_MAX {
46            return Err(PeerError::Policy(
47                "a protocol name of 1 to 255 bytes".to_owned(),
48            ));
49        }
50        Ok(Self(text.to_owned()))
51    }
52}
53
54impl TryFrom<&str> for Alpn {
55    type Error = PeerError;
56
57    /// The name `text`.
58    ///
59    /// # Errors
60    ///
61    /// [`PeerError::Policy`] for an empty name and one over 255 bytes.
62    fn try_from(text: &str) -> Result<Self, PeerError> {
63        text.parse()
64    }
65}
66
67impl TryFrom<&[u8]> for Alpn {
68    type Error = PeerError;
69
70    /// The name `bytes`, which must be UTF-8.
71    ///
72    /// # Errors
73    ///
74    /// [`PeerError::Policy`] for an empty name, one over 255 bytes, and bytes that are not UTF-8.
75    fn try_from(bytes: &[u8]) -> Result<Self, PeerError> {
76        core::str::from_utf8(bytes)
77            .map_err(|_| PeerError::Policy("a protocol name is text, not UTF-8 bytes".to_owned()))?
78            .parse()
79    }
80}
81
82/// What a configuration builder takes whole through `fill`: the application protocols and the
83/// [`Policy`], in the form a file, a form or a peer fills.
84///
85/// Identities, trust and verifiers are not settings: they hold keys and code, so a builder
86/// takes them as inputs. Every key is optional; an absent one is the default (no ALPN,
87/// [`Policy::default`]), and an unknown key is refused.
88///
89/// The type is [`Describe`]: a `coqui_builder::Partial<TlsSettings>` is filled from text (the
90/// `serde` feature reads TOML, JSON and the other serde formats) and built. The setters of its
91/// keys are methods of [`ServerBuilder`](crate::ServerBuilder) and
92/// [`ClientBuilder`](crate::ClientBuilder), and a builder of another crate that holds this type
93/// takes `TlsSettingsSetters` from [`prelude`](crate::prelude). It is `#[non_exhaustive]`: start
94/// from [`Default`] and assign the fields.
95#[derive(Debug, Clone, Default, PartialEq, Eq, Describe)]
96#[builder(setters_on = <'a> crate::config::ServerBuilder<'a>)]
97#[builder(setters_on = <'a> crate::config::ClientBuilder<'a>)]
98#[map(deny_unknown_fields)]
99#[non_exhaustive]
100pub struct TlsSettings {
101    /// The application protocols offered, most preferred first, as text (`h2`, `coqui/1`), each
102    /// 1 to 255 bytes.
103    #[map(default)]
104    pub alpn: Vec<Alpn>,
105    /// The policy configurations are built under.
106    #[map(default)]
107    pub policy: Policy,
108}
109
110impl TlsSettings {
111    /// The protocols as the bytes a configuration carries.
112    pub(crate) fn alpn_bytes(&self) -> Vec<Vec<u8>> {
113        self.alpn
114            .iter()
115            .map(|name| name.as_bytes().to_vec())
116            .collect()
117    }
118}