Skip to main content

rust_web_server/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;
17
18use std::io::Cursor;
19use std::path::Path;
20
21use crate::entry_point::config_file::collect_settings;
22use crate::entry_point::Config;
23
24/// Errors and warnings found in a configuration file.
25#[derive(Debug, Default, Clone, PartialEq)]
26pub struct ConfigReport {
27    /// Mistakes: the configuration does not do what it says.
28    pub errors: Vec<String>,
29    /// Likely mistakes that don't stop the server working.
30    pub warnings: Vec<String>,
31}
32
33impl ConfigReport {
34    pub fn error(&mut self, message: impl Into<String>) {
35        self.errors.push(message.into());
36    }
37
38    pub fn warn(&mut self, message: impl Into<String>) {
39        self.warnings.push(message.into());
40    }
41
42    /// `true` when there are no errors (warnings are allowed).
43    pub fn is_ok(&self) -> bool {
44        self.errors.is_empty()
45    }
46
47    /// One JSON object: `{"path":…,"ok":…,"errors":[…],"warnings":[…]}`.
48    /// Strings are escaped; exit codes stay with the caller.
49    pub fn render_json(&self, path: &str) -> String {
50        fn escaped(s: &str) -> String {
51            let mut out = String::with_capacity(s.len() + 2);
52            for c in s.chars() {
53                match c {
54                    '"' => out.push_str("\\\""),
55                    '\\' => out.push_str("\\\\"),
56                    '\n' => out.push_str("\\n"),
57                    '\r' => out.push_str("\\r"),
58                    '\t' => out.push_str("\\t"),
59                    c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
60                    c => out.push(c),
61                }
62            }
63            out
64        }
65        let list = |items: &[String]| {
66            let inner: Vec<String> = items.iter().map(|i| format!("\"{}\"", escaped(i))).collect();
67            format!("[{}]", inner.join(","))
68        };
69        format!(
70            "{{\"path\":\"{}\",\"ok\":{},\"errors\":{},\"warnings\":{}}}",
71            escaped(path),
72            self.is_ok(),
73            list(&self.errors),
74            list(&self.warnings),
75        )
76    }
77
78    /// Human-readable report, one finding per line, ending in a verdict.
79    pub fn render(&self, path: &str) -> String {
80        let mut out = String::new();
81        for e in &self.errors {
82            out.push_str(&format!("error: {e}\n"));
83        }
84        for w in &self.warnings {
85            out.push_str(&format!("warning: {w}\n"));
86        }
87        if self.is_ok() {
88            out.push_str(&format!("{path}: configuration OK"));
89            if !self.warnings.is_empty() {
90                out.push_str(&format!(" ({} warning{})", self.warnings.len(), plural(self.warnings.len())));
91            }
92        } else {
93            out.push_str(&format!(
94                "{path}: {} error{}, {} warning{}",
95                self.errors.len(), plural(self.errors.len()),
96                self.warnings.len(), plural(self.warnings.len()),
97            ));
98        }
99        out.push('\n');
100        out
101    }
102}
103
104fn plural(n: usize) -> &'static str {
105    if n == 1 { "" } else { "s" }
106}
107
108/// The path `--check` targets in `args` (the process arguments), or `None`
109/// when `--check` is absent. `--check=<path>` and `--check <path>` name a
110/// file; a bare `--check` checks the file the server would load.
111pub fn check_target_from_args(args: &[String]) -> Option<String> {
112    let mut iter = args.iter().skip(1).peekable();
113    while let Some(arg) = iter.next() {
114        if let Some(path) = arg.strip_prefix("--check=") {
115            return Some(path.to_string());
116        }
117        if arg == "--check" {
118            return Some(match iter.peek() {
119                Some(next) if !next.starts_with('-') => next.to_string(),
120                _ => default_config_path(),
121            });
122        }
123    }
124    None
125}
126
127/// Whether the arguments ask for machine-readable output (`--format=json`).
128pub fn wants_json_output(args: &[String]) -> bool {
129    args.iter().any(|a| a == "--format=json")
130}
131
132/// `RWS_CONFIG_FILE` if set, else `rws.config.toml` in the working directory.
133pub fn default_config_path() -> String {
134    std::env::var("RWS_CONFIG_FILE")
135        .ok()
136        .filter(|p| !p.trim().is_empty())
137        .unwrap_or_else(|| "rws.config.toml".to_string())
138}
139
140/// Check the configuration file at `path`.
141pub fn check_file(path: &str) -> ConfigReport {
142    match std::fs::read_to_string(path) {
143        Ok(content) => check_str(&content),
144        Err(e) => {
145            let mut report = ConfigReport::default();
146            report.error(format!("cannot read {path}: {e}"));
147            report
148        }
149    }
150}
151
152/// Check configuration text. Relative file paths in it (certificates,
153/// htpasswd files, static roots) are resolved against the working directory,
154/// as the server resolves them.
155pub fn check_str(content: &str) -> ConfigReport {
156    let mut report = ConfigReport::default();
157    if content.contains('\0') {
158        report.error("the file contains a NUL byte");
159        return report;
160    }
161
162    match collect_settings(Cursor::new(content.as_bytes()), String::new()) {
163        Ok(resolved) => {
164            for key in &resolved.unknown {
165                report.error(format!("unknown setting '{key}' — ignored"));
166            }
167            check_settings(&resolved.settings, &mut report);
168        }
169        Err(e) => report.error(format!("unable to parse: {e}")),
170    }
171
172    #[cfg(not(target_arch = "wasm32"))]
173    if content.contains("[[route]]") || content.contains("[[upstream]]")
174        || content.contains("[[tcp_proxy]]") || content.contains("[[udp_proxy]]") || content.contains("[[ws_proxy]]")
175    {
176        crate::proxy_config::validate::check_unknown_keys(content, &mut report);
177        crate::proxy_config::ProxyConfig::from_str(content).validate(&mut report);
178    } else if content.lines().any(|l| l.trim().starts_with("[middleware")) {
179        report.warn("[middleware] only applies in proxy mode (a file with [[route]] or [[upstream]] sections)");
180    }
181
182    report
183}
184
185/// Type and consistency checks for the `RWS_CONFIG_*` settings in the file.
186fn check_settings(settings: &[(String, String)], report: &mut ConfigReport) {
187    let get = |name: &str| settings.iter().rev().find(|(n, _)| n == name).map(|(_, v)| v.trim());
188
189    for (name, value) in settings {
190        let value = value.trim();
191        let key = setting_key(name);
192        match name.as_str() {
193            Config::RWS_CONFIG_PORT | Config::RWS_CONFIG_HTTP_REDIRECT_PORT | Config::RWS_CONFIG_ACME_CHALLENGE_PORT => {
194                if !(name == Config::RWS_CONFIG_HTTP_REDIRECT_PORT && value.is_empty())
195                    && !value.parse::<u16>().is_ok_and(|p| p > 0)
196                {
197                    report.error(format!("{key} = {value:?}: not a port number (1-65535)"));
198                }
199            }
200            Config::RWS_CONFIG_IP => {
201                if value.parse::<std::net::IpAddr>().is_err() {
202                    report.error(format!("{key} = {value:?}: not an IP address (use 0.0.0.0 or :: for all interfaces)"));
203                }
204            }
205            Config::RWS_CONFIG_THREAD_COUNT => {
206                if !value.parse::<usize>().is_ok_and(|n| n > 0) {
207                    report.error(format!("{key} = {value:?}: not a positive number"));
208                }
209            }
210            Config::RWS_CONFIG_REQUEST_ALLOCATION_SIZE_IN_BYTES => {
211                if !value.parse::<u64>().is_ok_and(|n| n > 0) {
212                    report.error(format!("{key} = {value:?}: not a positive number"));
213                }
214            }
215            "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"
216            | "RWS_CONFIG_ACME_RENEW_BEFORE_DAYS" | "RWS_CONFIG_ACME_RENEW_CHECK_INTERVAL_SECS"
217            | "RWS_CONFIG_CIRCUIT_BREAKER_FAILURE_THRESHOLD" | "RWS_CONFIG_CIRCUIT_BREAKER_MAX_HALF_OPEN_PROBES"
218            | "RWS_CONFIG_CIRCUIT_BREAKER_RECOVERY_SECS" | Config::RWS_CONFIG_CORS_MAX_AGE => {
219                if value.parse::<u64>().is_err() {
220                    report.error(format!("{key} = {value:?}: not a whole number"));
221                }
222            }
223            Config::RWS_CONFIG_CORS_ALLOW_ALL | Config::RWS_CONFIG_CORS_ALLOW_CREDENTIALS | Config::RWS_CONFIG_ACME_STAGING
224            | "RWS_CONFIG_CLIENT_HINTS" | "RWS_CONFIG_OPEN_FILE_CACHE_STRICT"
225            | "RWS_CONFIG_SECURITY_HEADERS" | "RWS_CONFIG_NANOS_HEADERS" | "RWS_CONFIG_SERVE_DOTFILES" => {
226                if !matches!(value.to_ascii_lowercase().as_str(), "true" | "false") {
227                    report.error(format!("{key} = {value:?}: expected true or false"));
228                }
229            }
230            "RWS_CONFIG_RUNTIME" => {
231                if !matches!(value.to_ascii_lowercase().as_str(), "shared" | "per-core") {
232                    report.error(format!("{key} = {value:?}: expected \"shared\" or \"per-core\""));
233                }
234            }
235            "RWS_CONFIG_LOG_FORMAT" => {
236                if !matches!(value.to_ascii_lowercase().as_str(), "combined" | "json" | "off" | "none") {
237                    report.error(format!("{key} = {value:?}: expected \"combined\", \"json\" or \"off\""));
238                }
239            }
240            "RWS_CONFIG_TLS_CLIENT_CA_FILE" | Config::RWS_CONFIG_ACME_CA_FILE => {
241                if !value.is_empty() && !Path::new(value).is_file() {
242                    report.error(format!("{key} = {value:?}: file not found"));
243                }
244            }
245            "RWS_CONFIG_TEMPLATE_DIR" => {
246                if !value.is_empty() && !Path::new(value).is_dir() {
247                    report.warn(format!("{key} = {value:?}: directory not found"));
248                }
249            }
250            _ => {}
251        }
252    }
253
254    // TLS: both files or neither; loadable unless ACME will create them.
255    let acme_domains = get(Config::RWS_CONFIG_ACME_DOMAINS).unwrap_or("");
256    let acme = !acme_domains.is_empty();
257    let cert = get(Config::RWS_CONFIG_TLS_CERT_FILE).unwrap_or("");
258    let key = get(Config::RWS_CONFIG_TLS_KEY_FILE).unwrap_or("");
259    match (cert.is_empty(), key.is_empty()) {
260        (false, true) => report.error("tls_cert_file is set but tls_key_file is not"),
261        (true, false) => report.error("tls_key_file is set but tls_cert_file is not"),
262        (false, false) if !acme => check_tls_pair("tls_cert_file / tls_key_file", cert, key, report),
263        _ => {}
264    }
265    // spa_fallback names a file relative to the working directory; if it is
266    // missing, every client-side route except / 404s.
267    if let Some(fallback) = get(Config::RWS_CONFIG_SPA_FALLBACK).filter(|v| !v.is_empty()) {
268        if !std::path::Path::new(fallback).is_file() {
269            report.warn(format!(
270                "spa_fallback = {fallback:?}: the file does not exist in the working directory, so every client-side route would 404"
271            ));
272        }
273    }
274
275    // [cors] allow_origins must match what the browser sends in Origin:
276    // scheme://host[:port], no trailing slash, no path.
277    if let Some(origins) = get(Config::RWS_CONFIG_CORS_ALLOW_ORIGINS) {
278        for origin in origins.split(',').map(str::trim).filter(|o| !o.is_empty()) {
279            if origin != "*" && !origin.starts_with("http://") && !origin.starts_with("https://") {
280                report.warn(format!(
281                    "[cors] allow_origins: '{origin}' does not look like scheme://host[:port]; a browser's Origin header never matches it"
282                ));
283            } else if origin != "*" && (origin.ends_with('/') || origin.rsplit_once("://").is_some_and(|(_, rest)| rest.contains('/'))) {
284                report.warn(format!(
285                    "[cors] allow_origins: '{origin}' has a path or trailing slash; Origin headers carry none, so it never matches"
286                ));
287            }
288        }
289    }
290
291    let mut seen_domains: Vec<&str> = Vec::new();
292    for i in 0.. {
293        let domain = get(&format!("RWS_CONFIG_VIRTUAL_HOST_{i}_DOMAIN"));
294        let cert = get(&format!("RWS_CONFIG_VIRTUAL_HOST_{i}_CERT_FILE"));
295        let key = get(&format!("RWS_CONFIG_VIRTUAL_HOST_{i}_KEY_FILE"));
296        if domain.is_none() && cert.is_none() && key.is_none() {
297            break;
298        }
299        let label = format!("[[virtual_host]] {}", domain.unwrap_or("(no domain)"));
300        match (domain, cert, key) {
301            (Some(d), Some(c), Some(k)) if !d.is_empty() => {
302                // Two entries with the same domain: only one certificate can
303                // win, so the loser is a silent misconfiguration.
304                if seen_domains.contains(&d) {
305                    report.error(format!(
306                        "{label}: a second [[virtual_host]] with the same domain; only one certificate can win"
307                    ));
308                } else {
309                    seen_domains.push(d);
310                }
311                check_tls_pair(&label, c, k, report)
312            }
313            _ => report.error(format!("{label}: needs domain, cert_file and key_file")),
314        }
315    }
316
317    if acme {
318        #[cfg(not(feature = "acme"))]
319        report.error("[acme] is configured, but this rws binary was built without the `acme` feature — no certificate would be requested");
320        if get(Config::RWS_CONFIG_ACME_EMAIL).unwrap_or("").is_empty() {
321            report.warn("[acme] has no email: the CA can't warn you about expiring or revoked certificates");
322        }
323        for domain in acme_domains.split(',').map(str::trim) {
324            if domain.is_empty() || domain.contains('*') || domain.contains('/') || domain.contains(':') || !domain.contains('.') {
325                report.error(format!("[acme] domains: '{domain}' is not a domain name (wildcards need DNS-01, which rws doesn't do)"));
326            }
327        }
328        let port = get(Config::RWS_CONFIG_PORT).unwrap_or("7878");
329        let challenge_port = get(Config::RWS_CONFIG_ACME_CHALLENGE_PORT).unwrap_or("80");
330        let redirect_port = get(Config::RWS_CONFIG_HTTP_REDIRECT_PORT).unwrap_or("");
331        if redirect_port.is_empty() {
332            report.warn(format!(
333                "[acme] without http_redirect_port: nothing answers the HTTP-01 challenge on port {challenge_port}; set http_redirect_port = {challenge_port}"
334            ));
335        }
336        if port != "443" {
337            report.warn(format!("[acme] with port = {port}: browsers expect HTTPS on 443 (fine if a port mapping forwards 443 here)"));
338        }
339    }
340}
341
342/// `RWS_CONFIG_CORS_ALLOW_ALL` → `cors_allow_all`, for messages.
343fn setting_key(env_name: &str) -> String {
344    env_name.trim_start_matches("RWS_CONFIG_").to_ascii_lowercase()
345}
346
347fn check_tls_pair(label: &str, cert: &str, key: &str, report: &mut ConfigReport) {
348    let mut missing = false;
349    for (what, path) in [("certificate", cert), ("key", key)] {
350        if !Path::new(path).is_file() {
351            report.error(format!("{label}: {what} file '{path}' not found"));
352            missing = true;
353        }
354    }
355    if missing {
356        return;
357    }
358    #[cfg(all(feature = "http2", not(target_arch = "wasm32")))]
359    if let Err(e) = crate::tls::create_tls_acceptor(cert, key) {
360        report.error(format!("{label}: {e}"));
361    }
362    #[cfg(not(feature = "http2"))]
363    report.warn(format!("{label}: this build has no TLS support (`http1` only), so the certificate is not used"));
364}