Skip to main content

sew_call_client/
config.rs

1//! The engine's configuration and its TLS trust.
2//!
3//! Production trust is the platform's (`rustls-platform-verifier`: the macOS and Windows
4//! verifiers, the system roots on Linux), on one rustls crypto provider: the host's
5//! ([`ClientConfig::with_crypto_provider`]), else the process default
6//! (`CryptoProvider::get_default`), else the built-in ring provider (feature
7//! `builtin-ring-provider`, on by default; without it the engine refuses with
8//! `no_crypto_provider`). Signalling, the TURN-TLS connection and Sew's
9//! client API all use it. A test-only option (feature
10//! `testing`) adds a run CA **on top of** the platform roots; there is no way to trust only a
11//! test CA.
12
13use std::net::IpAddr;
14use std::path::PathBuf;
15use std::sync::Arc;
16use std::time::Duration;
17
18use rustls::ClientConfig as TlsConfig;
19use rustls::crypto::CryptoProvider;
20use rustls_platform_verifier::Verifier;
21
22use crate::device::{DeviceKeyStore, DevicePlatform, HardwareDeviceKey, StoreChoice};
23
24/// The engine's configuration (one per app).
25#[derive(Clone, Debug)]
26#[non_exhaustive]
27pub struct ClientConfig {
28    /// The host's app identifier (with feature `keyring-store`, `sew-voice.<app id>` is the OS
29    /// credential store's service).
30    pub app_id: String,
31    /// The host's data directory (the device store's public data).
32    pub data_dir: PathBuf,
33    /// Where [`crate::CallClient::with_mls`] keeps the device key and its public record.
34    /// Default [`StoreChoice::Auto`]: a 0600 file, warned as `key_storage_file` (with feature
35    /// `keyring-store`, the OS credential store first). A host passes its own store with
36    /// [`ClientConfig::with_device_key_store`].
37    pub device_store: StoreChoice,
38    /// The platform the device enrols as. Default from `target_os` (iOS, Android, otherwise
39    /// desktop); a host sets it with [`ClientConfig::with_device_platform`].
40    pub device_platform: DevicePlatform,
41    /// The reconnect window (Sew's media server's `reconnect_window_ms`, 20 s): resume and full
42    /// reconnects inside it; after it, a re-join through the provider.
43    pub reconnect_window: Duration,
44    /// How long the first connect may take before the call ends with `network`.
45    pub connect_timeout: Duration,
46    /// The rustls crypto provider of every TLS connection (signalling, TURN-TLS, the client
47    /// API and the key routes). `None` (the default): the process default
48    /// (`CryptoProvider::get_default`, e.g. one the host installed with `install_default`),
49    /// else the built-in ring provider (feature `builtin-ring-provider`, on by default; without
50    /// it, TLS setup fails with `no_crypto_provider`). A host sets it with
51    /// [`ClientConfig::with_crypto_provider`].
52    pub crypto_provider: Option<Arc<CryptoProvider>>,
53    /// Whether the media connection negotiates H.264 beside VP8 (feature `video-core`): the
54    /// receive sections offer it, so the media server may forward H.264 tracks, and a camera
55    /// or screen may publish in it. Default [`default_video_h264`]: on where this device can
56    /// show H.264 (VideoToolbox on macOS and iOS; the webview's WebCodecs elsewhere), off on
57    /// Linux, which has no H.264 decoder in the engine (kessel-video decodes only VP8 there), so
58    /// the media server never sends a Linux client H.264 it can't show. A host that decodes
59    /// H.264 itself turns it on with [`ClientConfig::with_video_h264`].
60    ///
61    /// It is an upper bound: once the host declares its decoders
62    /// ([`crate::CallClient::set_video_decode`]), H.264 is offered only if they list it (never
63    /// on Linux), and never under [`crate::VideoCodecPreference::PreferVp8`].
64    pub video_h264: bool,
65    /// Test-only overrides (feature `testing`).
66    #[cfg(feature = "testing")]
67    pub testing: TestingOverrides,
68}
69
70impl ClientConfig {
71    /// A config with the defaults.
72    pub fn new(app_id: &str, data_dir: PathBuf) -> ClientConfig {
73        ClientConfig {
74            app_id: app_id.to_owned(),
75            data_dir,
76            device_store: StoreChoice::Auto,
77            device_platform: crate::device::default_platform(),
78            reconnect_window: Duration::from_secs(20),
79            connect_timeout: Duration::from_secs(20),
80            crypto_provider: None,
81            video_h264: default_video_h264(),
82            #[cfg(feature = "testing")]
83            testing: TestingOverrides::default(),
84        }
85    }
86
87    /// Negotiates H.264 (`true`) or VP8 only (`false`) for video, instead of the
88    /// [`default_video_h264`] of this platform ([`ClientConfig::video_h264`]).
89    pub fn with_video_h264(mut self, on: bool) -> ClientConfig {
90        self.video_h264 = on;
91        self
92    }
93
94    /// Keeps the device's private key and public record in the host's own store (e.g. K2's
95    /// keyring or vault) instead of the built-in file ([`StoreChoice::Host`]).
96    pub fn with_device_key_store(mut self, store: Arc<dyn DeviceKeyStore>) -> ClientConfig {
97        self.device_store = StoreChoice::Host(store);
98        self
99    }
100
101    /// Keeps the device's private key in the host's hardware (Secure Enclave, StrongBox/TEE)
102    /// through [`HardwareDeviceKey`] ([`StoreChoice::Hardware`]); the public record stays in
103    /// the data directory. It replaces any other store, and the engine never falls back to a
104    /// software key.
105    pub fn with_hardware_device_key(mut self, key: Arc<dyn HardwareDeviceKey>) -> ClientConfig {
106        self.device_store = StoreChoice::Hardware(key);
107        self
108    }
109
110    /// The platform the device enrols as (instead of the `target_os` default).
111    pub fn with_device_platform(mut self, platform: DevicePlatform) -> ClientConfig {
112        self.device_platform = platform;
113        self
114    }
115
116    /// Builds every TLS connection on `provider` (e.g. the host's own rustls provider) instead
117    /// of the process default.
118    pub fn with_crypto_provider(mut self, provider: Arc<CryptoProvider>) -> ClientConfig {
119        self.crypto_provider = Some(provider);
120        self
121    }
122}
123
124/// Whether this platform negotiates H.264 by default ([`ClientConfig::video_h264`]): `false` on
125/// Linux (no H.264 decoder there), `true` elsewhere.
126pub const fn default_video_h264() -> bool {
127    !cfg!(target_os = "linux")
128}
129
130/// TEST ONLY (feature `testing`): what the loopback lanes change.
131#[cfg(feature = "testing")]
132#[derive(Clone, Debug, Default)]
133pub struct TestingOverrides {
134    /// CA certificates (DER) trusted **in addition to** the platform roots.
135    pub extra_roots: Vec<Vec<u8>>,
136    /// Fixed name resolution (`turn.sew.test` → 127.0.0.1), as Chrome's
137    /// `--host-resolver-rules`.
138    pub resolve: Vec<(String, IpAddr)>,
139    /// The media transport's source address (the TURN sockets and the host candidate bind
140    /// to it), shared so a test can move the client to another "network" mid-call (`None`: the
141    /// OS chooses, as in production).
142    pub source_ip: Arc<std::sync::RwLock<Option<IpAddr>>>,
143    /// The RTP sequence number the microphone's first packet carries in each new media session
144    /// (each new PC; `None`: the engine's own random start in [0, 2^15)). Lanes set it near
145    /// 65535 to make the sequence wrap early.
146    pub first_seq: Option<u16>,
147    /// Received video RTP packets to drop on arrival, before the reorder buffer (a lost
148    /// burst the retransmissions cannot fill: str0m already counted them received). A lane sets
149    /// it mid-call; each dropped packet takes one off.
150    pub drop_video_packets: Arc<std::sync::atomic::AtomicU32>,
151}
152
153/// Takes one off [`TestingOverrides::drop_video_packets`]: whether to drop this packet.
154#[cfg(feature = "testing")]
155pub(crate) fn drop_video_packet(cfg: &ClientConfig) -> bool {
156    use std::sync::atomic::Ordering;
157    cfg.testing
158        .drop_video_packets
159        .try_update(Ordering::AcqRel, Ordering::Acquire, |n| n.checked_sub(1))
160        .is_ok()
161}
162
163/// No packet is dropped (no testing override in this build).
164#[cfg(not(feature = "testing"))]
165pub(crate) fn drop_video_packet(_cfg: &ClientConfig) -> bool {
166    false
167}
168
169/// The testing source address of the media transport, if one is set.
170#[cfg(feature = "testing")]
171pub(crate) fn source_ip(cfg: &ClientConfig) -> Option<IpAddr> {
172    cfg.testing.source_ip.read().ok().and_then(|g| *g)
173}
174
175/// The media transport's source address: the OS chooses (no testing override in this build).
176#[cfg(not(feature = "testing"))]
177pub(crate) fn source_ip(_cfg: &ClientConfig) -> Option<IpAddr> {
178    None
179}
180
181/// Where the engine's crypto provider came from.
182#[derive(Clone, Copy, Debug, PartialEq, Eq)]
183pub(crate) enum ProviderSource {
184    /// [`ClientConfig::with_crypto_provider`].
185    Caller,
186    /// `CryptoProvider::get_default` (installed by the host).
187    ProcessDefault,
188    /// ring, the built-in (feature `builtin-ring-provider`).
189    #[cfg_attr(not(feature = "builtin-ring-provider"), allow(dead_code))]
190    BuiltIn,
191}
192
193impl ProviderSource {
194    fn as_str(self) -> &'static str {
195        match self {
196            ProviderSource::Caller => "caller",
197            ProviderSource::ProcessDefault => "process default",
198            ProviderSource::BuiltIn => "built-in",
199        }
200    }
201}
202
203/// The refusal when no provider is supplied, none is installed and the built-in is off.
204#[cfg(not(feature = "builtin-ring-provider"))]
205pub(crate) const NO_CRYPTO_PROVIDER: &str = "no_crypto_provider";
206
207/// The crypto provider the engine's TLS uses: `explicit`, else the process default, else the
208/// built-in ring provider (feature `builtin-ring-provider`); without that feature, an error.
209/// The choice is logged at info the first time it is made and whenever it changes.
210pub(crate) fn crypto_provider(
211    explicit: Option<&Arc<CryptoProvider>>,
212) -> Result<Arc<CryptoProvider>, rustls::Error> {
213    let (provider, source) = choose_provider(explicit, CryptoProvider::get_default())?;
214    log_choice(&provider, source);
215    Ok(provider)
216}
217
218fn choose_provider(
219    explicit: Option<&Arc<CryptoProvider>>,
220    default: Option<&Arc<CryptoProvider>>,
221) -> Result<(Arc<CryptoProvider>, ProviderSource), rustls::Error> {
222    if let Some(p) = explicit {
223        return Ok((p.clone(), ProviderSource::Caller));
224    }
225    if let Some(p) = default {
226        return Ok((p.clone(), ProviderSource::ProcessDefault));
227    }
228    builtin_provider()
229}
230
231#[cfg(feature = "builtin-ring-provider")]
232fn builtin_provider() -> Result<(Arc<CryptoProvider>, ProviderSource), rustls::Error> {
233    Ok((
234        Arc::new(rustls::crypto::ring::default_provider()),
235        ProviderSource::BuiltIn,
236    ))
237}
238
239#[cfg(not(feature = "builtin-ring-provider"))]
240fn builtin_provider() -> Result<(Arc<CryptoProvider>, ProviderSource), rustls::Error> {
241    Err(rustls::Error::General(format!(
242        "{NO_CRYPTO_PROVIDER}: no rustls crypto provider was passed \
243         (ClientConfig::with_crypto_provider) or installed as the process default, and the \
244         built-in one is off (feature `builtin-ring-provider`)"
245    )))
246}
247
248/// A provider's name: its random source's `Debug` name (`Ring` for ring's, `AwsLcRs` for
249/// aws-lc-rs's; a host provider's own).
250pub(crate) fn provider_name(p: &CryptoProvider) -> String {
251    format!("{:?}", p.secure_random)
252}
253
254fn log_choice(provider: &CryptoProvider, source: ProviderSource) {
255    static LAST: std::sync::Mutex<Option<(String, ProviderSource)>> = std::sync::Mutex::new(None);
256    let choice = (provider_name(provider), source);
257    let mut last = LAST
258        .lock()
259        .unwrap_or_else(std::sync::PoisonError::into_inner);
260    if last.as_ref() != Some(&choice) {
261        tracing::info!("tls provider: {} ({})", choice.0, source.as_str());
262        *last = Some(choice);
263    }
264}
265
266/// The TLS client config every connection of the engine uses.
267pub(crate) fn tls_config(cfg: &ClientConfig) -> Result<Arc<TlsConfig>, rustls::Error> {
268    let provider = crypto_provider(cfg.crypto_provider.as_ref())?;
269    #[cfg(feature = "testing")]
270    let verifier = if cfg.testing.extra_roots.is_empty() {
271        Verifier::new(provider.clone())?
272    } else {
273        let extra = cfg
274            .testing
275            .extra_roots
276            .iter()
277            .map(|d| rustls::pki_types::CertificateDer::from(d.clone()));
278        Verifier::new_with_extra_roots(extra, provider.clone())?
279    };
280    #[cfg(not(feature = "testing"))]
281    let verifier = {
282        let _ = cfg;
283        Verifier::new(provider.clone())?
284    };
285    let tls = TlsConfig::builder_with_provider(provider)
286        .with_safe_default_protocol_versions()?
287        .dangerous()
288        .with_custom_certificate_verifier(Arc::new(verifier))
289        .with_no_client_auth();
290    Ok(Arc::new(tls))
291}
292
293/// The platform's trust alone (the key session's default when the engine gives it none), on the
294/// process default provider, else the built-in.
295pub(crate) fn platform_tls() -> Result<Arc<TlsConfig>, rustls::Error> {
296    let provider = crypto_provider(None)?;
297    let verifier = Verifier::new(provider.clone())?;
298    let tls = TlsConfig::builder_with_provider(provider)
299        .with_safe_default_protocol_versions()?
300        .dangerous()
301        .with_custom_certificate_verifier(Arc::new(verifier))
302        .with_no_client_auth();
303    Ok(Arc::new(tls))
304}
305
306impl ClientConfig {
307    /// The TLS client config the engine uses for every connection (the platform's trust; in a
308    /// `testing` build, plus the run CA), on the provider [`ClientConfig::crypto_provider`]
309    /// describes. Hosts that set up the keys themselves
310    /// ([`crate::e2ee::MlsKeys::prepare_session_join`]) pass it on.
311    pub fn tls(&self) -> Result<Arc<TlsConfig>, rustls::Error> {
312        tls_config(self)
313    }
314}
315
316/// Resolves `host:port` (the testing overrides first).
317pub(crate) async fn resolve(
318    cfg: &ClientConfig,
319    host: &str,
320    port: u16,
321) -> std::io::Result<std::net::SocketAddr> {
322    let host = host.trim_start_matches('[').trim_end_matches(']');
323    if let Ok(ip) = host.parse::<IpAddr>() {
324        return Ok(std::net::SocketAddr::new(ip, port));
325    }
326    #[cfg(feature = "testing")]
327    if let Some((_, ip)) = cfg.testing.resolve.iter().find(|(n, _)| n == host) {
328        return Ok(std::net::SocketAddr::new(*ip, port));
329    }
330    #[cfg(not(feature = "testing"))]
331    let _ = cfg;
332    tokio::net::lookup_host((host, port))
333        .await?
334        .next()
335        .ok_or_else(|| std::io::Error::other(format!("{host} does not resolve")))
336}
337
338/// Whether `host` names this machine (plain `ws://` and `http://` are allowed only there).
339pub(crate) fn is_loopback_host(host: &str) -> bool {
340    let h = host.trim_start_matches('[').trim_end_matches(']');
341    h.eq_ignore_ascii_case("localhost") || h.parse::<IpAddr>().is_ok_and(|ip| ip.is_loopback())
342}
343
344#[cfg(test)]
345mod tests {
346    #![allow(clippy::unwrap_used)]
347    use super::*;
348
349    #[cfg(feature = "builtin-ring-provider")]
350    #[test]
351    fn the_platform_verifier_builds() {
352        let cfg = ClientConfig::new("test.app", std::env::temp_dir());
353        assert!(tls_config(&cfg).is_ok());
354    }
355
356    #[cfg(feature = "builtin-ring-provider")]
357    fn suites(p: &CryptoProvider) -> Vec<rustls::CipherSuite> {
358        p.cipher_suites.iter().map(|s| s.suite()).collect()
359    }
360
361    #[cfg(feature = "builtin-ring-provider")]
362    fn groups(p: &CryptoProvider) -> Vec<rustls::NamedGroup> {
363        p.kx_groups.iter().map(|g| g.name()).collect()
364    }
365
366    /// A provider that is not ring's default: one cipher suite, one group.
367    fn narrow() -> Arc<CryptoProvider> {
368        let ring = rustls::crypto::ring::default_provider();
369        Arc::new(CryptoProvider {
370            cipher_suites: vec![rustls::crypto::ring::cipher_suite::TLS13_AES_128_GCM_SHA256],
371            kx_groups: vec![rustls::crypto::ring::kx_group::X25519],
372            ..ring
373        })
374    }
375
376    #[test]
377    fn the_explicit_provider_wins_then_the_default() {
378        let explicit = narrow();
379        let default = narrow();
380        let (p, src) = choose_provider(Some(&explicit), Some(&default)).unwrap();
381        assert!(Arc::ptr_eq(&p, &explicit), "the explicit provider is used");
382        assert_eq!(src, ProviderSource::Caller);
383        let (p, src) = choose_provider(None, Some(&default)).unwrap();
384        assert!(Arc::ptr_eq(&p, &default), "the process default is used");
385        assert_eq!(src, ProviderSource::ProcessDefault);
386    }
387
388    #[test]
389    fn provider_names() {
390        assert_eq!(
391            provider_name(&rustls::crypto::ring::default_provider()),
392            "Ring"
393        );
394    }
395
396    /// Nothing in this test binary installs a process default, so the configs are ring's, as
397    /// before the option existed (tests/tls_provider.rs covers an installed default; nothing
398    /// here may call a rustls builder that installs one from the crate features).
399    #[cfg(feature = "builtin-ring-provider")]
400    #[test]
401    fn without_a_default_the_configs_are_on_the_builtin_ring() {
402        assert!(CryptoProvider::get_default().is_none());
403        let ring = rustls::crypto::ring::default_provider();
404        let (p, src) = choose_provider(None, None).unwrap();
405        assert_eq!(src, ProviderSource::BuiltIn);
406        assert_eq!(suites(&p), suites(&ring), "ring's suites");
407        assert_eq!(groups(&p), groups(&ring), "ring's groups");
408        let cfg = ClientConfig::new("test.app", std::env::temp_dir());
409        for tls in [tls_config(&cfg).unwrap(), platform_tls().unwrap()] {
410            assert_eq!(suites(tls.crypto_provider()), suites(&ring));
411            assert_eq!(groups(tls.crypto_provider()), groups(&ring));
412        }
413        let explicit = narrow();
414        let tls = tls_config(&cfg.with_crypto_provider(explicit.clone())).unwrap();
415        assert!(Arc::ptr_eq(tls.crypto_provider(), &explicit));
416    }
417
418    /// Without the built-in and with nothing passed or installed, TLS setup is refused; an
419    /// explicit provider still works.
420    #[cfg(not(feature = "builtin-ring-provider"))]
421    #[test]
422    fn without_the_builtin_nothing_is_guessed() {
423        assert!(CryptoProvider::get_default().is_none());
424        let e = choose_provider(None, None).unwrap_err();
425        assert!(e.to_string().contains(NO_CRYPTO_PROVIDER), "{e}");
426        let cfg = ClientConfig::new("test.app", std::env::temp_dir());
427        let e = tls_config(&cfg).unwrap_err();
428        assert!(e.to_string().contains(NO_CRYPTO_PROVIDER), "{e}");
429        let e = platform_tls().unwrap_err();
430        assert!(e.to_string().contains(NO_CRYPTO_PROVIDER), "{e}");
431        let explicit = narrow();
432        let tls = tls_config(&cfg.with_crypto_provider(explicit.clone())).unwrap();
433        assert!(Arc::ptr_eq(tls.crypto_provider(), &explicit));
434    }
435
436    #[test]
437    fn loopback_hosts() {
438        assert!(is_loopback_host("127.0.0.1"));
439        assert!(is_loopback_host("[::1]"));
440        assert!(is_loopback_host("localhost"));
441        assert!(!is_loopback_host("voice.example"));
442        assert!(!is_loopback_host("10.0.0.1"));
443    }
444}