Skip to main content

rust_web_server/proxy_config/
builder.rs

1//! Builder: converts a `ProxyConfig` into a live `ConfigDrivenApp` with
2//! health checkers and L4/WS proxy threads.
3
4use std::collections::HashMap;
5use std::sync::atomic::AtomicBool;
6use std::sync::{Arc, RwLock};
7
8use crate::middleware::WithMiddleware;
9use crate::proxy_config::{
10    ActionConfig, AuthConfig, CompiledRoute, ConfigDrivenApp, DynamicProxy, MiddlewareConfig,
11    ProxyConfig, RedirectAdapter, RespondAdapter, RouteMatcher, StaticAdapter, arc_app,
12    AuthMisconfigured, BearerAuthMiddleware, PerRouteMaxBodySize, PerRouteRateLimit,
13};
14
15/// Build a `ConfigDrivenApp` from `rws.config.toml` and spawn L4/WS proxy
16/// threads. Returns the app and a list of background thread handles.
17/// Problems `ProxyConfig::validate` finds are printed first (the same
18/// findings `rws --check` reports). The returned app reloads its routes when
19/// the configuration is reloaded (`SIGHUP`, `POST /admin/config/reload`) —
20/// see [`ConfigDrivenApp::reload_from_file`].
21pub fn build_from_file() -> (ConfigDrivenApp, Vec<std::thread::JoinHandle<()>>) {
22    let source = std::fs::read_to_string(crate::proxy_config::config_file_path()).unwrap_or_default();
23    let config = ProxyConfig::from_str(&source);
24    let mut report = crate::config_check::ConfigReport::default();
25    config.validate(&mut report);
26    for e in &report.errors {
27        eprintln!("[proxy_config] ERROR: {e}");
28    }
29    for w in &report.warnings {
30        eprintln!("[proxy_config] Warning: {w}");
31    }
32    let (app, handles) = build_with_source(config, Some(source));
33    let reloadable = app.clone();
34    crate::config_reload::on_reload(move || reloadable.reload_from_file());
35    (app, handles)
36}
37
38/// Build a `ConfigDrivenApp` from a `ProxyConfig` struct.
39pub fn build(config: ProxyConfig) -> (ConfigDrivenApp, Vec<std::thread::JoinHandle<()>>) {
40    build_with_source(config, None)
41}
42
43fn build_with_source(config: ProxyConfig, source: Option<String>) -> (ConfigDrivenApp, Vec<std::thread::JoinHandle<()>>) {
44    let health_stop = Arc::new(AtomicBool::new(false));
45    let compiled = compile_routes(&config, &health_stop);
46    let handles = spawn_listeners(&config);
47    (ConfigDrivenApp::new(compiled, config, health_stop, source), handles)
48}
49
50/// Compile `config`'s routes and start health checkers for its upstreams;
51/// the checkers stop when `health_stop` is set. Used at startup and on every
52/// hot reload.
53pub(crate) fn compile_routes(config: &ProxyConfig, health_stop: &Arc<AtomicBool>) -> Vec<CompiledRoute> {
54    // ── 0. The [authz] authorizer, for routes' authz middleware ─────────────
55    let authorizer = config_authorizer(config);
56    if let Some(Err(e)) = &authorizer {
57        eprintln!("[proxy_config] ERROR: [authz]: {e} — routes with authz answer 503 until it's fixed.");
58    }
59    crate::authz::config::set_current(authorizer);
60    // ── 1. Build upstream name → live backends map ─────────────────────────
61    let mut upstream_lives: HashMap<String, Arc<RwLock<Vec<String>>>> = HashMap::new();
62    // tls_ca_file trust settings per upstream, loaded once per compile (so a
63    // reload picks up a rotated CA). A CA file that can't be loaded fails
64    // closed: every handshake fails (502) instead of trusting public CAs.
65    let mut upstream_trust: HashMap<String, Arc<crate::proxy::UpstreamTls>> = HashMap::new();
66    // Weights, stickiness, circuit breaker, retries: one state per
67    // upstream, shared by its routes.
68    let mut upstream_policies: HashMap<String, Arc<crate::proxy_config::upstream::UpstreamPolicy>> = HashMap::new();
69
70    for upstream in &config.upstreams {
71        let live = Arc::new(RwLock::new(upstream.backends.clone()));
72        upstream_lives.insert(upstream.name.clone(), Arc::clone(&live));
73        upstream_policies.insert(
74            upstream.name.clone(),
75            Arc::new(crate::proxy_config::upstream::UpstreamPolicy::new(
76                &upstream.name,
77                Arc::clone(&live),
78                &upstream.backends,
79                &upstream.weights,
80                upstream.sticky.clone(),
81                upstream.circuit_breaker.as_ref(),
82                upstream.retry.clone(),
83            )),
84        );
85
86        let client = upstream.tls_client_cert_file.as_deref().zip(upstream.tls_client_key_file.as_deref());
87        let configured = upstream.tls_ca_file.is_some() || upstream.tls_client_cert_file.is_some() || upstream.tls_client_key_file.is_some();
88        let trust = configured.then(|| {
89            Arc::new(crate::proxy::UpstreamTls::new(upstream.tls_ca_file.as_deref(), client).unwrap_or_else(|e| {
90                eprintln!("[proxy_config] ERROR: upstream '{}': {e} — its TLS backends answer 502 until this is fixed", upstream.name);
91                crate::proxy::UpstreamTls::reject_all(&upstream.name)
92            }))
93        });
94        if let Some(trust) = &trust {
95            upstream_trust.insert(upstream.name.clone(), Arc::clone(trust));
96        }
97
98        if let Some(ref hc) = upstream.health_check {
99            crate::proxy_config::health::start_health_checker(
100                upstream.name.clone(),
101                upstream.backends.clone(),
102                Arc::clone(&live),
103                hc.clone(),
104                Arc::clone(health_stop),
105                trust,
106            );
107        }
108    }
109
110    crate::proxy_config::upstream::register(upstream_policies.values().cloned().collect());
111
112    // ── 2. Build compiled routes ───────────────────────────────────────────
113    let mut caches: Vec<(String, crate::cache::CacheLayer)> = Vec::new();
114    let mut compiled: Vec<CompiledRoute> = Vec::new();
115
116    for route in &config.routes {
117        let matcher = RouteMatcher::from_match_config(&route.match_);
118
119        let mut async_proxy: Option<Arc<DynamicProxy>> = None;
120        let cache_name = format!("route:{}", if route.name.is_empty() { format!("#{}", compiled.len() + 1) } else { route.name.clone() });
121        let mirror = route.middleware.mirror.as_ref().map(|m| build_mirror(&route.name, m, &upstream_lives));
122
123        // Build the action handler (base application)
124        let base_handler: Arc<dyn crate::application::Application + Send + Sync> =
125            match &route.action {
126                ActionConfig::Proxy {
127                    upstream,
128                    connect_timeout_ms,
129                    read_timeout_ms,
130                    strip_path_prefix,
131                    add_path_prefix,
132                } => {
133                    let live = upstream_lives
134                        .get(upstream.as_str())
135                        .cloned()
136                        .unwrap_or_else(|| {
137                            // Fallback: upstream not declared, use name as single backend
138                            Arc::new(RwLock::new(vec![upstream.clone()]))
139                        });
140                    let upstream_cfg = config.upstreams.iter().find(|u| u.name == *upstream);
141                    let upstream_tls = upstream_cfg.map_or_else(|| upstream.starts_with("https://"), |u| u.tls);
142                    let upstream_strategy = upstream_cfg
143                        .map(|u| u.strategy.clone())
144                        .unwrap_or_else(|| "round_robin".to_string());
145                    let proxy = Arc::new(DynamicProxy::new(
146                        live,
147                        *connect_timeout_ms,
148                        *read_timeout_ms,
149                        strip_path_prefix.clone(),
150                        add_path_prefix.clone(),
151                        upstream_tls,
152                        upstream_strategy,
153                    )
154                    .with_trust(upstream_trust.get(upstream.as_str()).cloned())
155                    .with_policy(upstream, upstream_policies.get(upstream.as_str()).cloned())
156                    .with_mirror(mirror.clone())
157                    .with_early_hints(&route.middleware.early_hints)
158                    .with_h3(upstream_cfg.is_some_and(|u| u.protocol.eq_ignore_ascii_case("h3"))));
159                    if proxy.supports_async() && route.middleware.is_empty() {
160                        async_proxy = Some(Arc::clone(&proxy));
161                    }
162                    proxy
163                }
164
165                ActionConfig::Redirect { location, status } => {
166                    arc_app(RedirectAdapter::new(location.clone(), *status))
167                }
168
169                ActionConfig::Respond { status, body, content_type } => {
170                    arc_app(RespondAdapter::new(*status, body.clone(), content_type.clone()))
171                }
172
173                ActionConfig::Static { root, index } => {
174                    arc_app(StaticAdapter::new(root.clone(), index.clone()))
175                }
176
177                // Grpc action: HTTP/2 to the upstream (HTTP/1.1 only in builds
178                // without the http2 feature, where gRPC can't work anyway).
179                ActionConfig::Grpc { upstream, connect_timeout_ms, read_timeout_ms } => {
180                    let live = upstream_lives
181                        .get(upstream.as_str())
182                        .cloned()
183                        .unwrap_or_else(|| Arc::new(RwLock::new(vec![upstream.clone()])));
184                    let upstream_cfg = config.upstreams.iter().find(|u| u.name == *upstream);
185                    let upstream_tls = upstream_cfg.map_or_else(|| upstream.starts_with("https://"), |u| u.tls);
186                    #[cfg(feature = "http2")]
187                    {
188                        let _ = upstream_cfg;
189                        arc_app(crate::proxy_config::H2Route::new(
190                            live,
191                            upstream_tls,
192                            upstream_trust.get(upstream.as_str()).cloned(),
193                            *connect_timeout_ms,
194                            *read_timeout_ms,
195                        ))
196                    }
197                    #[cfg(not(feature = "http2"))]
198                    {
199                        let upstream_strategy = upstream_cfg
200                            .map(|u| u.strategy.clone())
201                            .unwrap_or_else(|| "round_robin".to_string());
202                        arc_app(
203                            DynamicProxy::new(live, *connect_timeout_ms, *read_timeout_ms, None, None, upstream_tls, upstream_strategy)
204                                .with_trust(upstream_trust.get(upstream.as_str()).cloned())
205                                .with_policy(upstream, upstream_policies.get(upstream.as_str()).cloned()),
206                        )
207                    }
208                }
209
210                ActionConfig::Mcp(gateway) => arc_app(crate::proxy_config::mcp_gateway::GatewayAdapter::start(
211                    (**gateway).clone(),
212                    route.match_.path.clone().unwrap_or_else(|| "/mcp".to_string()),
213                )),
214                ActionConfig::Llm(llm) => arc_app(crate::proxy_config::llm::build(llm)),
215                ActionConfig::Unknown(_) => {
216                    // No-op: these fall through to fallback
217                    arc_app(crate::proxy_config::NullApp)
218                }
219            };
220
221        // Wrap the base handler with middleware layers. A proxy route sends
222        // its mirror copies and early hints itself (so it keeps the async
223        // forwarder); any other action gets a MirrorLayer / EarlyHintsLayer.
224        let mut handler = apply_middleware_named(base_handler, &route.middleware, &cache_name, &mut caches);
225        if !matches!(route.action, ActionConfig::Proxy { .. }) {
226            if let Some(mirror) = &mirror {
227                handler = arc_app(WithMiddleware::new(ArcApp(handler)).wrap(crate::proxy::mirror::MirrorLayer::new(mirror.clone())));
228            }
229            if !route.middleware.early_hints.is_empty() {
230                let layer = crate::early_hints::EarlyHintsLayer::new(route.middleware.early_hints.iter().cloned());
231                handler = arc_app(WithMiddleware::new(ArcApp(handler)).wrap(layer));
232            }
233        }
234
235        compiled.push(CompiledRoute { matcher, handler, async_proxy });
236    }
237    crate::cache::registry::replace_group("route:", caches);
238    compiled
239}
240
241/// Start the `[[tcp_proxy]]` / `[[udp_proxy]]` / `[[ws_proxy]]` listeners.
242/// Startup only: a hot reload can't move bound sockets, so changes to these
243/// sections need a restart.
244fn spawn_listeners(config: &ProxyConfig) -> Vec<std::thread::JoinHandle<()>> {
245    let mut handles: Vec<std::thread::JoinHandle<()>> = Vec::new();
246
247    for tcp_cfg in &config.tcp_proxies {
248        let listen = tcp_cfg.listen.clone();
249        let backends = tcp_cfg.backends.clone();
250        let timeout_ms = tcp_cfg.connect_timeout_ms;
251        let name = tcp_cfg.name.clone();
252        let h = std::thread::Builder::new()
253            .name(format!("tcp-proxy-{}", name))
254            .spawn(move || {
255                let proxy = crate::tcp_proxy::TcpProxy::new(backends)
256                    .connect_timeout_ms(timeout_ms);
257                if let Err(e) = proxy.bind(&listen) {
258                    eprintln!("[tcp_proxy:{}] {}", name, e);
259                }
260            })
261            .expect("failed to spawn tcp proxy thread");
262        handles.push(h);
263    }
264
265    for udp_cfg in &config.udp_proxies {
266        let listen = udp_cfg.listen.clone();
267        let backends = udp_cfg.backends.clone();
268        let reply_timeout_ms = udp_cfg.reply_timeout_ms;
269        let buffer_size = udp_cfg.buffer_size;
270        let name = udp_cfg.name.clone();
271        let h = std::thread::Builder::new()
272            .name(format!("udp-proxy-{}", name))
273            .spawn(move || {
274                let proxy = crate::udp_proxy::UdpProxy::new(backends)
275                    .reply_timeout_ms(reply_timeout_ms)
276                    .buffer_size(buffer_size);
277                if let Err(e) = proxy.bind(&listen) {
278                    eprintln!("[udp_proxy:{}] {}", name, e);
279                }
280            })
281            .expect("failed to spawn udp proxy thread");
282        handles.push(h);
283    }
284
285    for ws_cfg in &config.ws_proxies {
286        let listen = ws_cfg.listen.clone();
287        let backends = ws_cfg.backends.clone();
288        let connect_timeout_ms = ws_cfg.connect_timeout_ms;
289        let read_timeout_ms = ws_cfg.read_timeout_ms;
290        let name = ws_cfg.name.clone();
291
292        // With a health check configured, share a live-backend list with a
293        // background checker thread (same mechanism `[[upstream]]` pools
294        // use) instead of treating every configured backend as always live.
295        let live = Arc::new(RwLock::new(backends.clone()));
296        if let Some(ref hc) = ws_cfg.health_check {
297            crate::proxy_config::health::start_health_checker(
298                name.clone(),
299                backends.clone(),
300                Arc::clone(&live),
301                hc.clone(),
302                Arc::new(AtomicBool::new(false)),
303                None,
304            );
305        }
306
307        let h = std::thread::Builder::new()
308            .name(format!("ws-proxy-{}", name))
309            .spawn(move || {
310                let proxy = crate::ws_proxy::WsProxy::with_live_backends(backends, live)
311                    .connect_timeout_ms(connect_timeout_ms)
312                    .read_timeout_ms(read_timeout_ms);
313                if let Err(e) = proxy.bind(&listen) {
314                    eprintln!("[ws_proxy:{}] {}", name, e);
315                }
316            })
317            .expect("failed to spawn ws proxy thread");
318        handles.push(h);
319    }
320
321    handles
322}
323
324/// Wrap `handler` with the middleware layers described by `mw`, innermost
325/// (closest to the handler) to outermost (runs first, on every request):
326///
327///   1. Cache (innermost)
328///   2. Rewrite (request + response rules combined)
329///   3. Auth
330///   4. Rate limit
331///   5. IP filter
332///   6. Timeout — bounds this route's total time, including every layer above
333///   7. Max body size (outermost) — a fast, non-blocking length check, so a
334///      request this route will reject outright doesn't pay for a timeout
335///      wrapper (which runs its target on a background thread) or engage
336///      any other layer at all
337/// A route's mirror: a declared upstream's live backends, or its own list.
338fn build_mirror(route: &str, config: &crate::proxy_config::MirrorConfig, lives: &HashMap<String, Arc<RwLock<Vec<String>>>>) -> crate::proxy::mirror::Mirror {
339    let name = if config.upstream.is_empty() { format!("{route}-mirror") } else { config.upstream.clone() };
340    let mirror = match lives.get(&config.upstream) {
341        Some(live) if !config.upstream.is_empty() => crate::proxy::mirror::Mirror::with_live_backends(name, Arc::clone(live)),
342        _ if !config.upstream.is_empty() => crate::proxy::mirror::Mirror::new(name, vec![config.upstream.clone()]),
343        _ => crate::proxy::mirror::Mirror::new(name, config.backends.clone()),
344    };
345    mirror.percent(if config.percent.is_finite() { config.percent } else { 0.0 })
346}
347
348pub(crate) fn apply_middleware(
349    handler: Arc<dyn crate::application::Application + Send + Sync>,
350    mw: &MiddlewareConfig,
351) -> Arc<dyn crate::application::Application + Send + Sync> {
352    apply_middleware_named(handler, mw, "middleware", &mut Vec::new())
353}
354
355/// [`apply_middleware`], recording the route's cache (if any) as `name`
356/// in `caches` for the admin API's registry.
357pub(crate) fn apply_middleware_named(
358    handler: Arc<dyn crate::application::Application + Send + Sync>,
359    mw: &MiddlewareConfig,
360    name: &str,
361    caches: &mut Vec<(String, crate::cache::CacheLayer)>,
362) -> Arc<dyn crate::application::Application + Send + Sync> {
363    // Wrap the Arc<dyn Application> in an ArcApp adapter so it implements
364    // Application itself (needed for WithMiddleware::new).
365    let mut app: Arc<dyn crate::application::Application + Send + Sync> = handler;
366
367    // ── Cache (applied first so it's the innermost middleware) ─────────────
368    if let Some(ref cache_cfg) = mw.cache {
369        let mut layer = if cache_cfg.dir.is_empty() {
370            crate::cache::CacheLayer::memory(1000)
371        } else {
372            let max = crate::proxy_config::cache_max_bytes(&cache_cfg.max_size).unwrap_or(256 * 1024 * 1024);
373            crate::cache::CacheLayer::disk(&cache_cfg.dir, max).unwrap_or_else(|e| {
374                eprintln!("[proxy_config] ERROR: cache dir {}: {e} — this route caches in memory instead", cache_cfg.dir);
375                crate::cache::CacheLayer::memory(1000)
376            })
377        }
378        .ttl(cache_cfg.ttl_secs);
379        if !cache_cfg.purge_token_env.is_empty() {
380            layer = layer.purge_token(std::env::var(&cache_cfg.purge_token_env).unwrap_or_default().trim());
381        }
382        caches.push((name.to_string(), layer.clone()));
383        for vh in &cache_cfg.vary_by {
384            layer = layer.vary_by_header(vh.as_str());
385        }
386        app = arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(layer));
387    }
388
389    // ── Rewrite ────────────────────────────────────────────────────────────
390    if !mw.rewrite_request.is_empty() || !mw.rewrite_response.is_empty() {
391        let mut layer = crate::rewrite::RewriteLayer::new();
392        for rule in &mw.rewrite_request {
393            layer = apply_request_rewrite_rule(layer, rule);
394        }
395        for rule in &mw.rewrite_response {
396            layer = apply_response_rewrite_rule(layer, rule);
397        }
398        app = arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(layer));
399    }
400
401    // ── WebAssembly plugin (inside auth: it sees authenticated requests) ──
402    if let Some(ref wasm) = mw.wasm {
403        #[cfg(feature = "wasm-plugins")]
404        let layer = crate::wasm_plugin::WasmLayer::from_file(&wasm.module)
405            .map(|l| l.fuel(wasm.fuel).memory_mb(wasm.memory_mb).config(wasm.config.clone()));
406        #[cfg(not(feature = "wasm-plugins"))]
407        let layer: Result<crate::proxy_config::PluginMisconfigured, String> =
408            Err(format!("plugin {}: this rws binary was built without the wasm-plugins feature", wasm.module));
409        app = match layer {
410            Ok(layer) => arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(layer)),
411            Err(e) => {
412                eprintln!("[proxy_config] ERROR: {e} — this route answers 503 until the plugin is fixed.");
413                arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(crate::proxy_config::PluginMisconfigured))
414            }
415        };
416    }
417
418    // ── Authorization (inside auth, which sets the caller) ─────────────────
419    if let Some(ref rule) = mw.authz {
420        let layer = match crate::authz::config::current() {
421            Some(Ok(authorizer)) => crate::authz::AuthzLayer::new(authorizer, &rule.relation, &rule.object),
422            Some(Err(e)) => Err(format!("[authz] couldn't be built: {e}")),
423            None => Err("the route has [route.middleware.authz] but there's no [authz] section".to_string()),
424        };
425        app = match layer {
426            Ok(layer) => arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(layer)),
427            Err(e) => {
428                eprintln!("[proxy_config] ERROR: authz: {e} — this route answers 503 until it's fixed.");
429                arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(AuthMisconfigured))
430            }
431        };
432    }
433
434    // ── Auth ───────────────────────────────────────────────────────────────
435    // Fails closed: an auth setting that can't be honoured (secret unset,
436    // htpasswd missing, feature not compiled in) puts AuthMisconfigured in
437    // front of the route instead of silently serving it unauthenticated.
438    if let Some(ref auth_cfg) = mw.auth {
439        let deny = |reason: String| -> Arc<dyn crate::application::Application + Send + Sync> {
440            eprintln!(
441                "[proxy_config] ERROR: {reason} — this route answers 503 until the auth configuration is fixed."
442            );
443            arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(AuthMisconfigured))
444        };
445        app = match auth_cfg {
446            AuthConfig::Bearer { token_env } => {
447                let token = std::env::var(token_env).unwrap_or_default();
448                if token.is_empty() {
449                    deny(format!("bearer auth: env var '{token_env}' is unset or empty"))
450                } else {
451                    arc_app(
452                        WithMiddleware::new(ArcApp(Arc::clone(&app)))
453                            .wrap(BearerAuthMiddleware { token: Arc::new(token) }),
454                    )
455                }
456            }
457            #[cfg(feature = "auth")]
458            AuthConfig::Jwt { secret_env } => {
459                let secret = std::env::var(secret_env).unwrap_or_default();
460                if secret.is_empty() {
461                    deny(format!("JWT auth: env var '{secret_env}' is unset or empty"))
462                } else {
463                    arc_app(
464                        WithMiddleware::new(ArcApp(Arc::clone(&app)))
465                            .wrap(crate::auth::JwtLayer::new(secret)),
466                    )
467                }
468            }
469            #[cfg(not(feature = "auth"))]
470            AuthConfig::Jwt { .. } => {
471                deny("JWT auth requires the 'auth' feature, which this build doesn't include".to_string())
472            }
473            #[cfg(feature = "auth")]
474            AuthConfig::Basic { htpasswd_file } => {
475                match crate::auth::BasicAuthLayer::from_htpasswd_file(htpasswd_file) {
476                    Ok(layer) => arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(layer)),
477                    Err(e) => deny(format!("basic auth: {e}")),
478                }
479            }
480            #[cfg(not(feature = "auth"))]
481            AuthConfig::Basic { .. } => {
482                deny("basic auth requires the 'auth' feature, which this build doesn't include".to_string())
483            }
484        };
485    }
486
487    // ── Rate limit ─────────────────────────────────────────────────────────
488    if let Some(ref rl_cfg) = mw.rate_limit {
489        let limiter = Arc::new(crate::rate_limit::RateLimiter::new(
490            rl_cfg.max_requests,
491            rl_cfg.window_secs,
492        ));
493        app = arc_app(
494            WithMiddleware::new(ArcApp(Arc::clone(&app)))
495                .wrap(PerRouteRateLimit(limiter)),
496        );
497    }
498
499    // ── IP filter ────────────────────────────────────────────────────────────
500    if !mw.ip_allow.is_empty() {
501        let filter = crate::ip_filter::IpFilter::allow(mw.ip_allow.iter().map(|s| s.as_str()));
502        app = arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(filter));
503    } else if !mw.ip_deny.is_empty() {
504        let filter = crate::ip_filter::IpFilter::deny(mw.ip_deny.iter().map(|s| s.as_str()));
505        app = arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(filter));
506    }
507
508    // ── Timeout (bounds this route's total time, including every other
509    // middleware above) ─────────────────────────────────────────────────────
510    if let Some(timeout_ms) = mw.timeout_ms {
511        app = arc_app(crate::timeout::TimeoutLayer::from_arc(
512            app,
513            std::time::Duration::from_millis(timeout_ms),
514        ));
515    }
516
517    // ── Max body size (outermost — see PerRouteMaxBodySize's docs for why
518    // this is not a substitute for RWS_CONFIG_MAX_BODY_SIZE_IN_BYTES) ──────
519    if let Some(max_body_size) = mw.max_body_size {
520        app = arc_app(
521            WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(PerRouteMaxBodySize(max_body_size)),
522        );
523    }
524
525    app
526}
527
528fn apply_request_rewrite_rule(
529    layer: crate::rewrite::RewriteLayer,
530    rule: &crate::proxy_config::RewriteRuleConfig,
531) -> crate::rewrite::RewriteLayer {
532    match rule.type_.as_str() {
533        "header_set" => {
534            if let (Some(name), Some(value)) = (&rule.name, &rule.value) {
535                return layer.request_header_set(name, value);
536            }
537        }
538        "header_remove" => {
539            if let Some(name) = &rule.name {
540                return layer.request_header_remove(name);
541            }
542        }
543        "uri_set" => {
544            if let Some(value) = &rule.value {
545                return layer.request_uri_set(value);
546            }
547        }
548        "uri_strip_prefix" | "strip_prefix" => {
549            if let Some(prefix) = rule.prefix.as_ref().or(rule.value.as_ref()) {
550                return layer.request_uri_strip_prefix(prefix);
551            }
552        }
553        "uri_add_prefix" | "add_prefix" => {
554            if let Some(prefix) = rule.prefix.as_ref().or(rule.value.as_ref()) {
555                return layer.request_uri_add_prefix(prefix);
556            }
557        }
558        _ => {}
559    }
560    layer
561}
562
563fn apply_response_rewrite_rule(
564    layer: crate::rewrite::RewriteLayer,
565    rule: &crate::proxy_config::RewriteRuleConfig,
566) -> crate::rewrite::RewriteLayer {
567    match rule.type_.as_str() {
568        "header_set" => {
569            if let (Some(name), Some(value)) = (&rule.name, &rule.value) {
570                return layer.response_header_set(name, value);
571            }
572        }
573        "header_remove" => {
574            if let Some(name) = &rule.name {
575                return layer.response_header_remove(name);
576            }
577        }
578        "status" => {
579            if let (Some(code), Some(reason)) = (&rule.code, &rule.reason) {
580                return layer.response_status(*code as i16, reason);
581            }
582        }
583        "body_replace" => {
584            if let (Some(from), Some(to)) = (&rule.from, &rule.to) {
585                return layer.response_body_replace(from, to);
586            }
587        }
588        _ => {}
589    }
590    layer
591}
592
593// ── ArcApp adapter ─────────────────────────────────────────────────────────────
594
595/// Wraps `Arc<dyn Application + Send + Sync>` to implement `Application`
596/// (needed because you can't implement a foreign trait on a foreign type).
597pub(crate) struct ArcApp(pub(crate) Arc<dyn crate::application::Application + Send + Sync>);
598
599impl crate::application::Application for ArcApp {
600    fn execute(
601        &self,
602        request: &crate::request::Request,
603        conn: &crate::server::ConnectionInfo,
604    ) -> Result<crate::response::Response, String> {
605        self.0.execute(request, conn)
606    }
607
608    fn streams_body(&self, request: &crate::request::Request, conn: &crate::server::ConnectionInfo) -> bool {
609        self.0.streams_body(request, conn)
610    }
611}
612
613impl Clone for ArcApp {
614    fn clone(&self) -> Self {
615        ArcApp(Arc::clone(&self.0))
616    }
617}
618
619/// The authorizer `[authz]` describes: its schema, the process-wide tuple
620/// store, the seed tuples written. `None` without `[authz]`.
621pub(crate) fn config_authorizer(config: &ProxyConfig) -> Option<Result<crate::authz::Authorizer, String>> {
622    config_authorizer_with(config, None)
623}
624
625/// [`config_authorizer`], or over `check_store` whatever `store` says — a
626/// throwaway store for `rws --check`, which must not connect or write.
627pub(crate) fn config_authorizer_with(
628    config: &ProxyConfig,
629    check_store: Option<Arc<dyn crate::authz::TupleStore>>,
630) -> Option<Result<crate::authz::Authorizer, String>> {
631    let authz = config.authz.as_ref()?;
632    Some((|| {
633        let mut schema = crate::authz::Schema::new();
634        for (kind, relations) in &authz.types {
635            schema = if relations.is_empty() { schema.object_type(kind) } else { Ok(schema) }.map_err(|e| e.to_string())?;
636            for (relation, definition) in relations {
637                schema = schema.relation(kind, relation, definition).map_err(|e| format!("type {kind}, relation {relation}: {e}"))?;
638            }
639        }
640        let store = match (authz.store.as_str(), check_store) {
641            ("" | "memory" | "sql", Some(store)) => store,
642            ("" | "memory", None) => crate::authz::config::memory_store(),
643            #[cfg(any(feature = "model-sqlite", feature = "model-postgres", feature = "model-mysql"))]
644            ("sql", None) => crate::authz::sql::config_store()?,
645            #[cfg(not(any(feature = "model-sqlite", feature = "model-postgres", feature = "model-mysql")))]
646            ("sql", None) => return Err("store = \"sql\" needs a build with a model-sqlite / model-postgres / model-mysql feature".to_string()),
647            (other, _) => return Err(format!("store = \"{other}\" isn't supported (memory or sql)")),
648        };
649        let authorizer = crate::authz::Authorizer::with_store(schema, store).map_err(|e| e.to_string())?;
650        for tuple in &authz.tuples {
651            authorizer.write_str(tuple).map_err(|e| format!("tuple {tuple:?}: {e}"))?;
652        }
653        Ok(authorizer)
654    })())
655}