Skip to main content

bornera_rustls/
config.rs

1//! Immutable rustls connection configuration and accounted memory bounds.
2
3use std::{io, num::NonZeroUsize, sync::Arc};
4
5use bornera::{TransportLimits, TransportPressure};
6use calandria::RetainedBytes;
7use rustls::{ClientConfig, pki_types::ServerName};
8
9/// Stable per-connection charges for rustls-owned variable memory.
10#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11pub struct RustlsTransportLimits {
12    application_write_buffer_bytes: NonZeroUsize,
13    max_tls_egress_bytes: NonZeroUsize,
14    max_plaintext_bytes: NonZeroUsize,
15    pressure: TransportPressure,
16}
17
18impl RustlsTransportLimits {
19    /// Creates mechanically enforced logical-buffer bounds and one stable memory charge.
20    ///
21    /// The application-write bound is applied through rustls's buffer limit. The
22    /// egress and readable-plaintext bounds are checked after every rustls state
23    /// transition. `pressure` is the caller-audited conservative charge for rustls's
24    /// private allocation capacities and per-connection cryptographic state; rustls
25    /// does not expose those capacities for mechanical measurement. The outbound and
26    /// plaintext charges must cover their logical maxima, while inbound and protocol
27    /// charges must cover the exact rustls version, provider, and client configuration.
28    pub fn new(
29        application_write_buffer_bytes: NonZeroUsize,
30        max_tls_egress_bytes: NonZeroUsize,
31        max_plaintext_bytes: NonZeroUsize,
32        pressure: TransportPressure,
33    ) -> Result<Self, RustlsTransportLimitsError> {
34        if pressure.inbound() == RetainedBytes::ZERO {
35            return Err(RustlsTransportLimitsError::MissingInboundCharge);
36        }
37        if pressure.protocol() == RetainedBytes::ZERO {
38            return Err(RustlsTransportLimitsError::MissingProtocolCharge);
39        }
40        let application_write = u64::try_from(application_write_buffer_bytes.get())
41            .map(RetainedBytes::new)
42            .map_err(|_| RustlsTransportLimitsError::AddressSpace)?;
43        let readable_plaintext = u64::try_from(max_plaintext_bytes.get())
44            .map(RetainedBytes::new)
45            .map_err(|_| RustlsTransportLimitsError::AddressSpace)?;
46        let Some(minimum_plaintext) = application_write.checked_add(readable_plaintext) else {
47            return Err(RustlsTransportLimitsError::AddressSpace);
48        };
49        if pressure.plaintext() < minimum_plaintext {
50            return Err(RustlsTransportLimitsError::PlaintextCharge {
51                minimum: minimum_plaintext,
52                supplied: pressure.plaintext(),
53            });
54        }
55        let max_tls_egress = u64::try_from(max_tls_egress_bytes.get())
56            .map(RetainedBytes::new)
57            .map_err(|_| RustlsTransportLimitsError::AddressSpace)?;
58        if pressure.outbound() < max_tls_egress {
59            return Err(RustlsTransportLimitsError::EgressCharge {
60                minimum: max_tls_egress,
61                supplied: pressure.outbound(),
62            });
63        }
64        Ok(Self {
65            application_write_buffer_bytes,
66            max_tls_egress_bytes,
67            max_plaintext_bytes,
68            pressure,
69        })
70    }
71
72    /// Returns the hard rustls application-write buffer limit.
73    pub const fn application_write_buffer_bytes(self) -> NonZeroUsize {
74        self.application_write_buffer_bytes
75    }
76
77    /// Returns the maximum observable encrypted output retained by rustls.
78    pub const fn max_tls_egress_bytes(self) -> NonZeroUsize {
79        self.max_tls_egress_bytes
80    }
81
82    /// Returns the maximum observable application plaintext retained by rustls.
83    pub const fn max_plaintext_bytes(self) -> NonZeroUsize {
84        self.max_plaintext_bytes
85    }
86
87    /// Returns the stable caller-audited rustls retained-memory charge.
88    pub const fn pressure(self) -> TransportPressure {
89        self.pressure
90    }
91
92    /// Returns the exact aggregate charge advertised to Bornera.
93    pub const fn transport_limits(self) -> TransportLimits {
94        TransportLimits::new(self.pressure.total())
95    }
96}
97
98/// Invalid rustls transport-memory accounting configuration.
99#[derive(Clone, Copy, Debug, Eq, PartialEq)]
100#[non_exhaustive]
101pub enum RustlsTransportLimitsError {
102    /// The platform pointer width cannot fit the fixed retained-byte domain.
103    AddressSpace,
104    /// No conservative charge was supplied for rustls's private encoded-input storage.
105    MissingInboundCharge,
106    /// No conservative charge was supplied for rustls and provider protocol state.
107    MissingProtocolCharge,
108    /// The configured outbound charge cannot cover the observable TLS-egress bound.
109    EgressCharge {
110        /// Minimum charge required by the configured logical bound.
111        minimum: RetainedBytes,
112        /// Outbound charge supplied by the caller.
113        supplied: RetainedBytes,
114    },
115    /// The configured plaintext charge cannot cover both plaintext buffer bounds.
116    PlaintextCharge {
117        /// Minimum charge required by the configured logical bounds.
118        minimum: RetainedBytes,
119        /// Plaintext charge supplied by the caller.
120        supplied: RetainedBytes,
121    },
122}
123
124/// Immutable configuration for one logical TLS server identity.
125#[derive(Clone, Debug)]
126pub struct RustlsTransportConfig {
127    client: Arc<ClientConfig>,
128    server_name: ServerName<'static>,
129    limits: RustlsTransportLimits,
130}
131
132impl RustlsTransportConfig {
133    /// Creates configuration from an already validated owned server name.
134    pub fn new(
135        client: Arc<ClientConfig>,
136        server_name: ServerName<'static>,
137        limits: RustlsTransportLimits,
138    ) -> Self {
139        Self {
140            client,
141            server_name,
142            limits,
143        }
144    }
145
146    /// Validates and owns one DNS name or IP address for certificate verification and SNI.
147    pub fn for_server_name(
148        client: Arc<ClientConfig>,
149        server_name: &str,
150        limits: RustlsTransportLimits,
151    ) -> Result<Self, RustlsConfigError> {
152        let server_name = ServerName::try_from(server_name.to_owned())
153            .map_err(|_| RustlsConfigError::InvalidServerName)?;
154        Ok(Self::new(client, server_name, limits))
155    }
156
157    /// Returns the shared rustls client configuration.
158    pub fn client_config(&self) -> &Arc<ClientConfig> {
159        &self.client
160    }
161
162    /// Returns the owned logical server identity.
163    pub const fn server_name(&self) -> &ServerName<'static> {
164        &self.server_name
165    }
166
167    /// Returns the exact per-connection transport limits.
168    pub const fn limits(&self) -> RustlsTransportLimits {
169        self.limits
170    }
171}
172
173/// Invalid logical TLS configuration established before socket acquisition.
174#[derive(Clone, Copy, Debug, Eq, PartialEq)]
175#[non_exhaustive]
176pub enum RustlsConfigError {
177    /// The logical server identity is not a valid DNS name or IP address.
178    InvalidServerName,
179}
180
181/// Failure before one rustls transport becomes registered or observable.
182#[derive(Debug)]
183#[non_exhaustive]
184pub enum RustlsConnectError {
185    /// The configured adapter charge exceeds the Bornera slot ceiling.
186    Capacity {
187        /// Charge required by this rustls adapter configuration.
188        required: RetainedBytes,
189        /// Ceiling supplied by the exact Bornera connection slot.
190        supplied: RetainedBytes,
191    },
192    /// Rustls's initial logical buffers exceeded their configured bound.
193    Transport(bornera::TransportDiagnostic),
194    /// Rustls rejected construction of the client connection.
195    Tls(rustls::Error),
196    /// The operating system rejected creation of the nonblocking TCP stream.
197    Io(io::Error),
198}