rust-web-server 18.9.1

Single-binary web server and reverse proxy: automatic HTTPS (Let's Encrypt), HTTP/1.1, HTTP/2 and HTTP/3, load balancing, auth and rate limiting, configured in one TOML file. Also a Rust library: routing, middleware, MCP server, ORM, background jobs. No hyper, no Tower; HTTP/2 and HTTP/3 framing via h2 and quinn.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! `rws --check`: validate `rws.config.toml` without starting the server —
//! the counterpart of `nginx -t` / `caddy validate`.
//!
//! Reports unknown keys (in settings and in proxy sections), values of the
//! wrong type, TLS files that can't be loaded, proxy routes pointing at
//! undeclared upstreams, auth secrets that aren't set, and similar mistakes
//! that would otherwise surface as a warning in the startup log or as a 503
//! at request time. Nothing is bound and the environment is not modified.
//!
//! ```bash
//! rws --check                      # the file rws would load (RWS_CONFIG_FILE or ./rws.config.toml)
//! rws --check=/etc/rws/site.toml   # a specific file
//! ```

#[cfg(test)]
mod tests;

use std::io::Cursor;
use std::path::Path;

use crate::entry_point::config_file::collect_settings;
use crate::entry_point::Config;

/// Errors and warnings found in a configuration file.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct ConfigReport {
    /// Mistakes: the configuration does not do what it says.
    pub errors: Vec<String>,
    /// Likely mistakes that don't stop the server working.
    pub warnings: Vec<String>,
}

impl ConfigReport {
    pub fn error(&mut self, message: impl Into<String>) {
        self.errors.push(message.into());
    }

    pub fn warn(&mut self, message: impl Into<String>) {
        self.warnings.push(message.into());
    }

    /// `true` when there are no errors (warnings are allowed).
    pub fn is_ok(&self) -> bool {
        self.errors.is_empty()
    }

    /// One JSON object: `{"path":…,"ok":…,"errors":[…],"warnings":[…]}`.
    /// Strings are escaped; exit codes stay with the caller.
    pub fn render_json(&self, path: &str) -> String {
        fn escaped(s: &str) -> String {
            let mut out = String::with_capacity(s.len() + 2);
            for c in s.chars() {
                match c {
                    '"' => out.push_str("\\\""),
                    '\\' => out.push_str("\\\\"),
                    '\n' => out.push_str("\\n"),
                    '\r' => out.push_str("\\r"),
                    '\t' => out.push_str("\\t"),
                    c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
                    c => out.push(c),
                }
            }
            out
        }
        let list = |items: &[String]| {
            let inner: Vec<String> = items.iter().map(|i| format!("\"{}\"", escaped(i))).collect();
            format!("[{}]", inner.join(","))
        };
        format!(
            "{{\"path\":\"{}\",\"ok\":{},\"errors\":{},\"warnings\":{}}}",
            escaped(path),
            self.is_ok(),
            list(&self.errors),
            list(&self.warnings),
        )
    }

    /// Human-readable report, one finding per line, ending in a verdict.
    pub fn render(&self, path: &str) -> String {
        let mut out = String::new();
        for e in &self.errors {
            out.push_str(&format!("error: {e}\n"));
        }
        for w in &self.warnings {
            out.push_str(&format!("warning: {w}\n"));
        }
        if self.is_ok() {
            out.push_str(&format!("{path}: configuration OK"));
            if !self.warnings.is_empty() {
                out.push_str(&format!(" ({} warning{})", self.warnings.len(), plural(self.warnings.len())));
            }
        } else {
            out.push_str(&format!(
                "{path}: {} error{}, {} warning{}",
                self.errors.len(), plural(self.errors.len()),
                self.warnings.len(), plural(self.warnings.len()),
            ));
        }
        out.push('\n');
        out
    }
}

fn plural(n: usize) -> &'static str {
    if n == 1 { "" } else { "s" }
}

/// The path `--check` targets in `args` (the process arguments), or `None`
/// when `--check` is absent. `--check=<path>` and `--check <path>` name a
/// file; a bare `--check` checks the file the server would load.
pub fn check_target_from_args(args: &[String]) -> Option<String> {
    let mut iter = args.iter().skip(1).peekable();
    while let Some(arg) = iter.next() {
        if let Some(path) = arg.strip_prefix("--check=") {
            return Some(path.to_string());
        }
        if arg == "--check" {
            return Some(match iter.peek() {
                Some(next) if !next.starts_with('-') => next.to_string(),
                _ => default_config_path(),
            });
        }
    }
    None
}

/// Whether the arguments ask for machine-readable output (`--format=json`).
pub fn wants_json_output(args: &[String]) -> bool {
    args.iter().any(|a| a == "--format=json")
}

/// `RWS_CONFIG_FILE` if set, else `rws.config.toml` in the working directory.
pub fn default_config_path() -> String {
    std::env::var("RWS_CONFIG_FILE")
        .ok()
        .filter(|p| !p.trim().is_empty())
        .unwrap_or_else(|| "rws.config.toml".to_string())
}

/// Check the configuration file at `path`.
pub fn check_file(path: &str) -> ConfigReport {
    match std::fs::read_to_string(path) {
        Ok(content) => check_str(&content),
        Err(e) => {
            let mut report = ConfigReport::default();
            report.error(format!("cannot read {path}: {e}"));
            report
        }
    }
}

thread_local! {
    static OFFLINE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// `true` inside [`check_str_offline`]: checks that would read this
/// machine's files or environment are skipped.
pub(crate) fn offline() -> bool {
    OFFLINE.with(|o| o.get())
}

/// [`check_str`] without looking at this machine: no file is opened or
/// tested for existence (certificates, keys, CA bundles, htpasswd files,
/// static roots, programs) and no environment variable is read (auth
/// secrets, DNS API credentials). For configuration text from someone else,
/// e.g. the docs MCP server's `check_config` tool, where those answers would
/// describe the server, not the caller's deployment.
pub fn check_str_offline(content: &str) -> ConfigReport {
    struct Reset;
    impl Drop for Reset {
        fn drop(&mut self) {
            OFFLINE.with(|o| o.set(false));
        }
    }
    OFFLINE.with(|o| o.set(true));
    let _reset = Reset;
    check_str(content)
}

/// Check configuration text. Relative file paths in it (certificates,
/// htpasswd files, static roots) are resolved against the working directory,
/// as the server resolves them.
pub fn check_str(content: &str) -> ConfigReport {
    let mut report = ConfigReport::default();
    if content.contains('\0') {
        report.error("the file contains a NUL byte");
        return report;
    }

    match collect_settings(Cursor::new(content.as_bytes()), String::new()) {
        Ok(resolved) => {
            for key in &resolved.unknown {
                report.error(format!("unknown setting '{key}' — ignored"));
            }
            check_settings(&resolved.settings, &mut report);
        }
        Err(e) => report.error(format!("unable to parse: {e}")),
    }

    #[cfg(not(target_arch = "wasm32"))]
    if content.contains("[[route]]") || content.contains("[[upstream]]")
        || content.contains("[[tcp_proxy]]") || content.contains("[[udp_proxy]]") || content.contains("[[ws_proxy]]")
    {
        crate::proxy_config::validate::check_unknown_keys(content, &mut report);
        crate::proxy_config::ProxyConfig::from_str(content).validate(&mut report);
    } else if content.lines().any(|l| l.trim().starts_with("[middleware")) {
        report.warn("[middleware] only applies in proxy mode (a file with [[route]] or [[upstream]] sections)");
    }

    report
}

/// Type and consistency checks for the `RWS_CONFIG_*` settings in the file.
fn check_settings(settings: &[(String, String)], report: &mut ConfigReport) {
    let get = |name: &str| settings.iter().rev().find(|(n, _)| n == name).map(|(_, v)| v.trim());

    for (name, value) in settings {
        let value = value.trim();
        let key = setting_key(name);
        match name.as_str() {
            Config::RWS_CONFIG_PORT | Config::RWS_CONFIG_HTTP_REDIRECT_PORT | Config::RWS_CONFIG_ACME_CHALLENGE_PORT => {
                if !(name == Config::RWS_CONFIG_HTTP_REDIRECT_PORT && value.is_empty())
                    && !value.parse::<u16>().is_ok_and(|p| p > 0)
                {
                    report.error(format!("{key} = {value:?}: not a port number (1-65535)"));
                }
            }
            Config::RWS_CONFIG_IP => {
                if value.parse::<std::net::IpAddr>().is_err() {
                    report.error(format!("{key} = {value:?}: not an IP address (use 0.0.0.0 or :: for all interfaces)"));
                }
            }
            Config::RWS_CONFIG_THREAD_COUNT => {
                if !value.parse::<usize>().is_ok_and(|n| n > 0) {
                    report.error(format!("{key} = {value:?}: not a positive number"));
                }
            }
            Config::RWS_CONFIG_REQUEST_ALLOCATION_SIZE_IN_BYTES => {
                if !value.parse::<u64>().is_ok_and(|n| n > 0) {
                    report.error(format!("{key} = {value:?}: not a positive number"));
                }
            }
            "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"
            | "RWS_CONFIG_ACME_RENEW_BEFORE_DAYS" | "RWS_CONFIG_ACME_RENEW_CHECK_INTERVAL_SECS"
            | "RWS_CONFIG_CIRCUIT_BREAKER_FAILURE_THRESHOLD" | "RWS_CONFIG_CIRCUIT_BREAKER_MAX_HALF_OPEN_PROBES"
            | "RWS_CONFIG_CIRCUIT_BREAKER_RECOVERY_SECS" | Config::RWS_CONFIG_CORS_MAX_AGE => {
                if value.parse::<u64>().is_err() {
                    report.error(format!("{key} = {value:?}: not a whole number"));
                }
            }
            Config::RWS_CONFIG_CORS_ALLOW_ALL | Config::RWS_CONFIG_CORS_ALLOW_CREDENTIALS | Config::RWS_CONFIG_ACME_STAGING
            | "RWS_CONFIG_CLIENT_HINTS" | "RWS_CONFIG_OPEN_FILE_CACHE_STRICT"
            | "RWS_CONFIG_SECURITY_HEADERS" | "RWS_CONFIG_NANOS_HEADERS" | "RWS_CONFIG_SERVE_DOTFILES" | "RWS_CONFIG_WATCH"
            | "RWS_CONFIG_PROXY_PROTOCOL" | "RWS_CONFIG_GATEWAY_API_ENABLED" => {
                if !matches!(value.to_ascii_lowercase().as_str(), "true" | "false") {
                    report.error(format!("{key} = {value:?}: expected true or false"));
                }
            }
            "RWS_CONFIG_GATEWAY_API_MODE" => {
                if !matches!(value.to_ascii_lowercase().as_str(), "shared" | "provisioned") {
                    report.error(format!("{key} = {value:?}: expected shared or provisioned"));
                }
            }
            "RWS_CONFIG_ACCESS_LOG_MAX_SIZE" | "RWS_CONFIG_ACCESS_LOG_KEEP" => {
                if crate::log::access_sink::parse_size(value).is_none() {
                    report.error(format!("{key} = {value:?}: expected a number of bytes or files (e.g. 104857600 or 100M)"));
                }
            }
            "RWS_CONFIG_RUNTIME" => {
                if !matches!(value.to_ascii_lowercase().as_str(), "shared" | "per-core") {
                    report.error(format!("{key} = {value:?}: expected \"shared\" or \"per-core\""));
                }
            }
            "RWS_CONFIG_LOG_FORMAT" => {
                if !matches!(value.to_ascii_lowercase().as_str(), "combined" | "json" | "off" | "none") {
                    report.error(format!("{key} = {value:?}: expected \"combined\", \"json\" or \"off\""));
                }
            }
            "RWS_CONFIG_TLS_CLIENT_CA_FILE" | Config::RWS_CONFIG_ACME_CA_FILE => {
                if !offline() && !value.is_empty() && !Path::new(value).is_file() {
                    report.error(format!("{key} = {value:?}: file not found"));
                }
            }
            "RWS_CONFIG_TEMPLATE_DIR" => {
                if !offline() && !value.is_empty() && !Path::new(value).is_dir() {
                    report.warn(format!("{key} = {value:?}: directory not found"));
                }
            }
            _ => {}
        }
    }

    // TLS: both files or neither; loadable unless ACME will create them.
    let acme_domains = get(Config::RWS_CONFIG_ACME_DOMAINS).unwrap_or("");
    let acme = !acme_domains.is_empty();
    let cert = get(Config::RWS_CONFIG_TLS_CERT_FILE).unwrap_or("");
    let key = get(Config::RWS_CONFIG_TLS_KEY_FILE).unwrap_or("");
    match (cert.is_empty(), key.is_empty()) {
        (false, true) => report.error("tls_cert_file is set but tls_key_file is not"),
        (true, false) => report.error("tls_key_file is set but tls_cert_file is not"),
        (false, false) if !acme => check_tls_pair("tls_cert_file / tls_key_file", cert, key, report),
        _ => {}
    }
    // spa_fallback names a file relative to the working directory; if it is
    // missing, every client-side route except / 404s.
    if let Some(fallback) = get(Config::RWS_CONFIG_SPA_FALLBACK).filter(|v| !v.is_empty()) {
        if !offline() && !std::path::Path::new(fallback).is_file() {
            report.warn(format!(
                "spa_fallback = {fallback:?}: the file does not exist in the working directory, so every client-side route would 404"
            ));
        }
    }

    // [cors] allow_origins must match what the browser sends in Origin:
    // scheme://host[:port], no trailing slash, no path.
    if let Some(origins) = get(Config::RWS_CONFIG_CORS_ALLOW_ORIGINS) {
        for origin in origins.split(',').map(str::trim).filter(|o| !o.is_empty()) {
            if origin != "*" && !origin.starts_with("http://") && !origin.starts_with("https://") {
                report.warn(format!(
                    "[cors] allow_origins: '{origin}' does not look like scheme://host[:port]; a browser's Origin header never matches it"
                ));
            } else if origin != "*" && (origin.ends_with('/') || origin.rsplit_once("://").is_some_and(|(_, rest)| rest.contains('/'))) {
                report.warn(format!(
                    "[cors] allow_origins: '{origin}' has a path or trailing slash; Origin headers carry none, so it never matches"
                ));
            }
        }
    }

    let mut seen_domains: Vec<&str> = Vec::new();
    for i in 0.. {
        let domain = get(&format!("RWS_CONFIG_VIRTUAL_HOST_{i}_DOMAIN"));
        let cert = get(&format!("RWS_CONFIG_VIRTUAL_HOST_{i}_CERT_FILE"));
        let key = get(&format!("RWS_CONFIG_VIRTUAL_HOST_{i}_KEY_FILE"));
        if domain.is_none() && cert.is_none() && key.is_none() {
            break;
        }
        let label = format!("[[virtual_host]] {}", domain.unwrap_or("(no domain)"));
        match (domain, cert, key) {
            (Some(d), Some(c), Some(k)) if !d.is_empty() => {
                // Two entries with the same domain: only one certificate can
                // win, so the loser is a silent misconfiguration.
                if seen_domains.contains(&d) {
                    report.error(format!(
                        "{label}: a second [[virtual_host]] with the same domain; only one certificate can win"
                    ));
                } else {
                    seen_domains.push(d);
                }
                check_tls_pair(&label, c, k, report)
            }
            _ => report.error(format!("{label}: needs domain, cert_file and key_file")),
        }
    }

    if acme {
        #[cfg(not(feature = "acme"))]
        report.error("[acme] is configured, but this rws binary was built without the `acme` feature — no certificate would be requested");
        if get(Config::RWS_CONFIG_ACME_EMAIL).unwrap_or("").is_empty() {
            report.warn("[acme] has no email: the CA can't warn you about expiring or revoked certificates");
        }
        let challenge = get(Config::RWS_CONFIG_ACME_CHALLENGE).map(str::trim).filter(|v| !v.is_empty()).unwrap_or("http-01").to_ascii_lowercase();
        if !matches!(challenge.as_str(), "http-01" | "tls-alpn-01" | "dns-01" | "dns-persist-01") {
            report.error(format!("[acme] challenge = {challenge:?}: expected http-01, tls-alpn-01, dns-01 or dns-persist-01"));
        }
        for domain in acme_domains.split(',').map(str::trim) {
            // A wildcard is one leading "*." label (RFC 8555 §7.1.3).
            let (wildcard, name) = match domain.strip_prefix("*.") {
                Some(rest) => (true, rest),
                None => (false, domain),
            };
            if name.is_empty() || name.contains('*') || name.contains('/') || name.contains(':') || !name.contains('.') {
                report.error(format!("[acme] domains: '{domain}' is not a domain name"));
            } else if wildcard && !challenge.starts_with("dns-") {
                report.error(format!("[acme] domains: the wildcard '{domain}' needs challenge = \"dns-01\" or \"dns-persist-01\""));
            }
        }
        let port = get(Config::RWS_CONFIG_PORT).unwrap_or("7878");
        let challenge_port = get(Config::RWS_CONFIG_ACME_CHALLENGE_PORT).unwrap_or("80");
        let redirect_port = get(Config::RWS_CONFIG_HTTP_REDIRECT_PORT).unwrap_or("");
        if challenge == "http-01" && redirect_port.is_empty() {
            report.warn(format!(
                "[acme] without http_redirect_port: nothing answers the HTTP-01 challenge on port {challenge_port}; set http_redirect_port = {challenge_port}"
            ));
        }
        if challenge == "dns-01" {
            check_acme_dns(&get, report);
        }
        if challenge == "dns-persist-01" && get(Config::RWS_CONFIG_ACME_DNS_PROVIDER).is_some_and(|p| !p.trim().is_empty()) {
            report.warn("[acme] dns_provider is ignored with dns-persist-01: you publish its record once yourself (rws prints it)");
        }
        let on_demand = get(Config::RWS_CONFIG_ACME_ON_DEMAND).unwrap_or("").trim().to_ascii_lowercase();
        if !matches!(on_demand.as_str(), "" | "true" | "false") {
            report.error(format!("[acme] on_demand = {on_demand:?}: expected true or false"));
        } else if on_demand == "true" {
            match get(Config::RWS_CONFIG_ACME_ON_DEMAND_ASK).map(str::trim).filter(|v| !v.is_empty()) {
                None => report.error("[acme] on_demand needs on_demand_ask: without it anyone could make rws order certificates for any name pointed at it"),
                Some(ask) if !(ask.starts_with("http://") || ask.starts_with("https://")) => {
                    report.error(format!("[acme] on_demand_ask = {ask:?}: expected an http:// or https:// URL"))
                }
                Some(_) => {}
            }
            if challenge.starts_with("dns-") {
                report.error(format!("[acme] on_demand works with http-01 and tls-alpn-01, not {challenge} (it would need every customer's DNS zone)"));
            }
        }
        if port != "443" {
            report.warn(format!("[acme] with port = {port}: browsers expect HTTPS on 443 (fine if a port mapping forwards 443 here)"));
        }
    }
}

/// `dns_api_url`, when set: an http(s) URL.
fn check_api_url(url: Option<&str>, report: &mut ConfigReport) {
    if let Some(url) = url.filter(|u| !(u.starts_with("https://") || u.starts_with("http://"))) {
        report.error(format!("[acme] dns_api_url = {url:?}: expected an http:// or https:// URL"));
    }
}

/// `[acme] challenge = "dns-01"`: a provider and what it needs.
fn check_acme_dns<'a>(get: &dyn Fn(&str) -> Option<&'a str>, report: &mut ConfigReport) {
    let set = |name: &str| get(name).map(str::trim).filter(|v| !v.is_empty());
    match set(Config::RWS_CONFIG_ACME_DNS_PROVIDER).map(str::to_ascii_lowercase).as_deref() {
        Some("rfc2136") => {
            match set(Config::RWS_CONFIG_ACME_DNS_SERVER) {
                None => report.error("[acme] dns_provider = \"rfc2136\" needs dns_server (the primary DNS server, host[:port])"),
                Some(server) if server.contains('/') || server.is_empty() => report.error(format!("[acme] dns_server = {server:?}: expected host[:port]")),
                Some(_) => {}
            }
            match (set(Config::RWS_CONFIG_ACME_DNS_TSIG_KEY), set(Config::RWS_CONFIG_ACME_DNS_TSIG_SECRET)) {
                (Some(_), None) | (None, Some(_)) => report.error("[acme] dns_tsig_key and dns_tsig_secret go together"),
                (None, None) => report.warn("[acme] rfc2136 without a TSIG key: the server must accept unsigned updates from this host"),
                (Some(_), Some(secret)) => {
                    #[cfg(feature = "acme")]
                    if crate::acme::base64_secret(secret).is_none() {
                        report.error("[acme] dns_tsig_secret is not base64");
                    }
                    #[cfg(not(feature = "acme"))]
                    let _ = secret;
                }
            }
            if let Some(algorithm) = set(Config::RWS_CONFIG_ACME_DNS_TSIG_ALGORITHM) {
                if !matches!(algorithm.to_ascii_lowercase().as_str(), "hmac-sha256" | "hmac-sha512") {
                    report.error(format!("[acme] dns_tsig_algorithm = {algorithm:?}: expected hmac-sha256 or hmac-sha512"));
                }
            }
        }
        Some("exec") => match set(Config::RWS_CONFIG_ACME_DNS_EXEC) {
            None => report.error("[acme] dns_provider = \"exec\" needs dns_exec (the program)"),
            Some(program) if !offline() && !Path::new(program).is_file() => report.error(format!("[acme] dns_exec = {program:?}: file not found")),
            Some(_) => {}
        },
        Some("cloudflare") => {
            // Usually kept out of the file, in the environment.
            let in_env = offline() || std::env::var(Config::RWS_CONFIG_ACME_DNS_API_TOKEN).is_ok_and(|v| !v.trim().is_empty());
            if set(Config::RWS_CONFIG_ACME_DNS_API_TOKEN).is_none() && !in_env {
                report.error("[acme] dns_provider = \"cloudflare\" needs dns_api_token (an API token with DNS edit permission; or RWS_CONFIG_ACME_DNS_API_TOKEN)");
            }
            check_api_url(set(Config::RWS_CONFIG_ACME_DNS_API_URL), report);
        }
        Some("route53") => {
            let aws = |name: &str| offline() || std::env::var(name).is_ok_and(|v| !v.trim().is_empty());
            if !(aws("AWS_ACCESS_KEY_ID") && aws("AWS_SECRET_ACCESS_KEY")) {
                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");
            }
            check_api_url(set(Config::RWS_CONFIG_ACME_DNS_API_URL), report);
        }
        Some(other) => report.error(format!("[acme] dns_provider = {other:?}: expected rfc2136, cloudflare, route53 or exec")),
        None => report.error("[acme] challenge = \"dns-01\" needs dns_provider (rfc2136, cloudflare, route53 or exec)"),
    }
    if let Some(secs) = set(Config::RWS_CONFIG_ACME_DNS_PROPAGATION_SECS) {
        if secs.parse::<u64>().is_err() {
            report.error(format!("[acme] dns_propagation_secs = {secs:?}: not a whole number"));
        }
    }
}

/// `RWS_CONFIG_CORS_ALLOW_ALL` → `cors_allow_all`, for messages.
fn setting_key(env_name: &str) -> String {
    env_name.trim_start_matches("RWS_CONFIG_").to_ascii_lowercase()
}

fn check_tls_pair(label: &str, cert: &str, key: &str, report: &mut ConfigReport) {
    if offline() {
        return;
    }
    let mut missing = false;
    for (what, path) in [("certificate", cert), ("key", key)] {
        if !Path::new(path).is_file() {
            report.error(format!("{label}: {what} file '{path}' not found"));
            missing = true;
        }
    }
    if missing {
        return;
    }
    #[cfg(all(feature = "http2", not(target_arch = "wasm32")))]
    if let Err(e) = crate::tls::create_tls_acceptor(cert, key) {
        report.error(format!("{label}: {e}"));
    }
    #[cfg(not(feature = "http2"))]
    report.warn(format!("{label}: this build has no TLS support (`http1` only), so the certificate is not used"));
}