Skip to main content

rws_proxy/config_check/
mod.rs

1//! `rws --check`: validate `rws.config.toml` without starting the server —
2//! the counterpart of `nginx -t` / `caddy validate`.
3//!
4//! Reports unknown keys (in settings and in proxy sections), values of the
5//! wrong type, TLS files that can't be loaded, proxy routes pointing at
6//! undeclared upstreams, auth secrets that aren't set, and similar mistakes
7//! that would otherwise surface as a warning in the startup log or as a 503
8//! at request time. Nothing is bound and the environment is not modified.
9//!
10//! ```bash
11//! rws --check                      # the file rws would load (RWS_CONFIG_FILE or ./rws.config.toml)
12//! rws --check=/etc/rws/site.toml   # a specific file
13//! ```
14
15#[cfg(test)]
16mod tests;
17pub mod syntax;
18
19use std::io::Cursor;
20use std::path::Path;
21
22use crate::entry_point::config_file::collect_settings;
23use crate::entry_point::Config;
24
25/// Errors and warnings found in a configuration file.
26#[derive(Debug, Default, Clone, PartialEq)]
27pub struct ConfigReport {
28    /// Mistakes: the configuration does not do what it says.
29    pub errors: Vec<String>,
30    /// Likely mistakes that don't stop the server working.
31    pub warnings: Vec<String>,
32}
33
34impl ConfigReport {
35    pub fn error(&mut self, message: impl Into<String>) {
36        self.errors.push(message.into());
37    }
38
39    pub fn warn(&mut self, message: impl Into<String>) {
40        self.warnings.push(message.into());
41    }
42
43    /// `true` when there are no errors (warnings are allowed).
44    pub fn is_ok(&self) -> bool {
45        self.errors.is_empty()
46    }
47
48    /// One JSON object: `{"path":…,"ok":…,"errors":[…],"warnings":[…]}`.
49    /// Strings are escaped; exit codes stay with the caller.
50    pub fn render_json(&self, path: &str) -> String {
51        fn escaped(s: &str) -> String {
52            let mut out = String::with_capacity(s.len() + 2);
53            for c in s.chars() {
54                match c {
55                    '"' => out.push_str("\\\""),
56                    '\\' => out.push_str("\\\\"),
57                    '\n' => out.push_str("\\n"),
58                    '\r' => out.push_str("\\r"),
59                    '\t' => out.push_str("\\t"),
60                    c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
61                    c => out.push(c),
62                }
63            }
64            out
65        }
66        let list = |items: &[String]| {
67            let inner: Vec<String> = items.iter().map(|i| format!("\"{}\"", escaped(i))).collect();
68            format!("[{}]", inner.join(","))
69        };
70        format!(
71            "{{\"path\":\"{}\",\"ok\":{},\"errors\":{},\"warnings\":{}}}",
72            escaped(path),
73            self.is_ok(),
74            list(&self.errors),
75            list(&self.warnings),
76        )
77    }
78
79    /// Human-readable report, one finding per line, ending in a verdict.
80    pub fn render(&self, path: &str) -> String {
81        let mut out = String::new();
82        for e in &self.errors {
83            out.push_str(&format!("error: {e}\n"));
84        }
85        for w in &self.warnings {
86            out.push_str(&format!("warning: {w}\n"));
87        }
88        if self.is_ok() {
89            out.push_str(&format!("{path}: configuration OK"));
90            if !self.warnings.is_empty() {
91                out.push_str(&format!(" ({} warning{})", self.warnings.len(), plural(self.warnings.len())));
92            }
93        } else {
94            out.push_str(&format!(
95                "{path}: {} error{}, {} warning{}",
96                self.errors.len(), plural(self.errors.len()),
97                self.warnings.len(), plural(self.warnings.len()),
98            ));
99        }
100        out.push('\n');
101        out
102    }
103}
104
105fn plural(n: usize) -> &'static str {
106    if n == 1 { "" } else { "s" }
107}
108
109/// The path `--check` targets in `args` (the process arguments), or `None`
110/// when `--check` is absent. `--check=<path>` and `--check <path>` name a
111/// file; a bare `--check` checks the file the server would load.
112pub fn check_target_from_args(args: &[String]) -> Option<String> {
113    let mut iter = args.iter().skip(1).peekable();
114    while let Some(arg) = iter.next() {
115        if let Some(path) = arg.strip_prefix("--check=") {
116            return Some(path.to_string());
117        }
118        if arg == "--check" {
119            return Some(match iter.peek() {
120                Some(next) if !next.starts_with('-') => next.to_string(),
121                _ => default_config_path(),
122            });
123        }
124    }
125    None
126}
127
128/// Whether the arguments ask for machine-readable output (`--format=json`).
129pub fn wants_json_output(args: &[String]) -> bool {
130    args.iter().any(|a| a == "--format=json")
131}
132
133/// `RWS_CONFIG_FILE` if set, else `rws.config.toml` in the working directory.
134pub fn default_config_path() -> String {
135    std::env::var("RWS_CONFIG_FILE")
136        .ok()
137        .filter(|p| !p.trim().is_empty())
138        .unwrap_or_else(|| "rws.config.toml".to_string())
139}
140
141/// Check the configuration file at `path`.
142pub fn check_file(path: &str) -> ConfigReport {
143    match std::fs::read_to_string(path) {
144        Ok(content) => check_str(&content),
145        Err(e) => {
146            let mut report = ConfigReport::default();
147            report.error(format!("cannot read {path}: {e}"));
148            report
149        }
150    }
151}
152
153thread_local! {
154    static OFFLINE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
155}
156
157/// `true` inside [`check_str_offline`]: checks that would read this
158/// machine's files or environment are skipped.
159#[doc(hidden)]
160pub fn offline() -> bool {
161    OFFLINE.with(|o| o.get())
162}
163
164/// [`check_str`] without looking at this machine: no file is opened or
165/// tested for existence (certificates, keys, CA bundles, htpasswd files,
166/// static roots, programs) and no environment variable is read (auth
167/// secrets, DNS API credentials). For configuration text from someone else,
168/// e.g. the docs MCP server's `check_config` tool, where those answers would
169/// describe the server, not the caller's deployment.
170pub fn check_str_offline(content: &str) -> ConfigReport {
171    struct Reset;
172    impl Drop for Reset {
173        fn drop(&mut self) {
174            OFFLINE.with(|o| o.set(false));
175        }
176    }
177    OFFLINE.with(|o| o.set(true));
178    let _reset = Reset;
179    check_str(content)
180}
181
182/// Check configuration text. Relative file paths in it (certificates,
183/// htpasswd files, static roots) are resolved against the working directory,
184/// as the server resolves them.
185pub fn check_str(content: &str) -> ConfigReport {
186    let mut report = ConfigReport::default();
187    if content.contains('\0') {
188        report.error("the file contains a NUL byte");
189        return report;
190    }
191
192    for finding in syntax::check(content) {
193        let message = format!("line {}, column {}: {}", finding.line, finding.column, finding.message);
194        if finding.error { report.error(message) } else { report.warn(message) }
195    }
196
197    match collect_settings(Cursor::new(content.as_bytes()), String::new()) {
198        Ok(resolved) => {
199            for key in &resolved.unknown {
200                let hint = crate::entry_point::config_file::suggestion(key).map(|s| format!("; did you mean '{s}'?")).unwrap_or_default();
201                report.error(format!("unknown setting '{key}'{hint} (the server would skip it)"));
202            }
203            check_settings(&resolved.settings, &mut report);
204        }
205        Err(e) => report.error(format!("unable to parse: {e}")),
206    }
207
208    #[cfg(not(target_arch = "wasm32"))]
209    if content.contains("[[route]]") || content.contains("[[upstream]]")
210        || content.contains("[[tcp_proxy]]") || content.contains("[[udp_proxy]]") || content.contains("[[ws_proxy]]")
211    {
212        crate::proxy_config::validate::check_unknown_keys(content, &mut report);
213        crate::proxy_config::ProxyConfig::from_str(content).validate(&mut report);
214    } else if content.lines().any(|l| l.trim().starts_with("[middleware")) {
215        report.warn("[middleware] only applies in proxy mode (a file with [[route]] or [[upstream]] sections)");
216    }
217
218    report
219}
220
221/// Type and consistency checks for the `RWS_CONFIG_*` settings in the file.
222fn check_settings(settings: &[(String, String)], report: &mut ConfigReport) {
223    let get = |name: &str| settings.iter().rev().find(|(n, _)| n == name).map(|(_, v)| v.trim());
224
225    for (name, value) in settings {
226        let value = value.trim();
227        let key = setting_key(name);
228        match name.as_str() {
229            Config::RWS_CONFIG_PORT | Config::RWS_CONFIG_HTTP_REDIRECT_PORT | Config::RWS_CONFIG_ACME_CHALLENGE_PORT => {
230                if !(name == Config::RWS_CONFIG_HTTP_REDIRECT_PORT && value.is_empty())
231                    && !value.parse::<u16>().is_ok_and(|p| p > 0)
232                {
233                    report.error(format!("{key} = {value:?}: not a port number (1-65535)"));
234                }
235            }
236            Config::RWS_CONFIG_IP => {
237                if value.parse::<std::net::IpAddr>().is_err() {
238                    report.error(format!("{key} = {value:?}: not an IP address (use 0.0.0.0 or :: for all interfaces)"));
239                }
240            }
241            Config::RWS_CONFIG_THREAD_COUNT => {
242                if !value.parse::<usize>().is_ok_and(|n| n > 0) {
243                    report.error(format!("{key} = {value:?}: not a positive number"));
244                }
245            }
246            Config::RWS_CONFIG_REQUEST_ALLOCATION_SIZE_IN_BYTES => {
247                if !value.parse::<u64>().is_ok_and(|n| n > 0) {
248                    report.error(format!("{key} = {value:?}: not a positive number"));
249                }
250            }
251            "RWS_CONFIG_MAX_BODY_SIZE_IN_BYTES" | "RWS_CONFIG_OPEN_FILE_CACHE_SECS" | "RWS_CONFIG_RATE_LIMIT_MAX_REQUESTS" | "RWS_CONFIG_RATE_LIMIT_WINDOW_SECS"
252            | "RWS_CONFIG_ACME_RENEW_BEFORE_DAYS" | "RWS_CONFIG_ACME_RENEW_CHECK_INTERVAL_SECS"
253            | "RWS_CONFIG_CIRCUIT_BREAKER_FAILURE_THRESHOLD" | "RWS_CONFIG_CIRCUIT_BREAKER_MAX_HALF_OPEN_PROBES"
254            | "RWS_CONFIG_CIRCUIT_BREAKER_RECOVERY_SECS" | Config::RWS_CONFIG_CORS_MAX_AGE => {
255                if value.parse::<u64>().is_err() {
256                    report.error(format!("{key} = {value:?}: not a whole number"));
257                }
258            }
259            Config::RWS_CONFIG_CORS_ALLOW_ALL | Config::RWS_CONFIG_CORS_ALLOW_CREDENTIALS | Config::RWS_CONFIG_ACME_STAGING
260            | "RWS_CONFIG_CLIENT_HINTS" | "RWS_CONFIG_OPEN_FILE_CACHE_STRICT"
261            | "RWS_CONFIG_SECURITY_HEADERS" | "RWS_CONFIG_NANOS_HEADERS" | "RWS_CONFIG_SERVE_DOTFILES" | "RWS_CONFIG_WATCH"
262            | "RWS_CONFIG_PROXY_PROTOCOL" | "RWS_CONFIG_GATEWAY_API_ENABLED" => {
263                if !matches!(value.to_ascii_lowercase().as_str(), "true" | "false") {
264                    report.error(format!("{key} = {value:?}: expected true or false"));
265                }
266            }
267            "RWS_CONFIG_GATEWAY_API_MODE" => {
268                if !matches!(value.to_ascii_lowercase().as_str(), "shared" | "provisioned") {
269                    report.error(format!("{key} = {value:?}: expected shared or provisioned"));
270                }
271            }
272            "RWS_CONFIG_ACCESS_LOG_MAX_SIZE" | "RWS_CONFIG_ACCESS_LOG_KEEP" => {
273                if crate::disk_guard::parse_size(value).is_none() {
274                    report.error(format!("{key} = {value:?}: expected a number of bytes or files (e.g. 104857600 or 100M)"));
275                }
276            }
277            "RWS_CONFIG_RUNTIME" => {
278                if !matches!(value.to_ascii_lowercase().as_str(), "shared" | "per-core") {
279                    report.error(format!("{key} = {value:?}: expected \"shared\" or \"per-core\""));
280                }
281            }
282            "RWS_CONFIG_ACCESS_LOG_ANONYMIZE_IP" => {
283                if crate::server_config::log_privacy::AnonymizeIp::parse(value).is_none() {
284                    report.error(format!("{key} = {value:?}: expected \"off\", \"truncate\" or \"hash\""));
285                }
286            }
287            // The log module (and syslog) isn't built for wasm32.
288            #[cfg(not(target_arch = "wasm32"))]
289            "RWS_CONFIG_ACCESS_LOG_SYSLOG" => {
290                if !value.trim().is_empty() {
291                    if let Err(e) = crate::log::syslog::Target::parse(value) {
292                        report.error(format!("{key}: {e}"));
293                    }
294                }
295            }
296            #[cfg(not(target_arch = "wasm32"))]
297            "RWS_CONFIG_ACCESS_LOG_SYSLOG_FACILITY" => {
298                if let Err(e) = crate::log::syslog::parse_facility(value) {
299                    report.error(format!("{key}: {e}"));
300                }
301            }
302            "RWS_CONFIG_LOG_FORMAT" => {
303                if !matches!(value.to_ascii_lowercase().as_str(), "combined" | "json" | "off" | "none") {
304                    report.error(format!("{key} = {value:?}: expected \"combined\", \"json\" or \"off\""));
305                }
306            }
307            "RWS_CONFIG_TLS_CLIENT_CA_FILE" | Config::RWS_CONFIG_ACME_CA_FILE => {
308                if !offline() && !value.is_empty() && !Path::new(value).is_file() {
309                    report.error(format!("{key} = {value:?}: file not found"));
310                }
311            }
312            #[cfg(feature = "http2")]
313            "RWS_CONFIG_TLS_CLIENT_CRL_FILE" => {
314                if !offline() && !value.is_empty() {
315                    if let Err(e) = crate::tls::load_crls(value) {
316                        report.error(format!("{key}: {e}"));
317                    }
318                }
319            }
320            "RWS_CONFIG_TRUSTED_PROXIES" => {
321                if let Err(e) = crate::ip_filter::TrustedProxies::parse(value) {
322                    report.error(format!("{key}: {e}"));
323                } else if value.trim() == "*" {
324                    report.warn(format!("{key} = \"*\": every client can set X-Forwarded-Proto/Host and Forwarded (claim https, another host); list your load balancers instead"));
325                }
326            }
327            "RWS_CONFIG_SHUTDOWN_DELAY_SECS" => {
328                if !value.trim().is_empty() && value.trim().parse::<u64>().is_err() {
329                    report.error(format!("{key} = {value:?}: expected a whole number of seconds"));
330                }
331            }
332            "RWS_CONFIG_METRICS_ALLOW" => {
333                if let Err(e) = crate::ip_filter::TrustedProxies::parse(value) {
334                    report.error(format!("{key}: {}", e.replace("trusted_proxies: ", "")));
335                } else if value.trim() == "*" {
336                    report.warn(format!("{key} = \"*\": /metrics (upstream names, backend addresses, traffic) is served to anyone"));
337                }
338            }
339            "RWS_CONFIG_CLIENT_IP" => {
340                let v = value.trim();
341                if !v.is_empty() && !v.eq_ignore_ascii_case("forwarded") && !v.eq_ignore_ascii_case("peer") {
342                    report.error(format!("{key} = {value:?}: expected \"forwarded\" (the client from a trusted proxy's X-Forwarded-For) or \"peer\""));
343                }
344            }
345            "RWS_CONFIG_TLS" => {
346                if !value.is_empty() && !value.eq_ignore_ascii_case("internal") {
347                    report.error(format!("{key} = {value:?}: expected \"internal\" (or leave it out)"));
348                }
349            }
350            "RWS_CONFIG_TEMPLATE_DIR" => {
351                if !offline() && !value.is_empty() && !Path::new(value).is_dir() {
352                    report.warn(format!("{key} = {value:?}: directory not found"));
353                }
354            }
355            _ => {}
356        }
357    }
358
359    #[cfg(not(target_arch = "wasm32"))]
360    crate::admin::validate(&|name| get(name).map(str::to_string), report);
361
362    // TLS: both files or neither; loadable unless ACME will create them.
363    let acme_domains = get(Config::RWS_CONFIG_ACME_DOMAINS).unwrap_or("");
364    let acme = !acme_domains.is_empty();
365    let cert = get(Config::RWS_CONFIG_TLS_CERT_FILE).unwrap_or("");
366    let key = get(Config::RWS_CONFIG_TLS_KEY_FILE).unwrap_or("");
367    match (cert.is_empty(), key.is_empty()) {
368        (false, true) => report.error("tls_cert_file is set but tls_key_file is not"),
369        (true, false) => report.error("tls_key_file is set but tls_cert_file is not"),
370        (false, false) if !acme => check_tls_pair("tls_cert_file / tls_key_file", cert, key, report),
371        _ => {}
372    }
373    // spa_fallback names a file relative to the working directory; if it is
374    // missing, every client-side route except / 404s.
375    if let Some(fallback) = get(Config::RWS_CONFIG_SPA_FALLBACK).filter(|v| !v.is_empty()) {
376        if !offline() && !std::path::Path::new(fallback).is_file() {
377            report.warn(format!(
378                "spa_fallback = {fallback:?}: the file does not exist in the working directory, so every client-side route would 404"
379            ));
380        }
381    }
382
383    // spa_fallback_routes: "prefix=file" pairs; each file must exist, like spa_fallback's.
384    if let Some(routes) = get(Config::RWS_CONFIG_SPA_FALLBACK_ROUTES).filter(|v| !v.is_empty()) {
385        for entry in routes.split(',').map(str::trim).filter(|e| !e.is_empty()) {
386            match entry.split_once('=').map(|(p, f)| (p.trim(), f.trim())) {
387                Some((prefix, file)) if prefix.starts_with('/') && !file.is_empty() => {
388                    if !offline() && !std::path::Path::new(file).is_file() {
389                        report.warn(format!(
390                            "spa_fallback_routes: {file:?} for {prefix:?} does not exist in the working directory, so client-side routes under it would 404"
391                        ));
392                    }
393                }
394                _ => report.error(format!(
395                    "spa_fallback_routes: {entry:?} is not \"/prefix=file\" (the prefix starts with /, the file is a path relative to the working directory)"
396                )),
397            }
398        }
399    }
400
401    // [cors] allow_origins must match what the browser sends in Origin:
402    // scheme://host[:port], no trailing slash, no path.
403    if let Some(origins) = get(Config::RWS_CONFIG_CORS_ALLOW_ORIGINS) {
404        for origin in origins.split(',').map(str::trim).filter(|o| !o.is_empty()) {
405            if origin != "*" && !origin.starts_with("http://") && !origin.starts_with("https://") {
406                report.warn(format!(
407                    "[cors] allow_origins: '{origin}' does not look like scheme://host[:port]; a browser's Origin header never matches it"
408                ));
409            } else if origin != "*" && (origin.ends_with('/') || origin.rsplit_once("://").is_some_and(|(_, rest)| rest.contains('/'))) {
410                report.warn(format!(
411                    "[cors] allow_origins: '{origin}' has a path or trailing slash; Origin headers carry none, so it never matches"
412                ));
413            }
414        }
415    }
416
417    let mut seen_domains: Vec<&str> = Vec::new();
418    for i in 0.. {
419        let domain = get(&format!("RWS_CONFIG_VIRTUAL_HOST_{i}_DOMAIN"));
420        let cert = get(&format!("RWS_CONFIG_VIRTUAL_HOST_{i}_CERT_FILE"));
421        let key = get(&format!("RWS_CONFIG_VIRTUAL_HOST_{i}_KEY_FILE"));
422        if domain.is_none() && cert.is_none() && key.is_none() {
423            break;
424        }
425        let label = format!("[[virtual_host]] {}", domain.unwrap_or("(no domain)"));
426        match (domain, cert, key) {
427            (Some(d), Some(c), Some(k)) if !d.is_empty() => {
428                // Two entries with the same domain: only one certificate can
429                // win, so the loser is a silent misconfiguration.
430                if seen_domains.contains(&d) {
431                    report.error(format!(
432                        "{label}: a second [[virtual_host]] with the same domain; only one certificate can win"
433                    ));
434                } else {
435                    seen_domains.push(d);
436                }
437                check_tls_pair(&label, c, k, report)
438            }
439            _ => report.error(format!("{label}: needs domain, cert_file and key_file")),
440        }
441    }
442
443    if acme {
444        #[cfg(not(feature = "acme"))]
445        report.error("[acme] is configured, but this rws binary was built without the `acme` feature — no certificate would be requested");
446        if get(Config::RWS_CONFIG_ACME_EMAIL).unwrap_or("").is_empty() {
447            report.warn("[acme] has no email: the CA can't warn you about expiring or revoked certificates");
448        }
449        let challenge = get(Config::RWS_CONFIG_ACME_CHALLENGE).map(str::trim).filter(|v| !v.is_empty()).unwrap_or("http-01").to_ascii_lowercase();
450        if !matches!(challenge.as_str(), "http-01" | "tls-alpn-01" | "dns-01" | "dns-persist-01") {
451            report.error(format!("[acme] challenge = {challenge:?}: expected http-01, tls-alpn-01, dns-01 or dns-persist-01"));
452        }
453        for domain in acme_domains.split(',').map(str::trim) {
454            // A wildcard is one leading "*." label (RFC 8555 §7.1.3).
455            let (wildcard, name) = match domain.strip_prefix("*.") {
456                Some(rest) => (true, rest),
457                None => (false, domain),
458            };
459            if name.is_empty() || name.contains('*') || name.contains('/') || name.contains(':') || !name.contains('.') {
460                report.error(format!("[acme] domains: '{domain}' is not a domain name"));
461            } else if wildcard && !challenge.starts_with("dns-") {
462                report.error(format!("[acme] domains: the wildcard '{domain}' needs challenge = \"dns-01\" or \"dns-persist-01\""));
463            }
464        }
465        let port = get(Config::RWS_CONFIG_PORT).unwrap_or("7878");
466        let challenge_port = get(Config::RWS_CONFIG_ACME_CHALLENGE_PORT).unwrap_or("80");
467        let redirect_port = get(Config::RWS_CONFIG_HTTP_REDIRECT_PORT).unwrap_or("");
468        if challenge == "http-01" && redirect_port.is_empty() {
469            report.warn(format!(
470                "[acme] without http_redirect_port: nothing answers the HTTP-01 challenge on port {challenge_port}; set http_redirect_port = {challenge_port}"
471            ));
472        }
473        if challenge == "dns-01" {
474            check_acme_dns(&get, report);
475        }
476        if challenge == "dns-persist-01" && get(Config::RWS_CONFIG_ACME_DNS_PROVIDER).is_some_and(|p| !p.trim().is_empty()) {
477            report.warn("[acme] dns_provider is ignored with dns-persist-01: you publish its record once yourself (rws prints it)");
478        }
479        let on_demand = get(Config::RWS_CONFIG_ACME_ON_DEMAND).unwrap_or("").trim().to_ascii_lowercase();
480        if !matches!(on_demand.as_str(), "" | "true" | "false") {
481            report.error(format!("[acme] on_demand = {on_demand:?}: expected true or false"));
482        } else if on_demand == "true" {
483            match get(Config::RWS_CONFIG_ACME_ON_DEMAND_ASK).map(str::trim).filter(|v| !v.is_empty()) {
484                None => report.error("[acme] on_demand needs on_demand_ask: without it anyone could make rws order certificates for any name pointed at it"),
485                Some(ask) if !(ask.starts_with("http://") || ask.starts_with("https://")) => {
486                    report.error(format!("[acme] on_demand_ask = {ask:?}: expected an http:// or https:// URL"))
487                }
488                Some(_) => {}
489            }
490            if challenge.starts_with("dns-") {
491                report.error(format!("[acme] on_demand works with http-01 and tls-alpn-01, not {challenge} (it would need every customer's DNS zone)"));
492            }
493        }
494        if port != "443" {
495            report.warn(format!("[acme] with port = {port}: browsers expect HTTPS on 443 (fine if a port mapping forwards 443 here)"));
496        }
497    }
498}
499
500/// `dns_api_url`, when set: an http(s) URL.
501fn check_api_url(url: Option<&str>, report: &mut ConfigReport) {
502    if let Some(url) = url.filter(|u| !(u.starts_with("https://") || u.starts_with("http://"))) {
503        report.error(format!("[acme] dns_api_url = {url:?}: expected an http:// or https:// URL"));
504    }
505}
506
507/// `[acme] challenge = "dns-01"`: a provider and what it needs.
508fn check_acme_dns<'a>(get: &dyn Fn(&str) -> Option<&'a str>, report: &mut ConfigReport) {
509    let set = |name: &str| get(name).map(str::trim).filter(|v| !v.is_empty());
510    match set(Config::RWS_CONFIG_ACME_DNS_PROVIDER).map(str::to_ascii_lowercase).as_deref() {
511        Some("rfc2136") => {
512            match set(Config::RWS_CONFIG_ACME_DNS_SERVER) {
513                None => report.error("[acme] dns_provider = \"rfc2136\" needs dns_server (the primary DNS server, host[:port])"),
514                Some(server) if server.contains('/') || server.is_empty() => report.error(format!("[acme] dns_server = {server:?}: expected host[:port]")),
515                Some(_) => {}
516            }
517            match (set(Config::RWS_CONFIG_ACME_DNS_TSIG_KEY), set(Config::RWS_CONFIG_ACME_DNS_TSIG_SECRET)) {
518                (Some(_), None) | (None, Some(_)) => report.error("[acme] dns_tsig_key and dns_tsig_secret go together"),
519                (None, None) => report.warn("[acme] rfc2136 without a TSIG key: the server must accept unsigned updates from this host"),
520                (Some(_), Some(secret)) => {
521                    #[cfg(feature = "acme")]
522                    if crate::acme::base64_secret(secret).is_none() {
523                        report.error("[acme] dns_tsig_secret is not base64");
524                    }
525                    #[cfg(not(feature = "acme"))]
526                    let _ = secret;
527                }
528            }
529            if let Some(algorithm) = set(Config::RWS_CONFIG_ACME_DNS_TSIG_ALGORITHM) {
530                if !matches!(algorithm.to_ascii_lowercase().as_str(), "hmac-sha256" | "hmac-sha512") {
531                    report.error(format!("[acme] dns_tsig_algorithm = {algorithm:?}: expected hmac-sha256 or hmac-sha512"));
532                }
533            }
534        }
535        Some("exec") => match set(Config::RWS_CONFIG_ACME_DNS_EXEC) {
536            None => report.error("[acme] dns_provider = \"exec\" needs dns_exec (the program)"),
537            Some(program) if !offline() && !Path::new(program).is_file() => report.error(format!("[acme] dns_exec = {program:?}: file not found")),
538            Some(_) => {}
539        },
540        Some("cloudflare") => {
541            // Usually kept out of the file, in the environment.
542            let in_env = offline() || std::env::var(Config::RWS_CONFIG_ACME_DNS_API_TOKEN).is_ok_and(|v| !v.trim().is_empty());
543            if set(Config::RWS_CONFIG_ACME_DNS_API_TOKEN).is_none() && !in_env {
544                report.error("[acme] dns_provider = \"cloudflare\" needs dns_api_token (an API token with DNS edit permission; or RWS_CONFIG_ACME_DNS_API_TOKEN)");
545            }
546            check_api_url(set(Config::RWS_CONFIG_ACME_DNS_API_URL), report);
547        }
548        Some("route53") => {
549            let aws = |name: &str| offline() || std::env::var(name).is_ok_and(|v| !v.trim().is_empty());
550            if !(aws("AWS_ACCESS_KEY_ID") && aws("AWS_SECRET_ACCESS_KEY")) {
551                report.warn("[acme] dns_provider = \"route53\" reads AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY from the environment, and they aren't set here");
552            }
553            check_api_url(set(Config::RWS_CONFIG_ACME_DNS_API_URL), report);
554        }
555        Some(other) => report.error(format!("[acme] dns_provider = {other:?}: expected rfc2136, cloudflare, route53 or exec")),
556        None => report.error("[acme] challenge = \"dns-01\" needs dns_provider (rfc2136, cloudflare, route53 or exec)"),
557    }
558    if let Some(secs) = set(Config::RWS_CONFIG_ACME_DNS_PROPAGATION_SECS) {
559        if secs.parse::<u64>().is_err() {
560            report.error(format!("[acme] dns_propagation_secs = {secs:?}: not a whole number"));
561        }
562    }
563}
564
565/// `RWS_CONFIG_CORS_ALLOW_ALL` → `cors_allow_all`, for messages.
566fn setting_key(env_name: &str) -> String {
567    env_name.trim_start_matches("RWS_CONFIG_").to_ascii_lowercase()
568}
569
570fn check_tls_pair(label: &str, cert: &str, key: &str, report: &mut ConfigReport) {
571    if offline() {
572        return;
573    }
574    let mut missing = false;
575    let token_key = key.trim_start().get(..7).is_some_and(|p| p.eq_ignore_ascii_case("pkcs11:"));
576    for (what, path) in [("certificate", cert), ("key", key)] {
577        if what == "key" && token_key {
578            continue;
579        }
580        if !Path::new(path).is_file() {
581            report.error(format!("{label}: {what} file '{path}' not found"));
582            missing = true;
583        }
584    }
585    if missing {
586        return;
587    }
588    #[cfg(all(feature = "http2", not(target_arch = "wasm32")))]
589    if let Err(e) = crate::tls::create_tls_acceptor(cert, key) {
590        report.error(format!("{label}: {e}"));
591    }
592    #[cfg(not(feature = "http2"))]
593    report.warn(format!("{label}: this build has no TLS support (`http1` only), so the certificate is not used"));
594}