Skip to main content

riffdb_client_rust/
tls.rs

1//! Verified direct-TLS channel construction from the closed deployment config.
2
3use std::error::Error;
4use std::fmt;
5use std::fs;
6use std::io::Read;
7#[cfg(unix)]
8use std::os::unix::fs::{MetadataExt, PermissionsExt};
9use std::path::Path;
10
11use riffdb_config::{ClientTlsIdentity, ClientTrustRootConfig, TlsClientConfig};
12use rustls_pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject};
13use tonic::transport::{Certificate, ClientTlsConfig as TonicTlsConfig, Endpoint, Identity};
14use zeroize::Zeroizing;
15
16use crate::{ClientError, RiffDbClient};
17
18const MAX_TRUST_ROOT_BYTES: u64 = 1_024 * 1_024;
19const MAX_CLIENT_PRIVATE_KEY_BYTES: u64 = 65_536;
20const MAX_TRUST_ROOT_CERTIFICATES: usize = 512;
21const DEFAULT_REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
22const SYSTEM_CA_BUNDLE_CANDIDATES: &[&str] = &[
23    "/etc/ssl/certs/ca-certificates.crt",
24    "/etc/pki/tls/certs/ca-bundle.crt",
25    "/etc/ssl/cert.pem",
26    "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
27    "/etc/ssl/ca-bundle.pem",
28];
29
30#[derive(Clone, Debug, Eq, PartialEq)]
31struct TrustRootFileIdentity {
32    bytes: u64,
33    #[cfg(unix)]
34    device: u64,
35    #[cfg(unix)]
36    inode: u64,
37    #[cfg(unix)]
38    modified_seconds: i64,
39    #[cfg(unix)]
40    modified_nanoseconds: i64,
41    #[cfg(not(unix))]
42    modified_since_epoch: Option<std::time::Duration>,
43}
44
45struct TrustRootSnapshot {
46    bytes: Vec<u8>,
47    identity: TrustRootFileIdentity,
48}
49
50impl fmt::Debug for TrustRootSnapshot {
51    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
52        formatter
53            .debug_struct("TrustRootSnapshot")
54            .field("bytes", &"[TRUST ROOT]")
55            .field("identity", &self.identity)
56            .finish()
57    }
58}
59
60/// Closed, path-redacted failure while constructing a verified TLS channel.
61#[derive(Clone, Copy, Debug, Eq, PartialEq)]
62pub enum TlsClientFailure {
63    /// The configured trust-root file was absent, replaced, empty, or oversized.
64    TrustRootUnavailable,
65    /// The trust-root file was writable by a group or other users.
66    TrustRootPermissions,
67    /// The exact HTTPS endpoint or TLS verifier could not be constructed.
68    InvalidConfiguration,
69    /// The peer could not be reached or did not pass the mandatory TLS handshake.
70    ConnectionOrPeerVerification,
71}
72
73impl fmt::Display for TlsClientFailure {
74    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
75        formatter.write_str(match self {
76            Self::TrustRootUnavailable => "the configured TLS trust root is unavailable",
77            Self::TrustRootPermissions => "the configured TLS trust root has unsafe permissions",
78            Self::InvalidConfiguration => "the verified TLS endpoint is invalid",
79            Self::ConnectionOrPeerVerification => "the TLS peer could not be reached or verified",
80        })
81    }
82}
83
84impl Error for TlsClientFailure {}
85
86/// Redacted disposition of the latest trust-root observation.
87#[derive(Clone, Copy, Debug, Eq, PartialEq)]
88pub enum TlsTrustReloadStatus {
89    /// The configured file and active snapshot are the same valid identity.
90    Current,
91    /// The configured file was unavailable or unsafe, so the prior snapshot remains active.
92    RetainedPreviousUnavailable,
93    /// A complete replacement was malformed, so the prior snapshot remains active.
94    RetainedPreviousInvalid,
95}
96
97/// Stateful verified-TLS connector with atomic trust-root replacement.
98///
99/// A complete valid replacement is used for subsequent connections. An
100/// unavailable, malformed, or unsafe replacement retains the last valid
101/// snapshot. Existing channels are unaffected and never downgrade.
102pub struct VerifiedTlsConnector {
103    config: TlsClientConfig,
104    current: TrustRootSnapshot,
105    rejected: Option<TrustRootFileIdentity>,
106    last_reload: TlsTrustReloadStatus,
107}
108
109impl VerifiedTlsConnector {
110    /// Loads and validates the initial trust-root snapshot (and optional mTLS client identity).
111    pub fn new(config: TlsClientConfig) -> Result<Self, ClientError> {
112        let current = read_trust_root_snapshot(&config)?;
113        if let Some(identity) = config.client_identity() {
114            let _ = read_client_identity_material(identity)?;
115        }
116        Ok(Self {
117            config,
118            current,
119            rejected: None,
120            last_reload: TlsTrustReloadStatus::Current,
121        })
122    }
123
124    /// Loads and validates a verified-TLS connector from a canonical `https://`
125    /// endpoint, optional explicit PEM trust-root path, and optional expected
126    /// server name (which, when supplied, must match the canonical endpoint host
127    /// identity per `NET-002`/`NET-003`).
128    pub fn from_https_parts(
129        endpoint: &str,
130        trust_root: Option<&Path>,
131        server_name: Option<&str>,
132    ) -> Result<Self, ClientError> {
133        let endpoint = riffdb_config::CanonicalHttpsEndpoint::parse(endpoint)
134            .map_err(|_| ClientError::Tls(TlsClientFailure::InvalidConfiguration))?;
135        let identity = match server_name {
136            Some(name) => riffdb_config::TlsServerIdentity::parse(name)
137                .map_err(|_| ClientError::Tls(TlsClientFailure::InvalidConfiguration))?,
138            None => endpoint.identity().clone(),
139        };
140        let trust_root_config = match trust_root {
141            Some(path) => ClientTrustRootConfig::ExplicitPemFile(
142                riffdb_config::ProtectedFilePath::new(path.to_path_buf())
143                    .map_err(|_| ClientError::Tls(TlsClientFailure::InvalidConfiguration))?,
144            ),
145            None => ClientTrustRootConfig::SystemCaBundle,
146        };
147        let config = TlsClientConfig::with_trust_root_config(
148            endpoint,
149            trust_root_config,
150            identity,
151            std::time::Duration::from_secs(5),
152            DEFAULT_REQUEST_TIMEOUT,
153            std::num::NonZeroU32::new(1)
154                .ok_or(ClientError::Tls(TlsClientFailure::InvalidConfiguration))?,
155            std::num::NonZeroU32::new(64)
156                .ok_or(ClientError::Tls(TlsClientFailure::InvalidConfiguration))?,
157        )
158        .map_err(|_| ClientError::Tls(TlsClientFailure::InvalidConfiguration))?;
159        Self::new(config)
160    }
161
162    /// Connects one reusable HTTP/2 channel using the current valid snapshot.
163    pub async fn connect(&mut self) -> Result<RiffDbClient, ClientError> {
164        self.reload_trust_root_for_new_handshake();
165        connect_with_trust_root(&self.config, self.current.bytes.clone()).await
166    }
167
168    /// Returns a path-free disposition suitable for operator diagnostics.
169    #[must_use]
170    pub const fn last_reload_status(&self) -> TlsTrustReloadStatus {
171        self.last_reload
172    }
173
174    fn reload_trust_root_for_new_handshake(&mut self) {
175        let observed = match self.config.trust_root_config() {
176            ClientTrustRootConfig::ExplicitPemFile(path) => {
177                trust_root_file_identity(path.as_path())
178            }
179            ClientTrustRootConfig::SystemCaBundle => {
180                resolve_system_ca_bundle_path().and_then(|path| system_ca_bundle_identity(&path))
181            }
182        };
183        let Ok(observed) = observed else {
184            self.last_reload = TlsTrustReloadStatus::RetainedPreviousUnavailable;
185            return;
186        };
187        if observed == self.current.identity || self.rejected.as_ref() == Some(&observed) {
188            if observed == self.current.identity {
189                self.last_reload = TlsTrustReloadStatus::Current;
190            }
191            return;
192        }
193        match read_trust_root_snapshot(&self.config) {
194            Ok(snapshot) => {
195                self.current = snapshot;
196                self.rejected = None;
197                self.last_reload = TlsTrustReloadStatus::Current;
198            }
199            Err(_) => {
200                self.rejected = Some(observed);
201                self.last_reload = TlsTrustReloadStatus::RetainedPreviousInvalid;
202            }
203        }
204    }
205}
206
207impl RiffDbClient {
208    /// Connects through mandatory CA and exact server-name verification.
209    ///
210    /// This path has no trust-all, cleartext fallback, redirect,
211    /// client-certificate, cipher-suite, or provider selector.
212    pub async fn connect_verified_tls(config: &TlsClientConfig) -> Result<Self, ClientError> {
213        VerifiedTlsConnector::new(config.clone())?.connect().await
214    }
215
216    /// Connects to a canonical `https://` endpoint with verified TLS using
217    /// either an explicit protected PEM trust-root file or the system CA
218    /// bundle, and either an explicit server identity or the endpoint host.
219    pub async fn connect_https(
220        endpoint: &str,
221        trust_root: Option<&Path>,
222        server_name: Option<&str>,
223    ) -> Result<Self, ClientError> {
224        VerifiedTlsConnector::from_https_parts(endpoint, trust_root, server_name)?
225            .connect()
226            .await
227    }
228}
229
230async fn connect_with_trust_root(
231    config: &TlsClientConfig,
232    trust_root: Vec<u8>,
233) -> Result<RiffDbClient, ClientError> {
234    let mut tls = TonicTlsConfig::new()
235        .ca_certificate(Certificate::from_pem(trust_root))
236        .domain_name(config.expected_server_identity().as_str());
237    if let Some(identity) = config.client_identity() {
238        let (cert_pem, key_pem) = read_client_identity_material(identity)?;
239        tls = tls.identity(Identity::from_pem(cert_pem, key_pem.as_slice()));
240    }
241    let endpoint = Endpoint::from_shared(config.endpoint().as_str().to_owned())
242        .map_err(|_| ClientError::Tls(TlsClientFailure::InvalidConfiguration))?
243        .connect_timeout(config.connect_timeout())
244        .timeout(DEFAULT_REQUEST_TIMEOUT)
245        .http2_keep_alive_interval(config.keepalive_interval())
246        .keep_alive_while_idle(true)
247        .tls_config(tls)
248        .map_err(|_| ClientError::Tls(TlsClientFailure::InvalidConfiguration))?;
249    let channel = endpoint
250        .connect()
251        .await
252        .map_err(|_| ClientError::Tls(TlsClientFailure::ConnectionOrPeerVerification))?;
253    Ok(RiffDbClient::from_channel(channel))
254}
255
256fn read_client_identity_material(
257    identity: &ClientTlsIdentity,
258) -> Result<(Vec<u8>, Zeroizing<Vec<u8>>), ClientError> {
259    let cert_bytes = read_protected_tls_file(
260        identity.certificate_chain().as_path(),
261        MAX_TRUST_ROOT_BYTES,
262        false,
263    )?;
264    let key_bytes = Zeroizing::new(read_protected_tls_file(
265        identity.private_key().as_path(),
266        MAX_CLIENT_PRIVATE_KEY_BYTES,
267        true,
268    )?);
269    let mut cert_reader = std::io::Cursor::new(&cert_bytes);
270    let mut cert_count = 0_usize;
271    for cert in CertificateDer::pem_reader_iter(&mut cert_reader) {
272        let cert = cert.map_err(|_| ClientError::Tls(TlsClientFailure::InvalidConfiguration))?;
273        if cert_count == 0 {
274            webpki::EndEntityCert::try_from(&cert)
275                .map_err(|_| ClientError::Tls(TlsClientFailure::InvalidConfiguration))?;
276        }
277        cert_count = cert_count
278            .checked_add(1)
279            .ok_or(ClientError::Tls(TlsClientFailure::InvalidConfiguration))?;
280        if cert_count > 16 {
281            return Err(ClientError::Tls(TlsClientFailure::InvalidConfiguration));
282        }
283    }
284    if cert_count == 0 {
285        return Err(ClientError::Tls(TlsClientFailure::InvalidConfiguration));
286    }
287    PrivateKeyDer::from_pem_reader(std::io::Cursor::new(key_bytes.as_slice()))
288        .map_err(|_| ClientError::Tls(TlsClientFailure::InvalidConfiguration))?;
289    Ok((cert_bytes, key_bytes))
290}
291
292fn read_protected_tls_file(
293    path: &Path,
294    maximum_bytes: u64,
295    private: bool,
296) -> Result<Vec<u8>, ClientError> {
297    let identity = tls_file_identity(path, private)?;
298    let file = fs::File::open(path)
299        .map_err(|_| ClientError::Tls(TlsClientFailure::TrustRootUnavailable))?;
300    let opened = file
301        .metadata()
302        .map_err(|_| ClientError::Tls(TlsClientFailure::TrustRootUnavailable))?;
303    if !opened.is_file()
304        || opened.len() == 0
305        || opened.len() > maximum_bytes
306        || !opened_file_matches_identity(&identity, &opened)
307    {
308        return Err(ClientError::Tls(TlsClientFailure::TrustRootUnavailable));
309    }
310    let mut contents = Vec::with_capacity(opened.len() as usize);
311    file.take(maximum_bytes + 1)
312        .read_to_end(&mut contents)
313        .map_err(|_| ClientError::Tls(TlsClientFailure::TrustRootUnavailable))?;
314    if contents.is_empty() || contents.len() as u64 > maximum_bytes {
315        return Err(ClientError::Tls(TlsClientFailure::TrustRootUnavailable));
316    }
317    let after = tls_file_identity(path, private)?;
318    if after != identity {
319        return Err(ClientError::Tls(TlsClientFailure::TrustRootUnavailable));
320    }
321    Ok(contents)
322}
323
324#[cfg(unix)]
325fn tls_file_identity(path: &Path, private: bool) -> Result<TrustRootFileIdentity, ClientError> {
326    let metadata = fs::symlink_metadata(path)
327        .map_err(|_| ClientError::Tls(TlsClientFailure::TrustRootUnavailable))?;
328    if !metadata.file_type().is_file() || metadata.len() == 0 {
329        return Err(ClientError::Tls(TlsClientFailure::TrustRootUnavailable));
330    }
331    let forbidden = if private { 0o077 } else { 0o022 };
332    if metadata.permissions().mode() & forbidden != 0 {
333        return Err(ClientError::Tls(TlsClientFailure::TrustRootPermissions));
334    }
335    Ok(TrustRootFileIdentity {
336        bytes: metadata.len(),
337        device: metadata.dev(),
338        inode: metadata.ino(),
339        modified_seconds: metadata.mtime(),
340        modified_nanoseconds: metadata.mtime_nsec(),
341    })
342}
343
344#[cfg(not(unix))]
345fn tls_file_identity(path: &Path, _private: bool) -> Result<TrustRootFileIdentity, ClientError> {
346    trust_root_file_identity(path)
347}
348
349fn read_trust_root_snapshot(config: &TlsClientConfig) -> Result<TrustRootSnapshot, ClientError> {
350    match config.trust_root_config() {
351        ClientTrustRootConfig::ExplicitPemFile(path) => {
352            read_explicit_trust_root_snapshot(path.as_path())
353        }
354        ClientTrustRootConfig::SystemCaBundle => read_system_ca_bundle_snapshot(),
355    }
356}
357
358fn read_explicit_trust_root_snapshot(path: &Path) -> Result<TrustRootSnapshot, ClientError> {
359    let identity = trust_root_file_identity(path)?;
360    let file = fs::File::open(path)
361        .map_err(|_| ClientError::Tls(TlsClientFailure::TrustRootUnavailable))?;
362    let opened = file
363        .metadata()
364        .map_err(|_| ClientError::Tls(TlsClientFailure::TrustRootUnavailable))?;
365    if !opened.is_file()
366        || opened.len() == 0
367        || opened.len() > MAX_TRUST_ROOT_BYTES
368        || !opened_file_matches_identity(&identity, &opened)
369    {
370        return Err(ClientError::Tls(TlsClientFailure::TrustRootUnavailable));
371    }
372    let mut contents = Vec::with_capacity(opened.len() as usize);
373    file.take(MAX_TRUST_ROOT_BYTES + 1)
374        .read_to_end(&mut contents)
375        .map_err(|_| ClientError::Tls(TlsClientFailure::TrustRootUnavailable))?;
376    if contents.is_empty() || contents.len() as u64 > MAX_TRUST_ROOT_BYTES {
377        return Err(ClientError::Tls(TlsClientFailure::TrustRootUnavailable));
378    }
379    let after = trust_root_file_identity(path)?;
380    if after != identity {
381        return Err(ClientError::Tls(TlsClientFailure::TrustRootUnavailable));
382    }
383    validate_trust_root(&contents)?;
384    Ok(TrustRootSnapshot {
385        bytes: contents,
386        identity,
387    })
388}
389
390fn resolve_system_ca_bundle_path() -> Result<std::path::PathBuf, ClientError> {
391    for candidate in SYSTEM_CA_BUNDLE_CANDIDATES {
392        let path = Path::new(candidate);
393        if fs::metadata(path).is_ok_and(|meta| meta.is_file() && meta.len() > 0) {
394            return Ok(path.to_path_buf());
395        }
396    }
397    Err(ClientError::Tls(TlsClientFailure::TrustRootUnavailable))
398}
399
400fn read_system_ca_bundle_snapshot() -> Result<TrustRootSnapshot, ClientError> {
401    let path = resolve_system_ca_bundle_path()?;
402    read_system_ca_bundle_from_path(&path)
403}
404
405fn read_system_ca_bundle_from_path(path: &Path) -> Result<TrustRootSnapshot, ClientError> {
406    let identity = system_ca_bundle_identity(path)?;
407    let file = fs::File::open(path)
408        .map_err(|_| ClientError::Tls(TlsClientFailure::TrustRootUnavailable))?;
409    let opened = file
410        .metadata()
411        .map_err(|_| ClientError::Tls(TlsClientFailure::TrustRootUnavailable))?;
412    if !opened.is_file()
413        || opened.len() == 0
414        || opened.len() > MAX_TRUST_ROOT_BYTES
415        || !opened_file_matches_identity(&identity, &opened)
416    {
417        return Err(ClientError::Tls(TlsClientFailure::TrustRootUnavailable));
418    }
419    let mut contents = Vec::with_capacity(opened.len() as usize);
420    file.take(MAX_TRUST_ROOT_BYTES + 1)
421        .read_to_end(&mut contents)
422        .map_err(|_| ClientError::Tls(TlsClientFailure::TrustRootUnavailable))?;
423    if contents.is_empty() || contents.len() as u64 > MAX_TRUST_ROOT_BYTES {
424        return Err(ClientError::Tls(TlsClientFailure::TrustRootUnavailable));
425    }
426    let after = system_ca_bundle_identity(path)?;
427    if after != identity {
428        return Err(ClientError::Tls(TlsClientFailure::TrustRootUnavailable));
429    }
430    validate_system_ca_bundle(&contents)?;
431    Ok(TrustRootSnapshot {
432        bytes: contents,
433        identity,
434    })
435}
436
437#[cfg(unix)]
438fn system_ca_bundle_identity(path: &Path) -> Result<TrustRootFileIdentity, ClientError> {
439    let metadata =
440        fs::metadata(path).map_err(|_| ClientError::Tls(TlsClientFailure::TrustRootUnavailable))?;
441    if !metadata.is_file() || metadata.len() == 0 {
442        return Err(ClientError::Tls(TlsClientFailure::TrustRootUnavailable));
443    }
444    if metadata.permissions().mode() & 0o022 != 0 {
445        return Err(ClientError::Tls(TlsClientFailure::TrustRootPermissions));
446    }
447    Ok(TrustRootFileIdentity {
448        bytes: metadata.len(),
449        device: metadata.dev(),
450        inode: metadata.ino(),
451        modified_seconds: metadata.mtime(),
452        modified_nanoseconds: metadata.mtime_nsec(),
453    })
454}
455
456#[cfg(not(unix))]
457fn system_ca_bundle_identity(path: &Path) -> Result<TrustRootFileIdentity, ClientError> {
458    let metadata =
459        fs::metadata(path).map_err(|_| ClientError::Tls(TlsClientFailure::TrustRootUnavailable))?;
460    if !metadata.is_file() || metadata.len() == 0 {
461        return Err(ClientError::Tls(TlsClientFailure::TrustRootUnavailable));
462    }
463    Ok(TrustRootFileIdentity {
464        bytes: metadata.len(),
465        modified_since_epoch: metadata
466            .modified()
467            .ok()
468            .and_then(|value| value.duration_since(std::time::UNIX_EPOCH).ok()),
469    })
470}
471
472#[cfg(unix)]
473fn trust_root_file_identity(path: &Path) -> Result<TrustRootFileIdentity, ClientError> {
474    let metadata = fs::symlink_metadata(path)
475        .map_err(|_| ClientError::Tls(TlsClientFailure::TrustRootUnavailable))?;
476    if !metadata.file_type().is_file() || metadata.len() == 0 {
477        return Err(ClientError::Tls(TlsClientFailure::TrustRootUnavailable));
478    }
479    if metadata.permissions().mode() & 0o022 != 0 {
480        return Err(ClientError::Tls(TlsClientFailure::TrustRootPermissions));
481    }
482    Ok(TrustRootFileIdentity {
483        bytes: metadata.len(),
484        device: metadata.dev(),
485        inode: metadata.ino(),
486        modified_seconds: metadata.mtime(),
487        modified_nanoseconds: metadata.mtime_nsec(),
488    })
489}
490
491#[cfg(not(unix))]
492fn trust_root_file_identity(path: &Path) -> Result<TrustRootFileIdentity, ClientError> {
493    let metadata = fs::symlink_metadata(path)
494        .map_err(|_| ClientError::Tls(TlsClientFailure::TrustRootUnavailable))?;
495    if !metadata.file_type().is_file() || metadata.len() == 0 {
496        return Err(ClientError::Tls(TlsClientFailure::TrustRootUnavailable));
497    }
498    Ok(TrustRootFileIdentity {
499        bytes: metadata.len(),
500        modified_since_epoch: metadata
501            .modified()
502            .ok()
503            .and_then(|value| value.duration_since(std::time::UNIX_EPOCH).ok()),
504    })
505}
506
507#[cfg(unix)]
508fn opened_file_matches_identity(identity: &TrustRootFileIdentity, opened: &fs::Metadata) -> bool {
509    identity.device == opened.dev()
510        && identity.inode == opened.ino()
511        && identity.bytes == opened.len()
512        && identity.modified_seconds == opened.mtime()
513        && identity.modified_nanoseconds == opened.mtime_nsec()
514}
515
516#[cfg(not(unix))]
517fn opened_file_matches_identity(identity: &TrustRootFileIdentity, opened: &fs::Metadata) -> bool {
518    identity.bytes == opened.len()
519        && identity.modified_since_epoch
520            == opened
521                .modified()
522                .ok()
523                .and_then(|value| value.duration_since(std::time::UNIX_EPOCH).ok())
524}
525
526fn validate_trust_root(contents: &[u8]) -> Result<(), ClientError> {
527    let mut reader = std::io::Cursor::new(contents);
528    let mut count = 0_usize;
529    for certificate in CertificateDer::pem_reader_iter(&mut reader) {
530        let certificate =
531            certificate.map_err(|_| ClientError::Tls(TlsClientFailure::InvalidConfiguration))?;
532        count = count
533            .checked_add(1)
534            .ok_or(ClientError::Tls(TlsClientFailure::InvalidConfiguration))?;
535        if count > MAX_TRUST_ROOT_CERTIFICATES
536            || webpki::anchor_from_trusted_cert(&certificate).is_err()
537        {
538            return Err(ClientError::Tls(TlsClientFailure::InvalidConfiguration));
539        }
540    }
541    if count == 0 {
542        return Err(ClientError::Tls(TlsClientFailure::InvalidConfiguration));
543    }
544    Ok(())
545}
546
547fn validate_system_ca_bundle(contents: &[u8]) -> Result<(), ClientError> {
548    let mut reader = std::io::Cursor::new(contents);
549    let mut count = 0_usize;
550    let mut valid_anchors = 0_usize;
551    for certificate in CertificateDer::pem_reader_iter(&mut reader) {
552        let certificate =
553            certificate.map_err(|_| ClientError::Tls(TlsClientFailure::InvalidConfiguration))?;
554        count = count
555            .checked_add(1)
556            .ok_or(ClientError::Tls(TlsClientFailure::InvalidConfiguration))?;
557        if count > MAX_TRUST_ROOT_CERTIFICATES {
558            return Err(ClientError::Tls(TlsClientFailure::InvalidConfiguration));
559        }
560        if webpki::anchor_from_trusted_cert(&certificate).is_ok() {
561            valid_anchors += 1;
562        }
563    }
564    if valid_anchors == 0 {
565        return Err(ClientError::Tls(TlsClientFailure::InvalidConfiguration));
566    }
567    Ok(())
568}
569
570#[cfg(test)]
571mod tests {
572    use std::num::NonZeroU32;
573    #[cfg(unix)]
574    use std::os::unix::fs::{PermissionsExt, symlink};
575    use std::path::PathBuf;
576    use std::sync::atomic::{AtomicU64, Ordering};
577    use std::time::Duration;
578
579    use riffdb_config::{CanonicalHttpsEndpoint, ProtectedFilePath, TlsServerIdentity};
580
581    use super::*;
582
583    static NEXT_TEST_ROOT: AtomicU64 = AtomicU64::new(1);
584
585    #[test]
586    fn verified_tls_channels_have_a_bounded_request_lifetime() {
587        assert_eq!(DEFAULT_REQUEST_TIMEOUT, Duration::from_secs(30));
588        let source = include_str!("tls.rs");
589        assert!(source.contains(".timeout(DEFAULT_REQUEST_TIMEOUT)"));
590    }
591
592    fn config(path: PathBuf) -> TlsClientConfig {
593        TlsClientConfig::new(
594            CanonicalHttpsEndpoint::parse("https://127.0.0.1:7443").expect("endpoint"),
595            ProtectedFilePath::new(path).expect("trust path"),
596            TlsServerIdentity::parse("127.0.0.1").expect("identity"),
597            Duration::from_secs(5),
598            Duration::from_secs(30),
599            NonZeroU32::new(1).expect("pool"),
600            NonZeroU32::new(64).expect("streams"),
601        )
602        .expect("TLS client config")
603    }
604
605    #[cfg(unix)]
606    #[test]
607    fn trust_root_rejects_writable_and_symlinked_files_without_disclosing_paths() {
608        let unique = NEXT_TEST_ROOT.fetch_add(1, Ordering::Relaxed);
609        let root = std::env::current_dir()
610            .expect("test current directory")
611            .join("target/client-tls-tests")
612            .join(format!("{}-{unique}", std::process::id()));
613        fs::create_dir_all(root.parent().expect("test root parent"))
614            .expect("create TLS test parent");
615        fs::create_dir(&root).expect("create TLS test root");
616        fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).expect("protect root");
617        let trust = root.join("ca.pem");
618        fs::write(&trust, b"not-empty").expect("write trust root");
619        fs::set_permissions(&trust, fs::Permissions::from_mode(0o666)).expect("unsafe mode");
620        let error =
621            read_trust_root_snapshot(&config(trust.clone())).expect_err("writable trust root");
622        assert!(matches!(
623            error,
624            ClientError::Tls(TlsClientFailure::TrustRootPermissions)
625        ));
626        assert!(
627            !error
628                .to_string()
629                .contains(root.to_str().expect("UTF-8 root"))
630        );
631
632        fs::set_permissions(&trust, fs::Permissions::from_mode(0o600)).expect("safe mode");
633        let link = root.join("linked.pem");
634        symlink(&trust, &link).expect("create test symlink");
635        assert!(matches!(
636            read_trust_root_snapshot(&config(link)),
637            Err(ClientError::Tls(TlsClientFailure::TrustRootUnavailable))
638        ));
639
640        fs::remove_file(&trust).expect("remove trust root");
641        fs::remove_file(root.join("linked.pem")).expect("remove symlink");
642        fs::remove_dir(&root).expect("remove TLS test root");
643    }
644
645    #[cfg(unix)]
646    #[test]
647    fn connector_atomically_adopts_valid_trust_roots_and_retains_last_good_on_failure() {
648        let unique = NEXT_TEST_ROOT.fetch_add(1, Ordering::Relaxed);
649        let root = std::env::current_dir()
650            .expect("test current directory")
651            .join("target/client-tls-tests")
652            .join(format!("{}-{unique}", std::process::id()));
653        fs::create_dir_all(root.parent().expect("test root parent"))
654            .expect("create TLS test parent");
655        fs::create_dir(&root).expect("create TLS test root");
656        fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).expect("protect root");
657        let trust = root.join("ca.pem");
658        let valid = include_bytes!("../../riffdb-server/tests/fixtures/test-ca.pem");
659        fs::write(&trust, valid).expect("write initial trust root");
660        fs::set_permissions(&trust, fs::Permissions::from_mode(0o600))
661            .expect("protect initial trust root");
662        let mut connector =
663            VerifiedTlsConnector::new(config(trust.clone())).expect("initial trust root is valid");
664        let initial = connector.current.identity.clone();
665
666        let invalid = root.join("invalid.pem");
667        fs::write(&invalid, b"not a certificate\n").expect("write invalid replacement");
668        fs::set_permissions(&invalid, fs::Permissions::from_mode(0o600))
669            .expect("protect invalid replacement");
670        fs::rename(&invalid, &trust).expect("atomically publish invalid replacement");
671        connector.reload_trust_root_for_new_handshake();
672        assert_eq!(connector.current.identity, initial);
673        assert!(connector.rejected.is_some());
674        assert_eq!(
675            connector.last_reload_status(),
676            TlsTrustReloadStatus::RetainedPreviousInvalid
677        );
678
679        let replacement = root.join("replacement.pem");
680        fs::write(&replacement, valid).expect("write valid replacement");
681        fs::set_permissions(&replacement, fs::Permissions::from_mode(0o600))
682            .expect("protect valid replacement");
683        fs::rename(&replacement, &trust).expect("atomically publish valid replacement");
684        connector.reload_trust_root_for_new_handshake();
685        assert_ne!(connector.current.identity, initial);
686        assert!(connector.rejected.is_none());
687        assert_eq!(
688            connector.last_reload_status(),
689            TlsTrustReloadStatus::Current
690        );
691
692        fs::remove_file(&trust).expect("remove trust root");
693        fs::remove_dir(&root).expect("remove TLS test root");
694    }
695
696    #[cfg(unix)]
697    #[test]
698    // req: NET-001, NET-002, NET-005
699    fn remote_https_profile_derives_server_name_and_supports_system_and_explicit_trust_roots() {
700        let endpoint =
701            CanonicalHttpsEndpoint::parse("https://cloud.example.com:7443").expect("endpoint");
702        let system_cfg = TlsClientConfig::system_trust(
703            endpoint.clone(),
704            Duration::from_secs(5),
705            Duration::from_secs(30),
706            NonZeroU32::new(4).expect("pool"),
707            NonZeroU32::new(64).expect("streams"),
708        )
709        .expect("system trust config");
710        assert_eq!(
711            system_cfg.expected_server_identity(),
712            &TlsServerIdentity::parse("cloud.example.com").expect("identity")
713        );
714        assert_eq!(
715            system_cfg.trust_root_config(),
716            &ClientTrustRootConfig::SystemCaBundle
717        );
718        assert!(system_cfg.explicit_trust_root().is_none());
719
720        // Verify system CA bundle snapshot loads when standard OS bundle is present on host.
721        if resolve_system_ca_bundle_path().is_ok() {
722            let connector = VerifiedTlsConnector::new(system_cfg)
723                .expect("system CA bundle loads and validates");
724            assert_eq!(
725                connector.last_reload_status(),
726                TlsTrustReloadStatus::Current
727            );
728        }
729
730        // Verify explicit PEM trust root with derived server identity also works.
731        let unique = NEXT_TEST_ROOT.fetch_add(1, Ordering::Relaxed);
732        let root = std::env::current_dir()
733            .expect("test current directory")
734            .join("target/client-tls-tests")
735            .join(format!("{}-system-{unique}", std::process::id()));
736        fs::create_dir_all(root.parent().expect("test root parent"))
737            .expect("create TLS test parent");
738        fs::create_dir(&root).expect("create TLS test root");
739        fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).expect("protect root");
740        let trust = root.join("ca.pem");
741        let valid = include_bytes!("../../riffdb-server/tests/fixtures/test-ca.pem");
742        fs::write(&trust, valid).expect("write initial trust root");
743        fs::set_permissions(&trust, fs::Permissions::from_mode(0o600))
744            .expect("protect initial trust root");
745        let explicit_cfg = TlsClientConfig::with_trust_root_config(
746            endpoint.clone(),
747            ClientTrustRootConfig::ExplicitPemFile(
748                ProtectedFilePath::new(trust.clone()).expect("protected path"),
749            ),
750            endpoint.identity().clone(),
751            Duration::from_secs(5),
752            Duration::from_secs(30),
753            NonZeroU32::new(4).expect("pool"),
754            NonZeroU32::new(64).expect("streams"),
755        )
756        .expect("explicit trust config");
757        assert!(explicit_cfg.explicit_trust_root().is_some());
758        let connector = VerifiedTlsConnector::new(explicit_cfg)
759            .expect("explicit CA bundle loads and validates");
760        assert_eq!(
761            connector.last_reload_status(),
762            TlsTrustReloadStatus::Current
763        );
764
765        fs::remove_file(&trust).expect("remove trust root");
766        fs::remove_dir(&root).expect("remove TLS test root");
767    }
768}