Skip to main content

hyprstream_core/services/oauth/
account_tls.rs

1//! Account-zone certificate rotation stays inside the owned account worker.
2
3use crate::account::{AccountHttpConfig, AccountZone};
4use crate::server::tls::{serve_bound, BoundHttpListener};
5use hyprstream_rpc::error::RpcError;
6use std::{sync::Arc, time::Duration};
7use tokio::sync::Notify;
8
9pub(super) async fn serve_with_reload(
10    bound: BoundHttpListener,
11    app: axum::Router,
12    shutdown: Arc<Notify>,
13    config: AccountHttpConfig,
14    zone: AccountZone,
15    reload_interval: Duration,
16) -> Result<(), RpcError> {
17    let live_tls = match &bound {
18        BoundHttpListener::Https(_, tls) => tls.rustls.clone(),
19        BoundHttpListener::Http(_) => {
20            return Err(RpcError::SpawnFailed(
21                "account listener requires TLS".to_owned(),
22            ));
23        }
24    };
25    let reload = async {
26        let mut tick = tokio::time::interval(reload_interval);
27        tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
28        // Startup already validated the first pair. Subsequent reads also
29        // catch atomic file/symlink replacement without a filesystem watcher.
30        tick.tick().await;
31        loop {
32            tick.tick().await;
33            match super::resolve_account_http_tls(&config, &zone).await {
34                Ok(candidate) => live_tls.reload_from_config(candidate.get_inner()),
35                Err(error) => tracing::warn!(
36                    "account TLS rotation rejected; retaining previous certificate and retrying: {error:#}"
37                ),
38            }
39        }
40    };
41    // No spawned watcher can outlive this serve future. A slow reload does not
42    // stop polling the listener/shutdown; the enclosing ContainedWorker owns
43    // the runtime and preserves the existing bounded process-exit guarantee.
44    tokio::select! {
45        result = serve_bound(bound, app, shutdown, "AccountHttpService") => result,
46        () = reload => unreachable!("account certificate reload loop is permanent"),
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    #![allow(clippy::expect_used, clippy::unwrap_used)]
53
54    use super::*;
55
56    #[tokio::test]
57    async fn account_tls_rotation_updates_live_https_and_preserves_shutdown() -> anyhow::Result<()>
58    {
59        hyprstream_rpc::transport::install_pq_crypto_provider()?;
60        let directory = tempfile::tempdir()?;
61        let zone = AccountZone::new("acct.example.com")?;
62        let first = rcgen::generate_simple_self_signed(vec![zone.wildcard_domain().to_owned()])?;
63        let second = rcgen::generate_simple_self_signed(vec![zone.wildcard_domain().to_owned()])?;
64        let wrong_zone =
65            rcgen::generate_simple_self_signed(vec!["*.other.example.com".to_owned()])?;
66        let config = AccountHttpConfig {
67            host: "127.0.0.1".to_owned(),
68            port: 8443,
69            tls_cert: directory.path().join("cert.pem"),
70            tls_key: directory.path().join("key.pem"),
71        };
72        std::fs::write(&config.tls_cert, first.cert.pem())?;
73        std::fs::write(&config.tls_key, first.key_pair.serialize_pem())?;
74        let tls = super::super::resolve_account_http_tls(&config, &zone).await?;
75        let bound = crate::server::tls::bind_listener(
76            "127.0.0.1:0".parse()?,
77            Some(crate::server::tls::ResolvedTlsConfig::ordinary(tls)),
78            "AccountRotationTest",
79        )?;
80        let address = match &bound {
81            BoundHttpListener::Https(listener, _) => listener.local_addr()?,
82            _ => unreachable!(),
83        };
84        let shutdown = Arc::new(Notify::new());
85        let server = tokio::spawn(serve_with_reload(
86            bound,
87            axum::Router::new().route("/", axum::routing::get(|| async { "account-ok" })),
88            shutdown.clone(),
89            config.clone(),
90            zone,
91            Duration::from_millis(20),
92        ));
93        let client = reqwest::Client::builder()
94            .use_rustls_tls()
95            .no_proxy()
96            .tls_info(true)
97            .pool_max_idle_per_host(0)
98            .add_root_certificate(reqwest::Certificate::from_der(first.cert.der())?)
99            .add_root_certificate(reqwest::Certificate::from_der(second.cert.der())?)
100            .resolve("alice.acct.example.com", address)
101            .timeout(Duration::from_secs(2))
102            .build()?;
103        let url = format!("https://alice.acct.example.com:{}/", address.port());
104        let peer = || async {
105            let response = client.get(&url).send().await?.error_for_status()?;
106            let certificate = response
107                .extensions()
108                .get::<reqwest::tls::TlsInfo>()
109                .and_then(|info| info.peer_certificate())
110                .expect("live TLS handshake must report the peer certificate")
111                .to_vec();
112            assert_eq!(response.text().await?, "account-ok");
113            Ok::<_, anyhow::Error>(certificate)
114        };
115        assert_eq!(peer().await?, first.cert.der().as_ref());
116
117        // Reject a valid keypair for the wrong account zone, then an incomplete
118        // cert/key rotation. Both must leave the trusted live pair untouched.
119        std::fs::write(&config.tls_cert, wrong_zone.cert.pem())?;
120        std::fs::write(&config.tls_key, wrong_zone.key_pair.serialize_pem())?;
121        tokio::time::sleep(Duration::from_millis(80)).await;
122        assert_eq!(peer().await?, first.cert.der().as_ref());
123        std::fs::write(&config.tls_cert, second.cert.pem())?;
124        tokio::time::sleep(Duration::from_millis(80)).await;
125        assert_eq!(peer().await?, first.cert.der().as_ref());
126
127        std::fs::write(&config.tls_key, second.key_pair.serialize_pem())?;
128        tokio::time::timeout(Duration::from_secs(2), async {
129            loop {
130                if peer().await? == second.cert.der().as_ref() {
131                    return Ok::<_, anyhow::Error>(());
132                }
133                tokio::time::sleep(Duration::from_millis(10)).await;
134            }
135        })
136        .await??;
137        shutdown.notify_one();
138        tokio::time::timeout(Duration::from_secs(2), server).await???;
139        drop(std::net::TcpListener::bind(address)?);
140        Ok(())
141    }
142}