ctb_io_webui/
server.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later AND MIT
2// SPDX-License-Identifier for parts derived from from axum-extra: MIT
3/*
4This file is part of Collective Toolbox, a database and document workspace and utilities.
5Copyright (C) 2026 Collective Toolbox Developers
6Contact: info@collectivetoolbox.com
7
8This program is free software: you can redistribute it and/or modify it under
9the terms of the GNU Affero General Public License as published by the Free
10Software Foundation, either version 3 of the License, or (at your option) any
11later version.
12
13This program is distributed in the hope that it will be useful, but WITHOUT ANY
14WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
16
17You should have received a copy of the GNU Affero General Public License along
18with this program.  If not, see <https://www.gnu.org/licenses/>.
19*/
20
21// Parts derived from axum-extra (https://github.com/tokio-rs/axum/blob/b1cd1c17cb82fa26b526e0b9d99a0ac4794e139e/axum-extra/src/extract/host.rs):
22
23// Copyright (c) 2019–2025 axum Contributors
24
25// See additional licensing details at end of file.
26
27//! HTTP/HTTPS web application server and router initialization.
28
29use std::net::{Ipv4Addr, SocketAddr};
30use std::sync::Arc;
31
32use crate::middleware::compression_with_range::CompressionLayer as CompressionWithRangeLayer;
33use ::http::header;
34use anyhow::{Context, Result};
35use axum::Router;
36use axum::response::IntoResponse;
37use axum::{middleware, response::Response};
38use axum_server::tls_rustls::RustlsConfig;
39use portpicker::pick_unused_port;
40use rustls::ServerConfig;
41use rustls::server::WebPkiClientVerifier;
42use rustls_pki_types::CertificateDer;
43use rustls_pki_types::pem::PemObject;
44use std::time::Duration;
45use tower_http::compression::CompressionLayer;
46use tower_http::cors::CorsLayer;
47
48use crate::AppState;
49use crate::extractors::request_uri::RequestUri;
50use crate::middleware::access_log_layer::AccessLogLayer;
51use crate::routes::build_routes;
52use crate::tls_rustls_vendored::typed_der_from_pem;
53use crate::utilities::*;
54
55const SLOW_TTFB_THRESHOLD: Duration = Duration::from_millis(150);
56
57async fn redirect_www_to_non_www_middleware(
58    req: axum::http::Request<axum::body::Body>,
59    next: middleware::Next,
60) -> Response {
61    let Ok(settings) = pc_settings::PcSettings::load() else {
62        return next.run(req).await;
63    };
64
65    if !settings.get_bool(&pc_settings::PcSettingBoolKey::RedirectWwwToNonWww) {
66        return next.run(req).await;
67    }
68
69    let Some(host_header) = req
70        .headers()
71        .get(header::HOST)
72        .and_then(|h| h.to_str().ok())
73    else {
74        return next.run(req).await;
75    };
76
77    let host_header = host_header.trim();
78    if !host_header.starts_with("www.") {
79        return next.run(req).await;
80    }
81
82    #[expect(
83        clippy::expect_used,
84        reason = "host_header established to start with www. (4 ASCII bytes) above"
85    )]
86    let host_without_www = host_header
87        .get(4..)
88        .expect("Checked starts with www. above");
89    if host_without_www.is_empty() {
90        return next.run(req).await;
91    }
92
93    // Reason for fallback: URI without PathAndQuery component redirects to root path "/"
94    let path_and_query =
95        req.uri().path_and_query().map_or("/", |pq| pq.as_str());
96
97    // Use a scheme-relative URL to preserve http vs https.
98    let redirect_url = format!("//{host_without_www}{path_and_query}");
99    axum::response::Redirect::permanent(&redirect_url).into_response()
100}
101
102async fn redirect_ip_subdomains_middleware(
103    req: axum::http::Request<axum::body::Body>,
104    next: middleware::Next,
105) -> Response {
106    let Some(host_header) = req
107        .headers()
108        .get(header::HOST)
109        .and_then(|h| h.to_str().ok())
110    else {
111        return next.run(req).await;
112    };
113
114    let host_header = host_header.trim();
115    let is_ipv4 = host_header.starts_with("ipv4.");
116    let is_ipv6 = host_header.starts_with("ipv6.");
117
118    if is_ipv4 || is_ipv6 {
119        // Exception: allow /api/ip on ipv4. and ipv6. subdomains without redirect
120        if req.uri().path() == "/api/ip" {
121            return next.run(req).await;
122        }
123
124        #[expect(
125            clippy::expect_used,
126            reason = "host_header established to start with ipv4. or ipv6. (5 ASCII bytes) above"
127        )]
128        let host_without_prefix = host_header
129            .get(5..)
130            .expect("Checked starts with ipv4. or ipv6. above");
131
132        if !host_without_prefix.is_empty() {
133            // Reason for fallback: URI without PathAndQuery component redirects to root path "/"
134            let path_and_query =
135                req.uri().path_and_query().map_or("/", |pq| pq.as_str());
136            let redirect_url =
137                format!("//{host_without_prefix}{path_and_query}");
138            return axum::response::Redirect::permanent(&redirect_url)
139                .into_response();
140        }
141    }
142
143    next.run(req).await
144}
145
146async fn clear_invalid_session_middleware(
147    req: axum::http::Request<axum::body::Body>,
148    next: middleware::Next,
149) -> Response {
150    let session_key_str =
151        crate::session_auth::session_key_string_from_headers(req.headers());
152    let mut resp = next.run(req).await;
153
154    if let Some(session_key_str) = session_key_str {
155        let already_sets_session = resp
156            .headers()
157            .get_all(header::SET_COOKIE)
158            .iter()
159            .any(|v| v.to_str().is_ok_and(|s| s.starts_with("session=")));
160
161        if !already_sets_session {
162            use base64::Engine;
163            let is_valid = base64::engine::general_purpose::URL_SAFE_NO_PAD
164                .decode(&session_key_str)
165                .ok()
166                .and_then(|key_bytes| {
167                    let token =
168                        base64::engine::general_purpose::URL_SAFE_NO_PAD
169                            .encode(&key_bytes);
170                    ctb_storage::user::validate_session(&token).ok().flatten()
171                })
172                .is_some();
173
174            if !is_valid {
175                if let Ok(cookie_val) = header::HeaderValue::from_str(
176                    "session=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax",
177                ) {
178                    resp.headers_mut().append(header::SET_COOKIE, cookie_val);
179                }
180            }
181        }
182    }
183
184    resp
185}
186
187#[derive(Clone, Copy, Debug)]
188struct OnlyForContentTypes;
189
190impl tower_http::compression::Predicate for OnlyForContentTypes {
191    fn should_compress<B>(&self, response: &::http::Response<B>) -> bool {
192        if let Some(content_type) = response.headers().get(header::CONTENT_TYPE)
193        {
194            if let Ok(content_type_str) = content_type.to_str() {
195                return content_type_str
196                    .starts_with("application/x-executable")
197                    || content_type_str
198                        .starts_with("application/octet-stream")
199                    || content_type_str.starts_with("application/x-tar");
200            }
201        }
202        false
203    }
204}
205
206pub fn build_app_router(state: AppState) -> Router {
207    build_routes(state)
208        .layer(AccessLogLayer::new_elf(
209            SLOW_TTFB_THRESHOLD,
210            "c-ip c-ident c-user date time cs-method cs-uri cs-version sc-status sc-bytes cs(User-Agent)",
211        ))
212        // See https://docs.rs/tower-http/latest/tower_http/compression/struct.DefaultPredicate.html
213        // As of Jan 17 2026, compresses unless it's gRPC, content-type
214        // image/*, content-type text/event-stream, or response < 32 bytes.
215        // We exclude compression for installer binaries, tarballs, gzipped files,
216        // and chunk streams to ensure Range requests and Accept-Ranges work correctly.
217        .layer({
218            use tower_http::compression::predicate::{DefaultPredicate, NotForContentType, Predicate};
219            let predicate = DefaultPredicate::new()
220                .and(NotForContentType::new("application/gzip"))
221                .and(NotForContentType::new("application/x-gzip"))
222                .and(NotForContentType::new("application/x-executable"))
223                .and(NotForContentType::new("application/octet-stream"))
224                .and(NotForContentType::new("application/x-tar"));
225            CompressionLayer::new().compress_when(predicate)
226        })
227        .layer({
228            use tower_http::compression::predicate::{DefaultPredicate, Predicate};
229            let predicate = DefaultPredicate::new().and(OnlyForContentTypes);
230            CompressionWithRangeLayer::new().compress_when(predicate)
231        })
232        .layer(CorsLayer::permissive())
233        .layer(middleware::from_fn(redirect_ip_subdomains_middleware))
234        .layer(middleware::from_fn(redirect_www_to_non_www_middleware))
235        .layer(middleware::from_fn(clear_invalid_session_middleware))
236        .layer(middleware::from_fn(
237            crate::middleware::markdown_negotiation::markdown_negotiation_middleware,
238        ))
239}
240
241#[expect(
242    clippy::too_many_lines,
243    reason = "webui startup setup function is naturally long"
244)]
245pub fn start_webui_server() -> u16 {
246    log!("Starting local web UI server");
247    // Reason for fallback: unreadable settings file defaults web UI server configuration to initial settings
248    let current_settings = pc_settings::PcSettings::load().unwrap_or_default();
249    // debug_fmt!("Current PC settings for web UI: {:#?}", current_settings);
250
251    let tls_certificate =
252        current_settings.get_str(&pc_settings::PcSettingStrKey::TlsCertificate);
253    let tls_private_key =
254        current_settings.get_str(&pc_settings::PcSettingStrKey::TlsPrivateKey);
255    let tls_client_verification_cert = current_settings
256        .get_str(&pc_settings::PcSettingStrKey::TlsClientVerificationCert);
257
258    let protocol: String = if tls_certificate.is_some() {
259        log!("Using HTTPS");
260        "https".to_string()
261    } else {
262        log!("Using HTTP");
263        "http".to_string()
264    };
265    let relevant_port = if protocol == "http" {
266        current_settings.get_u16(&pc_settings::PcSettingU16Key::FixedHttpPort)
267    } else {
268        current_settings.get_u16(&pc_settings::PcSettingU16Key::FixedHttpsPort)
269    };
270    let _port: u16 = if let Some(port) = relevant_port {
271        log!("Using fixed port from settings: {}", port);
272        port
273    } else if let Some(port) = pick_unused_port() {
274        port
275    } else {
276        warn!("No ports free; not starting web UI.");
277        return 0;
278    };
279    let port: u16 = if let Some(port) = relevant_port {
280        log!("Using fixed port from settings: {}", port);
281        port
282    } else {
283        // Intentionally panicking here
284        #[expect(
285            clippy::expect_used,
286            reason = "There's no elegant way to recover in this case if the user's expecting the webUI to come up."
287        )]
288        pick_unused_port().expect("No ports free")
289    };
290    let bind_to_ip =
291        current_settings.get_str(&pc_settings::PcSettingStrKey::BindToIp);
292    let bind_to_ip = if let Some(s) = bind_to_ip {
293        s.clone()
294    } else {
295        warn!("No bind IP configured; not starting web UI.");
296        return 0;
297    };
298    // Reason for fallback: invalid IP address format in settings evaluates bind address as specified
299    let is_zero_ip =
300        ctb_formats_ipaddr::is_unspecified(&bind_to_ip).unwrap_or(false);
301    if is_zero_ip {
302        let admin_password_hash = current_settings
303            .get_str(&pc_settings::PcSettingStrKey::AdminPasswordHash);
304        if admin_password_hash.is_none() {
305            warn!(
306                "Refusing to listen on unspecified address (such as 0.0.0.0) because no admin password has been set. Not starting web UI."
307            );
308            return 0;
309        }
310    }
311    if bind_to_ip != "127.0.0.1" && protocol == "http" {
312        warn!(
313            "Binding web UI to non-localhost IP over HTTP is insecure; consider enabling HTTPS."
314        );
315    }
316    log!("Using server address: {}", bind_to_ip.clone());
317    let domain: String = match &current_settings
318        .get_str(&pc_settings::PcSettingStrKey::DomainName)
319    {
320        Some(domain) => {
321            log!("Using configured domain name: {}", domain.clone());
322            domain.clone()
323        }
324        None => bind_to_ip.clone(),
325    };
326    let protocol_clone = protocol.clone();
327    let bind_to_ip_clone = bind_to_ip.clone();
328    let domain_clone = domain.clone();
329    std::thread::spawn(move || {
330        if let Err(e) = start_webui_server_inner(
331            port,
332            protocol_clone,
333            bind_to_ip_clone,
334            Some(domain_clone),
335            tls_certificate,
336            tls_private_key,
337            tls_client_verification_cert,
338        ) {
339            log!(format!("Web UI server failed to start: {e:?}"));
340        }
341    });
342
343    // If using HTTPS and not on port 80, also start up a HTTP->HTTPS redirector
344    let http_redirect =
345        current_settings.get_bool(&pc_settings::PcSettingBoolKey::HttpRedirect);
346
347    if protocol == "https" && port != 80 && http_redirect {
348        let redirect_from_port = 80;
349        let bind_to_ip_clone = bind_to_ip.clone();
350        std::thread::spawn(move || {
351            // Check if we can bind to port 80 on the given IP
352            let can_bind = bind_to_ip_clone
353                .parse::<Ipv4Addr>()
354                .ok()
355                .and_then(|ip| {
356                    std::net::TcpListener::bind((ip, redirect_from_port)).ok()
357                })
358                .is_some();
359            if !can_bind {
360                log!(
361                    "Cannot bind to port 80 for HTTP->HTTPS redirector, skipping"
362                );
363                return;
364            }
365
366            let rt = match tokio::runtime::Builder::new_multi_thread()
367                .enable_all()
368                .thread_name("localwebui-redirect")
369                .build()
370            {
371                Ok(rt) => rt,
372                Err(e) => {
373                    log!(format!(
374                        "Failed building redirector tokio runtime: {e:?}"
375                    ));
376                    return;
377                }
378            };
379
380            let result = rt.block_on(http_to_https(
381                bind_to_ip_clone,
382                redirect_from_port,
383                port,
384            ));
385            if let Err(e) = result {
386                log!(format!("HTTP->HTTPS redirector failed: {e:?}"));
387            }
388        });
389    }
390
391    let url = format!("{protocol}://{domain}:{port}");
392    let probe_ip = if is_zero_ip {
393        Some(Ipv4Addr::LOCALHOST)
394    } else {
395        bind_to_ip.parse::<Ipv4Addr>().ok()
396    };
397
398    tokio::task::spawn_blocking(move || {
399        // Wait for the TCP listener to bind before issuing an HTTP request so we
400        // do not trigger HTTP client retry backoff while templates are compiling.
401        if let Some(ip) = probe_ip {
402            let sock_addr = std::net::SocketAddr::from((ip, port));
403            let mut tcp_tries: u32 = 0;
404            while std::net::TcpStream::connect_timeout(
405                &sock_addr,
406                Duration::from_millis(100),
407            )
408            .is_err()
409            {
410                tcp_tries = tcp_tries.saturating_add(1);
411                if tcp_tries >= 250 {
412                    break;
413                }
414                std::thread::sleep(Duration::from_millis(20));
415            }
416        }
417
418        // Request the URL in a loop until successful, to open the browser once the server is ready
419        let mut tries: u32 = 0;
420        loop {
421            tries = tries.saturating_add(1);
422            if tries > 50 {
423                error_fmt!(
424                    "Giving up trying to contact web UI server after {} tries",
425                    tries.saturating_sub(1)
426                );
427                break;
428            }
429
430            let response = https::blocking_client_no_crlite_with_timeout(Some(
431                Duration::from_secs(1),
432            ))
433            .and_then(|client| client.get_with_backoff(&url, 0));
434            log!("Waiting for web UI server to be ready...");
435            match response {
436                Ok(resp) => {
437                    if resp.is_success() {
438                        break;
439                    }
440                }
441                Err(_) => {
442                    log!("Server not yet ready...");
443                    // Server not ready yet
444                }
445            }
446            std::thread::sleep(Duration::from_millis(50));
447        }
448
449        let result = crate::webview::open_browser_url(url.as_str());
450        if let Err(e) = result {
451            log!(format!("Failed to open web browser automatically: {e:?}"));
452            log!(format!(
453                "Please open your web browser and navigate to {url}"
454            ));
455        } else {
456            log!(format!("Web browser opened to {url}"));
457        }
458    });
459
460    port
461}
462
463/// Helper that resolves the host of the request.
464///
465/// Host is resolved through the following, in order:
466/// - `Forwarded` header
467/// - `X-Forwarded-Host` header
468/// - `Host` header
469/// - Authority of the request URI
470///
471/// See <https://www.rfc-editor.org/rfc/rfc9110.html#name-host-and-authority> for the definition of
472/// host.
473///
474/// Note that user agents can set `X-Forwarded-Host` and `Host` headers to arbitrary values so make
475/// sure to validate them to avoid security issues.
476///
477/// This is based on the Host extractor that was deprecated and removed from axum-extra.
478fn resolve_host(headers: &header::HeaderMap, uri: &axum::http::Uri) -> String {
479    // 1. Forwarded
480    if let Some(forwarded) =
481        headers.get(header::FORWARDED).and_then(|h| h.to_str().ok())
482    {
483        if let Some(first_value) = forwarded.split(',').next() {
484            for pair in first_value.split(';') {
485                if let Some((key, value)) = pair.split_once('=') {
486                    if key.trim().eq_ignore_ascii_case("host") {
487                        return value.trim().trim_matches('"').to_string();
488                    }
489                }
490            }
491        }
492    }
493
494    // 2. X-Forwarded-Host
495    if let Some(host) = headers
496        .get("X-Forwarded-Host")
497        .and_then(|h| h.to_str().ok())
498    {
499        return host.to_string();
500    }
501
502    // 3. Host
503    if let Some(host) = headers.get(header::HOST).and_then(|h| h.to_str().ok())
504    {
505        return host.to_string();
506    }
507
508    // 4. Request URI authority
509    if let Some(authority) = uri.authority() {
510        return authority
511            .as_str()
512            .rsplit('@')
513            .next()
514            // Reason for fallback: URI authority slice without userinfo segment retains full authority host
515            .unwrap_or("")
516            .to_string();
517    }
518
519    String::new()
520}
521
522fn http_to_https_controller(
523    redirect_to_port: u16,
524    host: String,
525    uri: RequestUri,
526) -> impl IntoResponse {
527    let uri = uri.0;
528    let redirect_to_port = if redirect_to_port == 443 {
529        String::new()
530    } else {
531        format!(":{redirect_to_port}")
532    };
533    let redirect_url = format!("https://{host}{redirect_to_port}{uri}");
534    axum::response::Redirect::permanent(&redirect_url)
535}
536
537async fn http_to_https(
538    bind_to_ip: String,
539    redirect_from_port: u16,
540    redirect_to_port: u16,
541) -> Result<()> {
542    let ip = bind_to_ip.parse::<Ipv4Addr>().with_context(|| {
543        format!("Could not parse bind IP address: {bind_to_ip}")
544    })?;
545    let addr = SocketAddr::from((ip, redirect_from_port));
546
547    axum_server::bind(addr)
548        .serve(
549            Router::new()
550                .fallback(axum::routing::any(
551                    move |headers: header::HeaderMap,
552                          uri: axum::http::Uri,
553                          request_uri: RequestUri| async move {
554                        let host = resolve_host(&headers, &uri);
555                        http_to_https_controller(
556                            redirect_to_port,
557                            host,
558                            request_uri,
559                        )
560                    },
561                ))
562                .into_make_service(),
563        )
564        .await
565        .context("Error in HTTP to HTTPS redirector")?;
566
567    Ok(())
568}
569
570fn start_webui_server_inner(
571    port: u16,
572    protocol: String,
573    bind_to_ip: String,
574    _domain_name: Option<String>,
575    tls_certificate: Option<String>,
576    tls_private_key: Option<String>,
577    tls_client_verification_cert: Option<String>,
578) -> Result<()> {
579    // Build templates once and share via state
580    let state = AppState::try_new()?;
581
582    // Clear downloads_cache directories at server startup
583    if let Ok(storage_dir) = ctb_utilities::storage::get_storage_dir() {
584        let cache_dir = storage_dir.join("releases").join("downloads_cache");
585        if cache_dir.exists() {
586            if let Err(e) = std::fs::remove_dir_all(&cache_dir) {
587                warn_fmt!(
588                    "Failed to clear downloads cache directory {}: {e}",
589                    cache_dir.display()
590                );
591            }
592        }
593    }
594    if let Ok(app_cache_dir) = ctb_utilities::storage::get_cache_dir() {
595        let cache_dir = app_cache_dir.join("downloads_cache");
596        if cache_dir.exists() {
597            if let Err(e) = std::fs::remove_dir_all(&cache_dir) {
598                warn_fmt!(
599                    "Failed to clear downloads cache directory {}: {e}",
600                    cache_dir.display()
601                );
602            }
603        }
604    }
605
606    let app = build_app_router(state);
607
608    // Run on a dedicated runtime in this thread
609    let rt = tokio::runtime::Builder::new_multi_thread()
610        .enable_all()
611        .thread_name("localwebui-axum")
612        .build()
613        .context("failed building tokio runtime")?;
614
615    rt.block_on(async move {
616        let ip = bind_to_ip.parse::<Ipv4Addr>().with_context(|| {
617            format!("Could not parse bind IP address: {bind_to_ip}")
618        })?;
619        let addr = SocketAddr::from((ip, port));
620
621        // NOTE: into_make_service_with_connect_info enables the ConnectInfo<SocketAddr> extraction
622        let make_service =
623            app.into_make_service_with_connect_info::<SocketAddr>();
624
625        if protocol == "http" {
626            axum_server::bind(addr)
627                .serve(make_service)
628                .await
629                .context("HTTP server exited with error")?;
630            return Ok(());
631        }
632
633        let cert_pem = tls_certificate
634            .context("TLS certificate not provided, cannot start HTTPS server")?
635            .into_bytes();
636        let key_pem = tls_private_key
637            .context("TLS private key not provided, cannot start HTTPS server")?
638            .into_bytes();
639
640        let tls_client_verification_cert =
641            tls_client_verification_cert.filter(|pem| !pem.trim().is_empty());
642
643        let server_config = build_rustls_server_config(
644            cert_pem,
645            key_pem,
646            tls_client_verification_cert.as_deref(),
647        )
648        .context("Failed to build rustls ServerConfig")?;
649
650        let config = RustlsConfig::from_config(Arc::new(server_config));
651
652        axum_server::bind_rustls(addr, config)
653            .serve(make_service)
654            .await
655            .context("HTTPS server exited with error")?;
656
657        Ok(())
658    })
659}
660
661// TODO: This is LLM-generated. Should check for correctness. I'm also unsure
662// about the use of `'static` in `typed_der_from_pem`.
663fn build_rustls_server_config(
664    server_cert_pem: Vec<u8>,
665    server_key_pem: Vec<u8>,
666    client_verification_ca_pem: Option<&str>,
667) -> Result<ServerConfig> {
668    let (server_certs, server_key) =
669        typed_der_from_pem(server_cert_pem, server_key_pem)
670            .context("Failed to parse TLS certificate/private key PEM")?;
671
672    let mut server_config = if let Some(ca_pem) = client_verification_ca_pem {
673        let root_store = root_cert_store_from_pem(ca_pem).context(
674            "Failed to parse TLS client verification certificate(s)",
675        )?;
676        let client_verifier =
677            WebPkiClientVerifier::builder(Arc::new(root_store))
678                .build()
679                .context("Failed to build TLS client certificate verifier")?;
680
681        log!("Enabled TLS client certificate verification");
682        ServerConfig::builder()
683            .with_client_cert_verifier(client_verifier)
684            .with_single_cert(server_certs, server_key)
685            .context("Invalid TLS certificate/private key")?
686    } else {
687        ServerConfig::builder()
688            .with_no_client_auth()
689            .with_single_cert(server_certs, server_key)
690            .context("Invalid TLS certificate/private key")?
691    };
692
693    server_config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
694    Ok(server_config)
695}
696
697fn root_cert_store_from_pem(pem: &str) -> Result<rustls::RootCertStore> {
698    let mut cursor = std::io::Cursor::new(pem.as_bytes());
699    let mut root_store = rustls::RootCertStore::empty();
700    let mut loaded = 0usize;
701
702    for cert in CertificateDer::pem_reader_iter(&mut cursor) {
703        let cert =
704            cert.context("Invalid PEM in client verification certificate")?;
705        root_store.add(cert).context(
706            "Failed to add client verification certificate to trust store",
707        )?;
708        loaded = loaded.saturating_add(1);
709    }
710
711    if loaded == 0 {
712        anyhow::bail!("No certificates found in client verification PEM");
713    }
714
715    Ok(root_store)
716}
717
718#[cfg(test)]
719#[allow(
720    clippy::panic,
721    clippy::expect_used,
722    clippy::unwrap_used,
723    clippy::unwrap_in_result,
724    clippy::panic_in_result_fn,
725    clippy::indexing_slicing,
726    clippy::arithmetic_side_effects,
727    reason = "Standard repository test boilerplate"
728)]
729mod tests {
730    use super::*;
731    use axum::http::{Request, StatusCode};
732    use tower::ServiceExt;
733
734    use crate::json::maybe_value::MaybeValue;
735
736    #[crate::ctb_test("tokio")]
737    async fn redirects_www_to_non_www_when_enabled() {
738        let old_settings = pc_settings::PcSettings::load().unwrap_or_default();
739
740        let new_settings = pc_settings::PcSettings {
741            redirect_www_to_non_www: MaybeValue::Value(true),
742            ..Default::default()
743        };
744        new_settings.save().unwrap();
745
746        let app = build_app_router(AppState::try_new().unwrap());
747        let request = Request::builder()
748            .uri("/hello?x=1")
749            .header("Host", "www.example.com")
750            .body(axum::body::Body::empty())
751            .unwrap();
752
753        let response = app.oneshot(request).await.unwrap();
754        assert_eq!(response.status(), StatusCode::PERMANENT_REDIRECT);
755
756        let location = response
757            .headers()
758            .get("location")
759            .expect("expected Location header")
760            .to_str()
761            .unwrap();
762        assert_eq!(location, "//example.com/hello?x=1");
763
764        old_settings.save().unwrap();
765    }
766
767    #[crate::ctb_test("tokio")]
768    async fn test_clears_invalid_session_cookie() {
769        let app = build_app_router(AppState::try_new().unwrap());
770        let request = Request::builder()
771            .uri("/")
772            .header("Cookie", "session=invalid_or_expired_token")
773            .body(axum::body::Body::empty())
774            .unwrap();
775
776        let response = app.oneshot(request).await.unwrap();
777        let set_cookie = response
778            .headers()
779            .get("set-cookie")
780            .expect("expected Set-Cookie header")
781            .to_str()
782            .unwrap();
783        assert!(set_cookie.contains("session="));
784        assert!(set_cookie.contains("Max-Age=0"));
785    }
786
787    #[crate::ctb_test]
788    fn refuses_to_listen_on_zero_ip_without_admin_password() {
789        let old_settings = pc_settings::PcSettings::load().unwrap_or_default();
790
791        let new_settings = pc_settings::PcSettings {
792            bind_to_ip: MaybeValue::Value("0.0.0.0".to_string()),
793            admin_password_hash: crate::json::maybe_value::MaybeOption::Null,
794            ..Default::default()
795        };
796        new_settings.save().unwrap();
797
798        // `start_webui_server` should return 0 (refuse to start)
799        let port = start_webui_server();
800        assert_eq!(port, 0);
801
802        old_settings.save().unwrap();
803    }
804
805    #[crate::ctb_test]
806    fn test_resolve_host() {
807        use axum::http::Uri;
808        use axum::http::header::{FORWARDED, HOST, HeaderMap};
809
810        // 1. Host header
811        let mut headers = HeaderMap::new();
812        headers.insert(HOST, "example.com:8080".parse().unwrap());
813        let uri: Uri = "/".parse().unwrap();
814        assert_eq!(resolve_host(&headers, &uri), "example.com:8080");
815
816        // 2. X-Forwarded-Host header
817        let mut headers = HeaderMap::new();
818        headers.insert("X-Forwarded-Host", "proxy.com".parse().unwrap());
819        headers.insert(HOST, "example.com:8080".parse().unwrap());
820        assert_eq!(resolve_host(&headers, &uri), "proxy.com");
821
822        // 3. Forwarded header
823        let mut headers = HeaderMap::new();
824        headers
825            .insert(FORWARDED, "host=forward.com;proto=http".parse().unwrap());
826        headers.insert("X-Forwarded-Host", "proxy.com".parse().unwrap());
827        assert_eq!(resolve_host(&headers, &uri), "forward.com");
828
829        // 4. URI host (IPv4)
830        let headers = HeaderMap::new();
831        let uri: Uri = "https://127.0.0.1:1234/image.jpg".parse().unwrap();
832        assert_eq!(resolve_host(&headers, &uri), "127.0.0.1:1234");
833
834        // 5. URI host (IPv6)
835        let headers = HeaderMap::new();
836        let uri: Uri = "http://cool:user@[::1]:456/file.txt".parse().unwrap();
837        assert_eq!(resolve_host(&headers, &uri), "[::1]:456");
838
839        // 6. Missing host fallback
840        let headers = HeaderMap::new();
841        let uri: Uri = "/".parse().unwrap();
842        assert_eq!(resolve_host(&headers, &uri), "");
843
844        // 7. Forwarded parsing edge cases
845        // - Case insensitivity of the "host" key in Forwarded header
846        let mut headers = HeaderMap::new();
847        headers
848            .insert(FORWARDED, "HOST=192.0.2.60;proto=http".parse().unwrap());
849        let uri: Uri = "/".parse().unwrap();
850        assert_eq!(resolve_host(&headers, &uri), "192.0.2.60");
851
852        // - IPv6 host quoted
853        let mut headers = HeaderMap::new();
854        headers.insert(
855            FORWARDED,
856            "host=\"[2001:db8:cafe::17]:4711\"".parse().unwrap(),
857        );
858        assert_eq!(resolve_host(&headers, &uri), "[2001:db8:cafe::17]:4711");
859
860        // - Multiple values in one header
861        let mut headers = HeaderMap::new();
862        headers.insert(
863            FORWARDED,
864            "host=192.0.2.60, host=127.0.0.1".parse().unwrap(),
865        );
866        assert_eq!(resolve_host(&headers, &uri), "192.0.2.60");
867
868        // - Multiple header values (separate lines)
869        let mut headers = HeaderMap::new();
870        headers.append(FORWARDED, "host=192.0.2.60".parse().unwrap());
871        headers.append(FORWARDED, "host=127.0.0.1".parse().unwrap());
872        assert_eq!(resolve_host(&headers, &uri), "192.0.2.60");
873    }
874
875    #[crate::ctb_test]
876    fn test_build_rustls_server_config() {
877        let cert_pem =
878            crate::tls_rustls_vendored::get_tls_rustls_vendored_data(
879                "fixtures/cert.pem",
880            )
881            .expect("failed to get embedded cert.pem");
882        let key_pem = crate::tls_rustls_vendored::get_tls_rustls_vendored_data(
883            "fixtures/key.pem",
884        )
885        .expect("failed to get embedded key.pem");
886
887        // 1. Without client auth
888        let _config_no_auth =
889            build_rustls_server_config(cert_pem.clone(), key_pem.clone(), None)
890                .expect("failed to build ServerConfig without client auth");
891
892        // 2. With client auth (using the same cert as CA for testing)
893        let cert_str = std::str::from_utf8(&cert_pem).unwrap();
894        let _config_with_auth = build_rustls_server_config(
895            cert_pem.clone(),
896            key_pem,
897            Some(cert_str),
898        )
899        .expect("failed to build ServerConfig with client auth");
900    }
901
902    #[crate::ctb_test("tokio")]
903    async fn test_redirect_ip_subdomains_middleware() {
904        use crate::test_helpers::TestApp;
905        use axum::http::{HeaderMap, HeaderValue, Method, StatusCode};
906
907        let test_app = TestApp::new();
908
909        // 1. Non-api path on ipv4. should redirect
910        let mut headers = HeaderMap::new();
911        headers.insert(
912            "Host",
913            HeaderValue::from_static("ipv4.collectivetoolbox.com"),
914        );
915        let resp = test_app
916            .request_get_response::<()>(
917                Method::GET,
918                "/robots.txt",
919                Some(headers),
920                None,
921                None,
922                None,
923            )
924            .await;
925        assert_eq!(resp.status(), StatusCode::PERMANENT_REDIRECT);
926        let location =
927            resp.headers().get("location").unwrap().to_str().unwrap();
928        assert_eq!(location, "//collectivetoolbox.com/robots.txt");
929
930        // 2. Non-api path on ipv6. with port should redirect
931        let mut headers = HeaderMap::new();
932        headers.insert(
933            "Host",
934            HeaderValue::from_static("ipv6.collectivetoolbox.com:8080"),
935        );
936        let resp = test_app
937            .request_get_response::<()>(
938                Method::GET,
939                "/robots.txt",
940                Some(headers),
941                None,
942                None,
943                None,
944            )
945            .await;
946        assert_eq!(resp.status(), StatusCode::PERMANENT_REDIRECT);
947        let location =
948            resp.headers().get("location").unwrap().to_str().unwrap();
949        assert_eq!(location, "//collectivetoolbox.com:8080/robots.txt");
950
951        // 3. /api/ip on ipv4. should NOT redirect
952        let mut headers = HeaderMap::new();
953        headers.insert(
954            "Host",
955            HeaderValue::from_static("ipv4.collectivetoolbox.com"),
956        );
957        let resp = test_app
958            .request_get_response::<()>(
959                Method::GET,
960                "/api/ip",
961                Some(headers),
962                None,
963                None,
964                None,
965            )
966            .await;
967        assert_eq!(resp.status(), StatusCode::OK);
968
969        // 4. /api/ip on ipv6. should NOT redirect
970        let mut headers = HeaderMap::new();
971        headers.insert(
972            "Host",
973            HeaderValue::from_static("ipv6.collectivetoolbox.com"),
974        );
975        let resp = test_app
976            .request_get_response::<()>(
977                Method::GET,
978                "/api/ip",
979                Some(headers),
980                None,
981                None,
982                None,
983            )
984            .await;
985        assert_eq!(resp.status(), StatusCode::OK);
986    }
987}
988
989/*
990Code from axum-extra is used under the following license:
991======
992
993MIT License
994
995Copyright (c) 2019–2025 axum Contributors
996
997Permission is hereby granted, free of charge, to any
998person obtaining a copy of this software and associated
999documentation files (the "Software"), to deal in the
1000Software without restriction, including without
1001limitation the rights to use, copy, modify, merge,
1002publish, distribute, sublicense, and/or sell copies of
1003the Software, and to permit persons to whom the Software
1004is furnished to do so, subject to the following
1005conditions:
1006
1007The above copyright notice and this permission notice
1008shall be included in all copies or substantial portions
1009of the Software.
1010
1011THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
1012ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
1013TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
1014PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
1015SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
1016CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
1017OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
1018IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
1019DEALINGS IN THE SOFTWARE.
1020
1021*/