Skip to main content

rust_web_server/proxy_config/
validate.rs

1//! Static checks for the proxy sections of `rws.config.toml`, used by
2//! `rws --check` and printed at startup. The parser itself is lenient — a
3//! typo'd key just leaves a default in place — so this is where a route that
4//! points at a missing upstream, an auth secret that isn't set, or a key the
5//! parser never reads gets reported.
6
7use std::collections::HashSet;
8
9use crate::config_check::ConfigReport;
10use crate::proxy_config::{parser, ActionConfig, AuthConfig, MiddlewareConfig, ProxyConfig};
11
12const STRATEGIES: &[&str] = &["round_robin", "random", "ip_hash", "least_connections"];
13
14const HEALTH_CHECK_KEYS: &[&str] = &["path", "interval_secs", "timeout_ms", "healthy_threshold", "unhealthy_threshold"];
15const PROXY_ACTION_KEYS: &[&str] = &["upstream", "connect_timeout_ms", "read_timeout_ms", "strip_path_prefix", "add_path_prefix", "preserve_host", "upstream_host"];
16const GRPC_ACTION_KEYS: &[&str] = &["upstream", "connect_timeout_ms", "read_timeout_ms"];
17const STATIC_ACTION_KEYS: &[&str] = &["root", "index"];
18const REDIRECT_ACTION_KEYS: &[&str] = &["location", "status"];
19const FASTCGI_ACTION_KEYS: &[&str] = &["address", "root", "index", "split_path", "front_controller", "connect_timeout_ms", "read_timeout_ms", "max_idle"];
20const RESPOND_ACTION_KEYS: &[&str] = &["status", "body", "content_type"];
21const REWRITE_RULE_KEYS: &[&str] = &["type", "name", "value", "prefix", "from", "to", "code", "reason"];
22
23/// The keys the parser reads in a section, by the section's path with array
24/// indices removed (`route[2].middleware.auth` → `route.middleware.auth`).
25/// `None` for a section the parser never reads at all.
26fn known_keys(section: &str) -> Option<Vec<&'static str>> {
27    // The global `[middleware]` table has the same shape as `[route.middleware]`.
28    let route_form;
29    let section = if section == "middleware" || section.starts_with("middleware.") {
30        route_form = format!("route.{section}");
31        route_form.as_str()
32    } else {
33        section
34    };
35    let keys: Vec<&'static str> = match section {
36        "upstream" => vec!["name", "backends", "strategy", "weights", "tls_ca_file", "tls_client_cert_file", "tls_client_key_file", "protocol"],
37        "upstream.sticky" => vec!["cookie", "max_age_secs"],
38        "upstream.circuit_breaker" => vec!["failure_threshold", "recovery_secs", "half_open_probes"],
39        "upstream.retry" => vec!["attempts", "status"],
40        "upstream.health_check" | "ws_proxy.health_check" => HEALTH_CHECK_KEYS.to_vec(),
41        "route" => vec!["name"],
42        "route.match" => vec!["host", "path", "method", "content_type"],
43        // `[route.action]` takes `type` plus the short form of every action's keys.
44        "route.action" => {
45            let mut keys = vec!["type"];
46            for group in [PROXY_ACTION_KEYS, GRPC_ACTION_KEYS, STATIC_ACTION_KEYS, REDIRECT_ACTION_KEYS, RESPOND_ACTION_KEYS, FASTCGI_ACTION_KEYS] {
47                for key in group {
48                    if !keys.contains(key) {
49                        keys.push(key);
50                    }
51                }
52            }
53            keys
54        }
55        "route.action.proxy" => PROXY_ACTION_KEYS.to_vec(),
56        "route.action.grpc" => GRPC_ACTION_KEYS.to_vec(),
57        "route.action.static" => STATIC_ACTION_KEYS.to_vec(),
58        "route.action.fastcgi" => FASTCGI_ACTION_KEYS.to_vec(),
59        "route.action.redirect" => REDIRECT_ACTION_KEYS.to_vec(),
60        "route.action.respond" => RESPOND_ACTION_KEYS.to_vec(),
61        "route.action.mcp" => super::mcp_gateway::GATEWAY_KEYS.to_vec(),
62        "route.action.mcp.upstream" => super::mcp_gateway::UPSTREAM_KEYS.to_vec(),
63        "route.action.mcp.caller" => super::mcp_gateway::CALLER_KEYS.to_vec(),
64        "route.action.mcp.openapi" => super::mcp_gateway::OPENAPI_KEYS.to_vec(),
65        "route.action.mcp.allow" => super::mcp_gateway::ALLOW_KEYS.to_vec(),
66        "route.action.mcp.limit" => super::mcp_gateway::LIMIT_KEYS.to_vec(),
67        "route.action.llm" => super::llm::LLM_KEYS.to_vec(),
68        "route.action.a2a" => super::a2a_gateway::KEYS.to_vec(),
69        "route.action.llm.provider" => super::llm::PROVIDER_KEYS.to_vec(),
70        "route.action.llm.key" => super::llm::KEY_KEYS.to_vec(),
71        "route.middleware" => vec!["timeout_ms", "max_body_size", "early_hints"],
72        "route.middleware.rate_limit" => vec!["max_requests", "window_secs"],
73        "route.middleware.cache" => vec!["ttl_secs", "vary_by", "dir", "max_size", "purge_token_env"],
74        "route.middleware.auth" => vec![
75            "type", "token_env", "secret_env", "previous_secret_env", "htpasswd_file",
76            // oidc
77            "issuer", "provider", "tenant", "client_id", "client_secret_env", "redirect_uri", "scopes", "allowed_emails",
78            "allowed_domains", "allowed_groups", "groups_claim", "cookie_secret_env", "session_ttl_secs", "exclude", "forward_headers",
79            // forward
80            "url", "copy_headers", "timeout_ms",
81        ],
82        "route.middleware.ip_filter" => vec!["allow", "deny"],
83        "route.middleware.mirror" => vec!["upstream", "backends", "percent"],
84        "route.middleware.authz" => vec!["relation", "object"],
85        "authz" => vec!["store", "tuples"],
86        "route.middleware.wasm" => vec!["module", "fuel", "memory_mb", "config"],
87        "route.middleware.rewrite.request" | "route.middleware.rewrite.response" => REWRITE_RULE_KEYS.to_vec(),
88        "tcp_proxy" => vec!["name", "listen", "backends", "connect_timeout_ms"],
89        "udp_proxy" => vec!["name", "listen", "backends", "reply_timeout_ms", "buffer_size"],
90        "ws_proxy" => vec!["name", "listen", "backends", "connect_timeout_ms", "read_timeout_ms"],
91        _ => return None,
92    };
93    Some(keys)
94}
95
96/// `route[2].middleware.rewrite.request[0]` → `route.middleware.rewrite.request`.
97fn strip_indices(section: &str) -> String {
98    let mut out = String::with_capacity(section.len());
99    let mut in_index = false;
100    for c in section.chars() {
101        match c {
102            '[' => in_index = true,
103            ']' => in_index = false,
104            _ if !in_index => out.push(c),
105            _ => {}
106        }
107    }
108    out
109}
110
111/// Report keys and tables in the proxy sections that the parser ignores.
112pub fn check_unknown_keys(toml: &str, report: &mut ConfigReport) {
113    let map = parser::parse(toml);
114    let mut sections: Vec<&String> = map.keys().collect();
115    sections.sort();
116    for section in sections {
117        let root = section.split(['.', '[']).next().unwrap_or("");
118        if !["route", "upstream", "tcp_proxy", "udp_proxy", "ws_proxy", "middleware", "authz"].contains(&root) {
119            continue;
120        }
121        let shape = strip_indices(section);
122        // Header names, relation names: any key.
123        if shape == "route.action.mcp.upstream.headers_env" || shape == "route.action.mcp.openapi.headers_env" || shape == "route.action.a2a.headers_env" || shape.starts_with("authz.type.") || shape == "route.action.params" || shape == "route.action.fastcgi.params" {
124            continue;
125        }
126        match known_keys(&shape) {
127            None => report.error(format!("[{}]: unknown table — ignored", shape)),
128            Some(keys) => {
129                for (key, _) in &map[section] {
130                    if !keys.contains(&key.as_str()) {
131                        report.error(format!("[{}] {}: unknown key — ignored", shape, key));
132                    }
133                }
134            }
135        }
136    }
137}
138
139/// `host:port`, or a URL with an `http://`, `https://`, `h2://`, `ws://` or
140/// `wss://` scheme, whose port may be left to the scheme's default.
141fn is_host_port(backend: &str) -> bool {
142    let (rest, has_scheme) = match ["http://", "https://", "h2://", "h2s://", "grpc://", "grpcs://", "ws://", "wss://"]
143        .iter()
144        .find_map(|scheme| backend.strip_prefix(scheme))
145    {
146        Some(rest) => (rest, true),
147        None => (backend, false),
148    };
149    let rest = rest.trim_end_matches('/');
150    if rest.is_empty() || rest.contains('/') || rest.contains(char::is_whitespace) {
151        return false;
152    }
153    match rest.rsplit_once(':') {
154        Some((host, port)) => !host.is_empty() && port.parse::<u16>().is_ok_and(|p| p > 0),
155        None => has_scheme,
156    }
157}
158
159impl ProxyConfig {
160    /// Check the configuration for mistakes the parser lets through. Reads
161    /// the auth secrets' environment variables and htpasswd files, so run it
162    /// in the environment the server will run in.
163    pub fn validate(&self, report: &mut ConfigReport) {
164        // [authz], built over a throwaway store (nothing is written).
165        let authz = super::builder::config_authorizer_with(self, Some(std::sync::Arc::new(crate::authz::MemoryStore::new())));
166        if self.authz.as_ref().is_some_and(|a| a.store == "sql")
167            && !cfg!(any(feature = "model-sqlite", feature = "model-postgres", feature = "model-mysql"))
168        {
169            report.error("[authz]: store = \"sql\" needs a build with a model-sqlite / model-postgres / model-mysql feature".to_string());
170        }
171        if let Some(Err(e)) = &authz {
172            report.error(format!("[authz]: {e}"));
173        }
174        let mut names = HashSet::new();
175        for (i, upstream) in self.upstreams.iter().enumerate() {
176            let label = if upstream.name.is_empty() { format!("[[upstream]] #{}", i + 1) } else { format!("upstream '{}'", upstream.name) };
177            if upstream.name.is_empty() {
178                report.error(format!("{label}: missing `name` — no route can refer to it"));
179            } else if !names.insert(upstream.name.as_str()) {
180                report.error(format!("{label}: declared more than once"));
181            }
182            if upstream.backends.is_empty() {
183                report.error(format!("{label}: `backends` is empty"));
184            }
185            match upstream.protocol.to_ascii_lowercase().as_str() {
186                "" | "http1" => {}
187                "h3" => {
188                    if !cfg!(feature = "http3") {
189                        report.error(format!("{label}: protocol = \"h3\" needs a build with the http3 feature (the default)"));
190                    }
191                    if let Some(plain) = upstream.backends.iter().find(|b| !b.starts_with("https://")) {
192                        report.error(format!("{label}: protocol = \"h3\" needs https:// backends (QUIC is always TLS); '{plain}' isn't"));
193                    }
194                }
195                other => report.error(format!("{label}: protocol must be \"http1\" or \"h3\", not \"{other}\"")),
196            }
197            for backend in &upstream.backends {
198                if !is_host_port(backend) {
199                    report.error(format!("{label}: backend '{backend}' is not host:port"));
200                }
201            }
202            let client = match (&upstream.tls_client_cert_file, &upstream.tls_client_key_file) {
203                (Some(cert), Some(key)) => Some((cert.as_str(), key.as_str())),
204                (None, None) => None,
205                _ => {
206                    report.error(format!("{label}: tls_client_cert_file and tls_client_key_file go together"));
207                    None
208                }
209            };
210            if upstream.tls_ca_file.is_some() || client.is_some() {
211                if !crate::config_check::offline() {
212                    if let Err(e) = crate::proxy::UpstreamTls::new(upstream.tls_ca_file.as_deref(), client) {
213                        report.error(format!("{label}: {e}; its TLS backends would answer 502"));
214                    }
215                }
216                if !upstream.tls {
217                    report.warn(format!("{label}: TLS settings are set but no backend is https://, h2s:// or grpcs://, so they aren't used"));
218                }
219            }
220            if !STRATEGIES.contains(&upstream.strategy.as_str()) {
221                report.error(format!(
222                    "{label}: unknown strategy '{}' (expected one of {})",
223                    upstream.strategy,
224                    STRATEGIES.join(", ")
225                ));
226            }
227            if !upstream.weights.is_empty() {
228                if upstream.weights.len() != upstream.backends.len() {
229                    report.error(format!("{label}: `weights` has {} entries for {} backends (one each, in order)", upstream.weights.len(), upstream.backends.len()));
230                }
231                if upstream.weights.contains(&0) {
232                    report.error(format!("{label}: `weights` must be whole numbers of 1 or more"));
233                }
234                if upstream.strategy == "ip_hash" {
235                    report.warn(format!("{label}: `weights` don't apply to strategy ip_hash"));
236                }
237            }
238            if let Some(sticky) = &upstream.sticky {
239                let token = |c: char| c.is_ascii_alphanumeric() || "!#$%&'*+-.^_`|~".contains(c);
240                if sticky.cookie.is_empty() || !sticky.cookie.chars().all(token) {
241                    report.error(format!("{label}: sticky cookie name '{}' isn't a valid cookie name", sticky.cookie));
242                }
243            }
244            if let Some(breaker) = &upstream.circuit_breaker {
245                if breaker.failure_threshold == 0 {
246                    report.error(format!("{label}: circuit_breaker.failure_threshold must be 1 or more"));
247                }
248                if breaker.recovery_secs == 0 {
249                    report.warn(format!("{label}: circuit_breaker.recovery_secs = 0 probes an open backend on the next request"));
250                }
251            }
252            if let Some(retry) = &upstream.retry {
253                if retry.attempts == 0 {
254                    report.warn(format!("{label}: retry.attempts = 0 never retries"));
255                } else if retry.attempts as usize >= upstream.backends.len() {
256                    report.warn(format!(
257                        "{label}: retry.attempts = {} but there are {} backends — a request goes to each at most once",
258                        retry.attempts,
259                        upstream.backends.len()
260                    ));
261                }
262                if let Some(status) = retry.status.iter().find(|s| !(400..=599).contains(*s)) {
263                    report.error(format!("{label}: retry.status {status} isn't an error status (400–599)"));
264                }
265            }
266            #[cfg(not(any(feature = "http-client", feature = "http2")))]
267            if upstream.tls {
268                report.error(format!("{label}: https:// backends need the `http2` or `http-client` feature, which this build doesn't include"));
269            }
270        }
271
272        for (i, route) in self.routes.iter().enumerate() {
273            let label = if route.name.is_empty() { format!("route #{}", i + 1) } else { format!("route '{}'", route.name) };
274            // The proxy writes the upstream `Host` itself, after the rewrites.
275            if matches!(route.action, ActionConfig::Proxy { .. })
276                && route.middleware.rewrite_request.iter().any(|r| r.type_.starts_with("header_") && r.name.as_deref().is_some_and(|n| n.trim().eq_ignore_ascii_case("host")))
277            {
278                report.warn(format!("{label}: a request rewrite of `Host` doesn't reach the upstream — set `preserve_host = true` or `upstream_host = \"…\"` on the proxy action"));
279            }
280            match &route.action {
281                ActionConfig::Proxy { upstream, .. } | ActionConfig::Grpc { upstream, .. } => {
282                    if upstream.is_empty() {
283                        report.error(format!("{label}: proxy action has no `upstream`"));
284                    } else if !names.contains(upstream.as_str()) {
285                        if is_host_port(upstream) {
286                            report.warn(format!("{label}: upstream '{upstream}' is not a declared [[upstream]]; using it as a backend address (no health checks)"));
287                        } else {
288                            report.error(format!("{label}: upstream '{upstream}' is not a declared [[upstream]]"));
289                        }
290                    }
291                }
292                ActionConfig::Static { root, .. } => {
293                    if root.is_empty() {
294                        report.error(format!("{label}: static action has no `root`"));
295                    } else if !crate::config_check::offline() && !std::path::Path::new(root).is_dir() {
296                        report.warn(format!("{label}: static root '{root}' is not a directory (yet)"));
297                    }
298                }
299                ActionConfig::FastCgi(f) => {
300                    if f.address.is_empty() {
301                        report.error(format!("{label}: fastcgi action has no `address` (unix:/run/php/php-fpm.sock or host:port)"));
302                    } else if let Err(e) = crate::fastcgi::Address::parse(&f.address) {
303                        report.error(format!("{label}: {e}"));
304                    }
305                    if f.root.is_empty() {
306                        report.error(format!("{label}: fastcgi action has no `root`"));
307                    } else if !crate::config_check::offline() && !std::path::Path::new(&f.root).is_dir() {
308                        report.error(format!("{label}: fastcgi root '{}' is not a directory", f.root));
309                    }
310                }
311                ActionConfig::Redirect { location, status } => {
312                    if location.is_empty() {
313                        report.error(format!("{label}: redirect action has no `location`"));
314                    }
315                    if !(300..=399).contains(status) {
316                        report.error(format!("{label}: redirect status {status} is not a 3xx code"));
317                    }
318                }
319                ActionConfig::Respond { status, .. } => {
320                    if !(100..=599).contains(status) {
321                        report.error(format!("{label}: respond status {status} is not an HTTP status code"));
322                    }
323                }
324                ActionConfig::Mcp(gateway) => {
325                    super::mcp_gateway::validate(gateway, route.match_.path.as_deref(), &label, report);
326                }
327                ActionConfig::Llm(llm) => {
328                    super::llm::validate(llm, &label, report);
329                }
330                ActionConfig::A2a(gateway) => {
331                    super::a2a_gateway::validate(gateway, route.match_.path.as_deref(), &label, report);
332                }
333                ActionConfig::Unknown(kind) if kind.is_empty() => {
334                    report.error(format!("{label}: [route.action] has no `type`"));
335                }
336                ActionConfig::Unknown(kind) => {
337                    report.error(format!("{label}: unknown action type '{kind}' (expected proxy, grpc, static, redirect, respond, mcp, llm or a2a)"));
338                }
339            }
340            let has_auth = route.middleware.auth.is_some() || self.global_middleware.auth.is_some();
341            validate_middleware(&label, &route.middleware, authz.as_ref(), has_auth, report);
342
343            let m = &route.match_;
344            if m.host.is_none() && m.path.is_none() && m.method.is_none() && m.content_type.is_none() && i + 1 < self.routes.len() {
345                report.warn(format!("{label}: matches every request, so the routes after it are never reached"));
346            }
347        }
348
349        validate_middleware("[middleware]", &self.global_middleware, authz.as_ref(), self.global_middleware.auth.is_some(), report);
350        if self.global_middleware.authz.is_some() {
351            report.warn("[middleware.authz]: applies to every request, /healthz, /readyz and /metrics included — probes without a caller get 401".to_string());
352        }
353
354        let listeners = self.tcp_proxies.iter().map(|p| ("tcp_proxy", &p.name, &p.listen, &p.backends))
355            .chain(self.udp_proxies.iter().map(|p| ("udp_proxy", &p.name, &p.listen, &p.backends)))
356            .chain(self.ws_proxies.iter().map(|p| ("ws_proxy", &p.name, &p.listen, &p.backends)));
357        for (kind, name, listen, backends) in listeners {
358            let label = format!("[[{kind}]] '{name}'");
359            if listen.parse::<std::net::SocketAddr>().is_err() {
360                report.error(format!("{label}: listen '{listen}' is not an address like 0.0.0.0:5432"));
361            }
362            if backends.is_empty() {
363                report.error(format!("{label}: `backends` is empty"));
364            }
365            for backend in backends {
366                if !is_host_port(backend) {
367                    report.error(format!("{label}: backend '{backend}' is not host:port"));
368                }
369            }
370        }
371    }
372}
373
374fn validate_middleware(
375    label: &str,
376    mw: &MiddlewareConfig,
377    authz: Option<&Result<crate::authz::Authorizer, String>>,
378    has_auth: bool,
379    report: &mut ConfigReport,
380) {
381    for link in &mw.early_hints {
382        if !crate::early_hints::valid(link) {
383            report.error(format!("{label}: early_hints value {link:?} is empty or holds a line break"));
384        } else if !link.trim_start().starts_with('<') {
385            report.warn(format!("{label}: early_hints value {link:?} doesn't start with <URL>; browsers will ignore it"));
386        }
387    }
388    if let Some(rule) = &mw.authz {
389        let schema = authz.and_then(|a| a.as_ref().ok()).map(|a| a.schema());
390        match (authz, crate::authz::ObjectTemplate::parse(&rule.object)) {
391            (None, _) => report.error(format!("{label}: [middleware.authz] needs an [authz] section")),
392            (_, Err(e)) => report.error(format!("{label}: [middleware.authz] {e}")),
393            (Some(_), Ok(template)) => {
394                let kind = template.object_type().unwrap_or_default();
395                if rule.relation.is_empty() {
396                    report.error(format!("{label}: [middleware.authz] needs `relation`"));
397                } else if let Some(schema) = schema {
398                    if !schema.has_relation(kind, &rule.relation) {
399                        report.error(format!("{label}: [middleware.authz] {kind}#{} isn't defined in [authz]", rule.relation));
400                    }
401                }
402            }
403        }
404        if !has_auth {
405            report.warn(format!("{label}: [middleware.authz] without auth here or in [middleware]: no caller is known, every request gets 401"));
406        }
407    }
408    if let Some(m) = &mw.mirror {
409        match (m.upstream.is_empty(), m.backends.is_empty()) {
410            (true, true) => report.error(format!("{label}: [middleware.mirror] needs `upstream` or `backends`")),
411            (false, false) => report.error(format!("{label}: [middleware.mirror] has both `upstream` and `backends`; use one")),
412            _ => {}
413        }
414        for b in &m.backends {
415            if crate::proxy_config::health::parse_backend_url(b).is_none() {
416                report.error(format!("{label}: mirror backend '{b}' is not a backend address"));
417            }
418        }
419        if !(m.percent.is_finite() && (0.0..=100.0).contains(&m.percent)) {
420            report.error(format!("{label}: mirror percent must be a number from 0 to 100"));
421        } else if m.percent == 0.0 {
422            report.warn(format!("{label}: mirror percent is 0: nothing is mirrored"));
423        }
424    }
425    if let Some(wasm) = &mw.wasm {
426        if wasm.module.is_empty() {
427            report.error(format!("{label}: [middleware.wasm] has no `module`; the route answers 503"));
428        } else if cfg!(not(feature = "wasm-plugins")) {
429            report.error(format!("{label}: [middleware.wasm] needs the wasm-plugins feature, which this build doesn't include; the route answers 503"));
430        } else if !crate::config_check::offline() {
431            #[cfg(feature = "wasm-plugins")]
432            if let Err(e) = crate::wasm_plugin::WasmLayer::from_file(&wasm.module) {
433                report.error(format!("{label}: {e}; the route answers 503"));
434            }
435        }
436        if wasm.fuel == 0 || wasm.memory_mb == 0 {
437            report.error(format!("{label}: [middleware.wasm] fuel and memory_mb must be above 0"));
438        }
439    }
440    match &mw.auth {
441        Some(AuthConfig::Bearer { token_env }) | Some(AuthConfig::Jwt { secret_env: token_env, .. }) => {
442            if token_env.is_empty() {
443                report.error(format!("{label}: auth has no `token_env` / `secret_env`; the route answers 503"));
444            } else if !crate::config_check::offline() && std::env::var(token_env).unwrap_or_default().is_empty() {
445                report.error(format!("{label}: auth secret env var '{token_env}' is unset or empty; the route answers 503 until it is set"));
446            }
447        }
448        Some(AuthConfig::Oidc(o)) => {
449            if o.client_id.is_empty() {
450                report.error(format!("{label}: oidc auth has no `client_id`; the route answers 503"));
451            }
452            match (o.issuer.is_empty(), o.provider.as_str()) {
453                (true, "") => report.error(format!("{label}: oidc auth needs `issuer` (discovery URL) or `provider` (google, microsoft, github); the route answers 503")),
454                (true, "google" | "microsoft" | "github") => {}
455                (true, other) => report.error(format!("{label}: oidc provider {other:?}: expected google, microsoft or github (others: set `issuer`)")),
456                (false, _) if !o.issuer.starts_with("https://") && !o.issuer.starts_with("http://") => report.error(format!("{label}: oidc issuer {:?} is not a URL", o.issuer)),
457                _ => {}
458            }
459            if o.client_secret_env.is_empty() {
460                report.warn(format!("{label}: oidc auth has no `client_secret_env`: a public client (PKCE only), which most providers refuse for web apps"));
461            } else if !crate::config_check::offline() && std::env::var(&o.client_secret_env).unwrap_or_default().is_empty() {
462                report.error(format!("{label}: oidc client secret env var '{}' is unset or empty; the route answers 503", o.client_secret_env));
463            }
464            if o.cookie_secret_env.is_empty() {
465                report.warn(format!("{label}: oidc auth without `cookie_secret_env`: sign-ins are lost on restart and don't work across replicas"));
466            } else if !crate::config_check::offline() && std::env::var(&o.cookie_secret_env).unwrap_or_default().len() < 32 {
467                report.error(format!("{label}: oidc cookie secret env var '{}' must hold at least 32 characters; the route answers 503", o.cookie_secret_env));
468            }
469            #[cfg(not(feature = "sso"))]
470            report.error(format!("{label}: oidc auth needs the `sso` feature, which this build doesn't include; the route answers 503"));
471        }
472        Some(AuthConfig::Unknown(kind)) => {
473            report.error(format!("{label}: auth type {kind:?} is not one of bearer, jwt, basic, oidc, forward; the route answers 503"));
474        }
475        Some(AuthConfig::Forward { url, .. }) => {
476            if !(url.starts_with("http://") || url.starts_with("https://")) {
477                report.error(format!("{label}: forward auth `url` {url:?} is not an http(s) URL; the route answers 503"));
478            }
479            #[cfg(not(feature = "auth"))]
480            report.error(format!("{label}: forward auth needs the `auth` feature, which this build doesn't include; the route answers 503"));
481        }
482        Some(AuthConfig::Basic { htpasswd_file }) => {
483            #[cfg(feature = "auth")]
484            if !crate::config_check::offline() {
485                if let Err(e) = crate::auth::BasicAuthLayer::from_htpasswd_file(htpasswd_file) {
486                    report.error(format!("{label}: basic auth: {e}; the route answers 503"));
487                }
488            }
489            #[cfg(not(feature = "auth"))]
490            let _ = htpasswd_file;
491        }
492        None => {}
493    }
494    #[cfg(not(feature = "auth"))]
495    if matches!(mw.auth, Some(AuthConfig::Jwt { .. }) | Some(AuthConfig::Basic { .. })) {
496        report.error(format!("{label}: jwt and basic auth need the `auth` feature, which this build doesn't include; the route answers 503"));
497    }
498
499    for entry in mw.ip_allow.iter().chain(&mw.ip_deny) {
500        if !crate::ip_filter::is_valid_entry(entry) {
501            report.error(format!("{label}: ip_filter entry '{entry}' is not an IP address or CIDR range — ignored"));
502        }
503    }
504    if !mw.ip_allow.is_empty() && !mw.ip_deny.is_empty() {
505        report.warn(format!("{label}: ip_filter has both `allow` and `deny`; only `allow` is used"));
506    }
507    if let Some(cache) = &mw.cache {
508        if crate::proxy_config::cache_max_bytes(&cache.max_size).is_none() {
509            report.error(format!("{label}: cache max_size {:?} is not a size (e.g. \"512M\")", cache.max_size));
510        }
511        if !cache.purge_token_env.is_empty() && !crate::config_check::offline() && std::env::var(&cache.purge_token_env).unwrap_or_default().trim().is_empty() {
512            report.error(format!("{label}: cache purge_token_env {} is unset or empty; PURGE is refused", cache.purge_token_env));
513        }
514        if !cache.max_size.is_empty() && cache.dir.is_empty() {
515            report.warn(format!("{label}: cache max_size only applies with `dir` (the memory cache is bounded by entries)"));
516        }
517        if !cache.dir.is_empty() && !crate::config_check::offline() {
518            let probe = std::path::Path::new(&cache.dir).join(format!(".rws-check-{}", std::process::id()));
519            let writable = std::fs::create_dir_all(&cache.dir).and_then(|_| std::fs::write(&probe, b"")).is_ok();
520            let _ = std::fs::remove_file(&probe);
521            if !writable {
522                report.error(format!("{label}: cache dir {:?} isn't writable; the route caches in memory instead", cache.dir));
523            }
524        }
525    }
526    if let Some(rl) = &mw.rate_limit {
527        if rl.max_requests == 0 || rl.window_secs == 0 {
528            report.error(format!("{label}: rate_limit needs max_requests and window_secs above 0"));
529        }
530    }
531    for rule in mw.rewrite_request.iter().chain(&mw.rewrite_response) {
532        let known = ["header_set", "header_remove", "uri_set", "uri_strip_prefix", "strip_prefix",
533                     "uri_add_prefix", "add_prefix", "status", "body_replace"];
534        if !known.contains(&rule.type_.as_str()) {
535            report.error(format!("{label}: unknown rewrite rule type '{}' — ignored", rule.type_));
536        }
537    }
538}