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"];
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 RESPOND_ACTION_KEYS: &[&str] = &["status", "body", "content_type"];
20const REWRITE_RULE_KEYS: &[&str] = &["type", "name", "value", "prefix", "from", "to", "code", "reason"];
21
22/// The keys the parser reads in a section, by the section's path with array
23/// indices removed (`route[2].middleware.auth` → `route.middleware.auth`).
24/// `None` for a section the parser never reads at all.
25fn known_keys(section: &str) -> Option<Vec<&'static str>> {
26    // The global `[middleware]` table has the same shape as `[route.middleware]`.
27    let route_form;
28    let section = if section == "middleware" || section.starts_with("middleware.") {
29        route_form = format!("route.{section}");
30        route_form.as_str()
31    } else {
32        section
33    };
34    let keys: Vec<&'static str> = match section {
35        "upstream" => vec!["name", "backends", "strategy", "weights", "tls_ca_file", "tls_client_cert_file", "tls_client_key_file"],
36        "upstream.sticky" => vec!["cookie", "max_age_secs"],
37        "upstream.circuit_breaker" => vec!["failure_threshold", "recovery_secs", "half_open_probes"],
38        "upstream.retry" => vec!["attempts", "status"],
39        "upstream.health_check" | "ws_proxy.health_check" => HEALTH_CHECK_KEYS.to_vec(),
40        "route" => vec!["name"],
41        "route.match" => vec!["host", "path", "method", "content_type"],
42        // `[route.action]` takes `type` plus the short form of every action's keys.
43        "route.action" => {
44            let mut keys = vec!["type"];
45            for group in [PROXY_ACTION_KEYS, GRPC_ACTION_KEYS, STATIC_ACTION_KEYS, REDIRECT_ACTION_KEYS, RESPOND_ACTION_KEYS] {
46                for key in group {
47                    if !keys.contains(key) {
48                        keys.push(key);
49                    }
50                }
51            }
52            keys
53        }
54        "route.action.proxy" => PROXY_ACTION_KEYS.to_vec(),
55        "route.action.grpc" => GRPC_ACTION_KEYS.to_vec(),
56        "route.action.static" => STATIC_ACTION_KEYS.to_vec(),
57        "route.action.redirect" => REDIRECT_ACTION_KEYS.to_vec(),
58        "route.action.respond" => RESPOND_ACTION_KEYS.to_vec(),
59        "route.action.mcp" => super::mcp_gateway::GATEWAY_KEYS.to_vec(),
60        "route.action.mcp.upstream" => super::mcp_gateway::UPSTREAM_KEYS.to_vec(),
61        "route.action.mcp.caller" => super::mcp_gateway::CALLER_KEYS.to_vec(),
62        "route.action.mcp.allow" => super::mcp_gateway::ALLOW_KEYS.to_vec(),
63        "route.action.mcp.limit" => super::mcp_gateway::LIMIT_KEYS.to_vec(),
64        "route.action.llm" => super::llm::LLM_KEYS.to_vec(),
65        "route.action.llm.provider" => super::llm::PROVIDER_KEYS.to_vec(),
66        "route.action.llm.key" => super::llm::KEY_KEYS.to_vec(),
67        "route.middleware" => vec!["timeout_ms", "max_body_size"],
68        "route.middleware.rate_limit" => vec!["max_requests", "window_secs"],
69        "route.middleware.cache" => vec!["ttl_secs", "vary_by"],
70        "route.middleware.auth" => vec!["type", "token_env", "secret_env", "htpasswd_file"],
71        "route.middleware.ip_filter" => vec!["allow", "deny"],
72        "route.middleware.rewrite.request" | "route.middleware.rewrite.response" => REWRITE_RULE_KEYS.to_vec(),
73        "tcp_proxy" => vec!["name", "listen", "backends", "connect_timeout_ms"],
74        "udp_proxy" => vec!["name", "listen", "backends", "reply_timeout_ms", "buffer_size"],
75        "ws_proxy" => vec!["name", "listen", "backends", "connect_timeout_ms", "read_timeout_ms"],
76        _ => return None,
77    };
78    Some(keys)
79}
80
81/// `route[2].middleware.rewrite.request[0]` → `route.middleware.rewrite.request`.
82fn strip_indices(section: &str) -> String {
83    let mut out = String::with_capacity(section.len());
84    let mut in_index = false;
85    for c in section.chars() {
86        match c {
87            '[' => in_index = true,
88            ']' => in_index = false,
89            _ if !in_index => out.push(c),
90            _ => {}
91        }
92    }
93    out
94}
95
96/// Report keys and tables in the proxy sections that the parser ignores.
97pub fn check_unknown_keys(toml: &str, report: &mut ConfigReport) {
98    let map = parser::parse(toml);
99    let mut sections: Vec<&String> = map.keys().collect();
100    sections.sort();
101    for section in sections {
102        let root = section.split(['.', '[']).next().unwrap_or("");
103        if !["route", "upstream", "tcp_proxy", "udp_proxy", "ws_proxy", "middleware"].contains(&root) {
104            continue;
105        }
106        let shape = strip_indices(section);
107        // Header names: any key.
108        if shape == "route.action.mcp.upstream.headers_env" {
109            continue;
110        }
111        match known_keys(&shape) {
112            None => report.error(format!("[{}]: unknown table — ignored", shape)),
113            Some(keys) => {
114                for (key, _) in &map[section] {
115                    if !keys.contains(&key.as_str()) {
116                        report.error(format!("[{}] {}: unknown key — ignored", shape, key));
117                    }
118                }
119            }
120        }
121    }
122}
123
124/// `host:port`, or a URL with an `http://`, `https://`, `h2://`, `ws://` or
125/// `wss://` scheme, whose port may be left to the scheme's default.
126fn is_host_port(backend: &str) -> bool {
127    let (rest, has_scheme) = match ["http://", "https://", "h2://", "h2s://", "grpc://", "grpcs://", "ws://", "wss://"]
128        .iter()
129        .find_map(|scheme| backend.strip_prefix(scheme))
130    {
131        Some(rest) => (rest, true),
132        None => (backend, false),
133    };
134    let rest = rest.trim_end_matches('/');
135    if rest.is_empty() || rest.contains('/') || rest.contains(char::is_whitespace) {
136        return false;
137    }
138    match rest.rsplit_once(':') {
139        Some((host, port)) => !host.is_empty() && port.parse::<u16>().is_ok_and(|p| p > 0),
140        None => has_scheme,
141    }
142}
143
144impl ProxyConfig {
145    /// Check the configuration for mistakes the parser lets through. Reads
146    /// the auth secrets' environment variables and htpasswd files, so run it
147    /// in the environment the server will run in.
148    pub fn validate(&self, report: &mut ConfigReport) {
149        let mut names = HashSet::new();
150        for (i, upstream) in self.upstreams.iter().enumerate() {
151            let label = if upstream.name.is_empty() { format!("[[upstream]] #{}", i + 1) } else { format!("upstream '{}'", upstream.name) };
152            if upstream.name.is_empty() {
153                report.error(format!("{label}: missing `name` — no route can refer to it"));
154            } else if !names.insert(upstream.name.as_str()) {
155                report.error(format!("{label}: declared more than once"));
156            }
157            if upstream.backends.is_empty() {
158                report.error(format!("{label}: `backends` is empty"));
159            }
160            for backend in &upstream.backends {
161                if !is_host_port(backend) {
162                    report.error(format!("{label}: backend '{backend}' is not host:port"));
163                }
164            }
165            let client = match (&upstream.tls_client_cert_file, &upstream.tls_client_key_file) {
166                (Some(cert), Some(key)) => Some((cert.as_str(), key.as_str())),
167                (None, None) => None,
168                _ => {
169                    report.error(format!("{label}: tls_client_cert_file and tls_client_key_file go together"));
170                    None
171                }
172            };
173            if upstream.tls_ca_file.is_some() || client.is_some() {
174                if !crate::config_check::offline() {
175                    if let Err(e) = crate::proxy::UpstreamTls::new(upstream.tls_ca_file.as_deref(), client) {
176                        report.error(format!("{label}: {e}; its TLS backends would answer 502"));
177                    }
178                }
179                if !upstream.tls {
180                    report.warn(format!("{label}: TLS settings are set but no backend is https://, h2s:// or grpcs://, so they aren't used"));
181                }
182            }
183            if !STRATEGIES.contains(&upstream.strategy.as_str()) {
184                report.error(format!(
185                    "{label}: unknown strategy '{}' (expected one of {})",
186                    upstream.strategy,
187                    STRATEGIES.join(", ")
188                ));
189            }
190            if !upstream.weights.is_empty() {
191                if upstream.weights.len() != upstream.backends.len() {
192                    report.error(format!("{label}: `weights` has {} entries for {} backends (one each, in order)", upstream.weights.len(), upstream.backends.len()));
193                }
194                if upstream.weights.contains(&0) {
195                    report.error(format!("{label}: `weights` must be whole numbers of 1 or more"));
196                }
197                if upstream.strategy == "ip_hash" {
198                    report.warn(format!("{label}: `weights` don't apply to strategy ip_hash"));
199                }
200            }
201            if let Some(sticky) = &upstream.sticky {
202                let token = |c: char| c.is_ascii_alphanumeric() || "!#$%&'*+-.^_`|~".contains(c);
203                if sticky.cookie.is_empty() || !sticky.cookie.chars().all(token) {
204                    report.error(format!("{label}: sticky cookie name '{}' isn't a valid cookie name", sticky.cookie));
205                }
206            }
207            if let Some(breaker) = &upstream.circuit_breaker {
208                if breaker.failure_threshold == 0 {
209                    report.error(format!("{label}: circuit_breaker.failure_threshold must be 1 or more"));
210                }
211                if breaker.recovery_secs == 0 {
212                    report.warn(format!("{label}: circuit_breaker.recovery_secs = 0 probes an open backend on the next request"));
213                }
214            }
215            if let Some(retry) = &upstream.retry {
216                if retry.attempts == 0 {
217                    report.warn(format!("{label}: retry.attempts = 0 never retries"));
218                } else if retry.attempts as usize >= upstream.backends.len() {
219                    report.warn(format!(
220                        "{label}: retry.attempts = {} but there are {} backends — a request goes to each at most once",
221                        retry.attempts,
222                        upstream.backends.len()
223                    ));
224                }
225                if let Some(status) = retry.status.iter().find(|s| !(400..=599).contains(*s)) {
226                    report.error(format!("{label}: retry.status {status} isn't an error status (400–599)"));
227                }
228            }
229            #[cfg(not(any(feature = "http-client", feature = "http2")))]
230            if upstream.tls {
231                report.error(format!("{label}: https:// backends need the `http2` or `http-client` feature, which this build doesn't include"));
232            }
233        }
234
235        for (i, route) in self.routes.iter().enumerate() {
236            let label = if route.name.is_empty() { format!("route #{}", i + 1) } else { format!("route '{}'", route.name) };
237            match &route.action {
238                ActionConfig::Proxy { upstream, .. } | ActionConfig::Grpc { upstream, .. } => {
239                    if upstream.is_empty() {
240                        report.error(format!("{label}: proxy action has no `upstream`"));
241                    } else if !names.contains(upstream.as_str()) {
242                        if is_host_port(upstream) {
243                            report.warn(format!("{label}: upstream '{upstream}' is not a declared [[upstream]]; using it as a backend address (no health checks)"));
244                        } else {
245                            report.error(format!("{label}: upstream '{upstream}' is not a declared [[upstream]]"));
246                        }
247                    }
248                }
249                ActionConfig::Static { root, .. } => {
250                    if root.is_empty() {
251                        report.error(format!("{label}: static action has no `root`"));
252                    } else if !crate::config_check::offline() && !std::path::Path::new(root).is_dir() {
253                        report.warn(format!("{label}: static root '{root}' is not a directory (yet)"));
254                    }
255                }
256                ActionConfig::Redirect { location, status } => {
257                    if location.is_empty() {
258                        report.error(format!("{label}: redirect action has no `location`"));
259                    }
260                    if !(300..=399).contains(status) {
261                        report.error(format!("{label}: redirect status {status} is not a 3xx code"));
262                    }
263                }
264                ActionConfig::Respond { status, .. } => {
265                    if !(100..=599).contains(status) {
266                        report.error(format!("{label}: respond status {status} is not an HTTP status code"));
267                    }
268                }
269                ActionConfig::Mcp(gateway) => {
270                    super::mcp_gateway::validate(gateway, route.match_.path.as_deref(), &label, report);
271                }
272                ActionConfig::Llm(llm) => {
273                    super::llm::validate(llm, &label, report);
274                }
275                ActionConfig::Unknown(kind) if kind.is_empty() => {
276                    report.error(format!("{label}: [route.action] has no `type`"));
277                }
278                ActionConfig::Unknown(kind) => {
279                    report.error(format!("{label}: unknown action type '{kind}' (expected proxy, grpc, static, redirect, respond, mcp or llm)"));
280                }
281            }
282            validate_middleware(&label, &route.middleware, report);
283
284            let m = &route.match_;
285            if m.host.is_none() && m.path.is_none() && m.method.is_none() && m.content_type.is_none() && i + 1 < self.routes.len() {
286                report.warn(format!("{label}: matches every request, so the routes after it are never reached"));
287            }
288        }
289
290        validate_middleware("[middleware]", &self.global_middleware, report);
291
292        let listeners = self.tcp_proxies.iter().map(|p| ("tcp_proxy", &p.name, &p.listen, &p.backends))
293            .chain(self.udp_proxies.iter().map(|p| ("udp_proxy", &p.name, &p.listen, &p.backends)))
294            .chain(self.ws_proxies.iter().map(|p| ("ws_proxy", &p.name, &p.listen, &p.backends)));
295        for (kind, name, listen, backends) in listeners {
296            let label = format!("[[{kind}]] '{name}'");
297            if listen.parse::<std::net::SocketAddr>().is_err() {
298                report.error(format!("{label}: listen '{listen}' is not an address like 0.0.0.0:5432"));
299            }
300            if backends.is_empty() {
301                report.error(format!("{label}: `backends` is empty"));
302            }
303            for backend in backends {
304                if !is_host_port(backend) {
305                    report.error(format!("{label}: backend '{backend}' is not host:port"));
306                }
307            }
308        }
309    }
310}
311
312fn validate_middleware(label: &str, mw: &MiddlewareConfig, report: &mut ConfigReport) {
313    match &mw.auth {
314        Some(AuthConfig::Bearer { token_env }) | Some(AuthConfig::Jwt { secret_env: token_env }) => {
315            if token_env.is_empty() {
316                report.error(format!("{label}: auth has no `token_env` / `secret_env`; the route answers 503"));
317            } else if !crate::config_check::offline() && std::env::var(token_env).unwrap_or_default().is_empty() {
318                report.error(format!("{label}: auth secret env var '{token_env}' is unset or empty; the route answers 503 until it is set"));
319            }
320        }
321        Some(AuthConfig::Basic { htpasswd_file }) => {
322            #[cfg(feature = "auth")]
323            if !crate::config_check::offline() {
324                if let Err(e) = crate::auth::BasicAuthLayer::from_htpasswd_file(htpasswd_file) {
325                    report.error(format!("{label}: basic auth: {e}; the route answers 503"));
326                }
327            }
328            #[cfg(not(feature = "auth"))]
329            let _ = htpasswd_file;
330        }
331        None => {}
332    }
333    #[cfg(not(feature = "auth"))]
334    if matches!(mw.auth, Some(AuthConfig::Jwt { .. }) | Some(AuthConfig::Basic { .. })) {
335        report.error(format!("{label}: jwt and basic auth need the `auth` feature, which this build doesn't include; the route answers 503"));
336    }
337
338    for entry in mw.ip_allow.iter().chain(&mw.ip_deny) {
339        if !crate::ip_filter::is_valid_entry(entry) {
340            report.error(format!("{label}: ip_filter entry '{entry}' is not an IP address or CIDR range — ignored"));
341        }
342    }
343    if !mw.ip_allow.is_empty() && !mw.ip_deny.is_empty() {
344        report.warn(format!("{label}: ip_filter has both `allow` and `deny`; only `allow` is used"));
345    }
346    if let Some(rl) = &mw.rate_limit {
347        if rl.max_requests == 0 || rl.window_secs == 0 {
348            report.error(format!("{label}: rate_limit needs max_requests and window_secs above 0"));
349        }
350    }
351    for rule in mw.rewrite_request.iter().chain(&mw.rewrite_response) {
352        let known = ["header_set", "header_remove", "uri_set", "uri_strip_prefix", "strip_prefix",
353                     "uri_add_prefix", "add_prefix", "status", "body_replace"];
354        if !known.contains(&rule.type_.as_str()) {
355            report.error(format!("{label}: unknown rewrite rule type '{}' — ignored", rule.type_));
356        }
357    }
358}