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                    upstream_host,
133                } => {
134                    let live = upstream_lives
135                        .get(upstream.as_str())
136                        .cloned()
137                        .unwrap_or_else(|| {
138                            // Fallback: upstream not declared, use name as single backend
139                            Arc::new(RwLock::new(vec![upstream.clone()]))
140                        });
141                    let upstream_cfg = config.upstreams.iter().find(|u| u.name == *upstream);
142                    let upstream_tls = upstream_cfg.map_or_else(|| upstream.starts_with("https://"), |u| u.tls);
143                    let upstream_strategy = upstream_cfg
144                        .map(|u| u.strategy.clone())
145                        .unwrap_or_else(|| "round_robin".to_string());
146                    let proxy = Arc::new(DynamicProxy::new(
147                        live,
148                        *connect_timeout_ms,
149                        *read_timeout_ms,
150                        strip_path_prefix.clone(),
151                        add_path_prefix.clone(),
152                        upstream_tls,
153                        upstream_strategy,
154                    )
155                    .with_trust(upstream_trust.get(upstream.as_str()).cloned())
156                    .with_policy(upstream, upstream_policies.get(upstream.as_str()).cloned())
157                    .with_mirror(mirror.clone())
158                    .with_early_hints(&route.middleware.early_hints)
159                    .with_h3(upstream_cfg.is_some_and(|u| u.protocol.eq_ignore_ascii_case("h3")))
160                    .with_upstream_host(upstream_host.clone()));
161                    if proxy.supports_async() && route.middleware.is_empty() {
162                        async_proxy = Some(Arc::clone(&proxy));
163                    }
164                    proxy
165                }
166
167                ActionConfig::Redirect { location, status } => {
168                    arc_app(RedirectAdapter::new(location.clone(), *status))
169                }
170
171                ActionConfig::Respond { status, body, content_type } => {
172                    arc_app(RespondAdapter::new(*status, body.clone(), content_type.clone()))
173                }
174
175                ActionConfig::Static { root, index } => {
176                    arc_app(StaticAdapter::new(root.clone(), index.clone()))
177                }
178
179                // Grpc action: HTTP/2 to the upstream (HTTP/1.1 only in builds
180                // without the http2 feature, where gRPC can't work anyway).
181                ActionConfig::Grpc { upstream, connect_timeout_ms, read_timeout_ms } => {
182                    let live = upstream_lives
183                        .get(upstream.as_str())
184                        .cloned()
185                        .unwrap_or_else(|| Arc::new(RwLock::new(vec![upstream.clone()])));
186                    let upstream_cfg = config.upstreams.iter().find(|u| u.name == *upstream);
187                    let upstream_tls = upstream_cfg.map_or_else(|| upstream.starts_with("https://"), |u| u.tls);
188                    #[cfg(feature = "http2")]
189                    {
190                        let _ = upstream_cfg;
191                        arc_app(crate::proxy_config::H2Route::new(
192                            live,
193                            upstream_tls,
194                            upstream_trust.get(upstream.as_str()).cloned(),
195                            *connect_timeout_ms,
196                            *read_timeout_ms,
197                        ))
198                    }
199                    #[cfg(not(feature = "http2"))]
200                    {
201                        let upstream_strategy = upstream_cfg
202                            .map(|u| u.strategy.clone())
203                            .unwrap_or_else(|| "round_robin".to_string());
204                        arc_app(
205                            DynamicProxy::new(live, *connect_timeout_ms, *read_timeout_ms, None, None, upstream_tls, upstream_strategy)
206                                .with_trust(upstream_trust.get(upstream.as_str()).cloned())
207                                .with_policy(upstream, upstream_policies.get(upstream.as_str()).cloned()),
208                        )
209                    }
210                }
211
212                ActionConfig::FastCgi(f) => {
213                    let mut cfg = crate::fastcgi::FastCgiConfig::new(f.address.clone(), f.root.clone());
214                    cfg.index = f.index.clone();
215                    cfg.split_path = f.split_path.clone();
216                    cfg.front_controller = f.front_controller.clone();
217                    cfg.params = f.params.clone();
218                    cfg.connect_timeout = std::time::Duration::from_millis(f.connect_timeout_ms);
219                    cfg.read_timeout = std::time::Duration::from_millis(f.read_timeout_ms);
220                    cfg.max_idle = f.max_idle as usize;
221                    match crate::fastcgi::FastCgi::new(cfg) {
222                        Ok(app) => arc_app(app.with_static(arc_app(StaticAdapter::new(f.root.clone(), Vec::new())))),
223                        Err(e) => {
224                            eprintln!("[config] route {cache_name}: {e}; it answers 502");
225                            arc_app(RespondAdapter::new(502, "Bad Gateway".to_string(), "text/plain".to_string()))
226                        }
227                    }
228                }
229                ActionConfig::Mcp(gateway) => arc_app(crate::proxy_config::mcp_gateway::GatewayAdapter::start(
230                    (**gateway).clone(),
231                    route.match_.path.clone().unwrap_or_else(|| "/mcp".to_string()),
232                )),
233                ActionConfig::Llm(llm) => arc_app(crate::proxy_config::llm::build(llm)),
234                ActionConfig::A2a(gateway) => arc_app(crate::proxy_config::a2a_gateway::A2aGateway::new(
235                    (**gateway).clone(),
236                    route.match_.path.as_deref().unwrap_or("/"),
237                )),
238                ActionConfig::Unknown(_) => {
239                    // No-op: these fall through to fallback
240                    arc_app(crate::proxy_config::NullApp)
241                }
242            };
243
244        // Wrap the base handler with middleware layers. A proxy route sends
245        // its mirror copies and early hints itself (so it keeps the async
246        // forwarder); any other action gets a MirrorLayer / EarlyHintsLayer.
247        let mut handler = apply_middleware_named(base_handler, &route.middleware, &cache_name, &mut caches);
248        if !matches!(route.action, ActionConfig::Proxy { .. }) {
249            if let Some(mirror) = &mirror {
250                handler = arc_app(WithMiddleware::new(ArcApp(handler)).wrap(crate::proxy::mirror::MirrorLayer::new(mirror.clone())));
251            }
252            if !route.middleware.early_hints.is_empty() {
253                let layer = crate::early_hints::EarlyHintsLayer::new(route.middleware.early_hints.iter().cloned());
254                handler = arc_app(WithMiddleware::new(ArcApp(handler)).wrap(layer));
255            }
256        }
257
258        compiled.push(CompiledRoute { matcher, handler, async_proxy });
259    }
260    crate::cache::registry::replace_group("route:", caches);
261    compiled
262}
263
264/// Start the `[[tcp_proxy]]` / `[[udp_proxy]]` / `[[ws_proxy]]` listeners.
265/// Startup only: a hot reload can't move bound sockets, so changes to these
266/// sections need a restart.
267fn spawn_listeners(config: &ProxyConfig) -> Vec<std::thread::JoinHandle<()>> {
268    let mut handles: Vec<std::thread::JoinHandle<()>> = Vec::new();
269
270    for tcp_cfg in &config.tcp_proxies {
271        let listen = tcp_cfg.listen.clone();
272        let backends = tcp_cfg.backends.clone();
273        let timeout_ms = tcp_cfg.connect_timeout_ms;
274        let name = tcp_cfg.name.clone();
275        let h = std::thread::Builder::new()
276            .name(format!("tcp-proxy-{}", name))
277            .spawn(move || {
278                let proxy = crate::tcp_proxy::TcpProxy::new(backends)
279                    .connect_timeout_ms(timeout_ms);
280                if let Err(e) = proxy.bind(&listen) {
281                    eprintln!("[tcp_proxy:{}] {}", name, e);
282                }
283            })
284            .expect("failed to spawn tcp proxy thread");
285        handles.push(h);
286    }
287
288    for udp_cfg in &config.udp_proxies {
289        let listen = udp_cfg.listen.clone();
290        let backends = udp_cfg.backends.clone();
291        let reply_timeout_ms = udp_cfg.reply_timeout_ms;
292        let buffer_size = udp_cfg.buffer_size;
293        let name = udp_cfg.name.clone();
294        let h = std::thread::Builder::new()
295            .name(format!("udp-proxy-{}", name))
296            .spawn(move || {
297                let proxy = crate::udp_proxy::UdpProxy::new(backends)
298                    .reply_timeout_ms(reply_timeout_ms)
299                    .buffer_size(buffer_size);
300                if let Err(e) = proxy.bind(&listen) {
301                    eprintln!("[udp_proxy:{}] {}", name, e);
302                }
303            })
304            .expect("failed to spawn udp proxy thread");
305        handles.push(h);
306    }
307
308    for ws_cfg in &config.ws_proxies {
309        let listen = ws_cfg.listen.clone();
310        let backends = ws_cfg.backends.clone();
311        let connect_timeout_ms = ws_cfg.connect_timeout_ms;
312        let read_timeout_ms = ws_cfg.read_timeout_ms;
313        let name = ws_cfg.name.clone();
314
315        // With a health check configured, share a live-backend list with a
316        // background checker thread (same mechanism `[[upstream]]` pools
317        // use) instead of treating every configured backend as always live.
318        let live = Arc::new(RwLock::new(backends.clone()));
319        if let Some(ref hc) = ws_cfg.health_check {
320            crate::proxy_config::health::start_health_checker(
321                name.clone(),
322                backends.clone(),
323                Arc::clone(&live),
324                hc.clone(),
325                Arc::new(AtomicBool::new(false)),
326                None,
327            );
328        }
329
330        let h = std::thread::Builder::new()
331            .name(format!("ws-proxy-{}", name))
332            .spawn(move || {
333                let proxy = crate::ws_proxy::WsProxy::with_live_backends(backends, live)
334                    .connect_timeout_ms(connect_timeout_ms)
335                    .read_timeout_ms(read_timeout_ms);
336                if let Err(e) = proxy.bind(&listen) {
337                    eprintln!("[ws_proxy:{}] {}", name, e);
338                }
339            })
340            .expect("failed to spawn ws proxy thread");
341        handles.push(h);
342    }
343
344    handles
345}
346
347/// Wrap `handler` with the middleware layers described by `mw`, innermost
348/// (closest to the handler) to outermost (runs first, on every request):
349///
350///   1. Cache (innermost)
351///   2. Rewrite (request + response rules combined)
352///   3. Auth
353///   4. Rate limit
354///   5. IP filter
355///   6. Timeout — bounds this route's total time, including every layer above
356///   7. Max body size (outermost) — a fast, non-blocking length check, so a
357///      request this route will reject outright doesn't pay for a timeout
358///      wrapper (which runs its target on a background thread) or engage
359///      any other layer at all
360/// A route's mirror: a declared upstream's live backends, or its own list.
361fn build_mirror(route: &str, config: &crate::proxy_config::MirrorConfig, lives: &HashMap<String, Arc<RwLock<Vec<String>>>>) -> crate::proxy::mirror::Mirror {
362    let name = if config.upstream.is_empty() { format!("{route}-mirror") } else { config.upstream.clone() };
363    let mirror = match lives.get(&config.upstream) {
364        Some(live) if !config.upstream.is_empty() => crate::proxy::mirror::Mirror::with_live_backends(name, Arc::clone(live)),
365        _ if !config.upstream.is_empty() => crate::proxy::mirror::Mirror::new(name, vec![config.upstream.clone()]),
366        _ => crate::proxy::mirror::Mirror::new(name, config.backends.clone()),
367    };
368    mirror.percent(if config.percent.is_finite() { config.percent } else { 0.0 })
369}
370
371pub(crate) fn apply_middleware(
372    handler: Arc<dyn crate::application::Application + Send + Sync>,
373    mw: &MiddlewareConfig,
374) -> Arc<dyn crate::application::Application + Send + Sync> {
375    apply_middleware_named(handler, mw, "middleware", &mut Vec::new())
376}
377
378/// [`apply_middleware`], recording the route's cache (if any) as `name`
379/// in `caches` for the admin API's registry.
380pub(crate) fn apply_middleware_named(
381    handler: Arc<dyn crate::application::Application + Send + Sync>,
382    mw: &MiddlewareConfig,
383    name: &str,
384    caches: &mut Vec<(String, crate::cache::CacheLayer)>,
385) -> Arc<dyn crate::application::Application + Send + Sync> {
386    // Wrap the Arc<dyn Application> in an ArcApp adapter so it implements
387    // Application itself (needed for WithMiddleware::new).
388    let mut app: Arc<dyn crate::application::Application + Send + Sync> = handler;
389
390    // ── Cache (applied first so it's the innermost middleware) ─────────────
391    if let Some(ref cache_cfg) = mw.cache {
392        let mut layer = if cache_cfg.dir.is_empty() {
393            crate::cache::CacheLayer::memory(1000)
394        } else {
395            let max = crate::proxy_config::cache_max_bytes(&cache_cfg.max_size).unwrap_or(256 * 1024 * 1024);
396            crate::cache::CacheLayer::disk(&cache_cfg.dir, max).unwrap_or_else(|e| {
397                eprintln!("[proxy_config] ERROR: cache dir {}: {e} — this route caches in memory instead", cache_cfg.dir);
398                crate::cache::CacheLayer::memory(1000)
399            })
400        }
401        .ttl(cache_cfg.ttl_secs);
402        if !cache_cfg.purge_token_env.is_empty() {
403            layer = layer.purge_token(std::env::var(&cache_cfg.purge_token_env).unwrap_or_default().trim());
404        }
405        caches.push((name.to_string(), layer.clone()));
406        for vh in &cache_cfg.vary_by {
407            layer = layer.vary_by_header(vh.as_str());
408        }
409        app = arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(layer));
410    }
411
412    // ── Rewrite ────────────────────────────────────────────────────────────
413    if !mw.rewrite_request.is_empty() || !mw.rewrite_response.is_empty() {
414        let mut layer = crate::rewrite::RewriteLayer::new();
415        for rule in &mw.rewrite_request {
416            layer = apply_request_rewrite_rule(layer, rule);
417        }
418        for rule in &mw.rewrite_response {
419            layer = apply_response_rewrite_rule(layer, rule);
420        }
421        app = arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(layer));
422    }
423
424    // ── WebAssembly plugin (inside auth: it sees authenticated requests) ──
425    if let Some(ref wasm) = mw.wasm {
426        #[cfg(feature = "wasm-plugins")]
427        let layer = crate::wasm_plugin::WasmLayer::from_file(&wasm.module)
428            .map(|l| l.fuel(wasm.fuel).memory_mb(wasm.memory_mb).config(wasm.config.clone()));
429        #[cfg(not(feature = "wasm-plugins"))]
430        let layer: Result<crate::proxy_config::PluginMisconfigured, String> =
431            Err(format!("plugin {}: this rws binary was built without the wasm-plugins feature", wasm.module));
432        app = match layer {
433            Ok(layer) => arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(layer)),
434            Err(e) => {
435                eprintln!("[proxy_config] ERROR: {e} — this route answers 503 until the plugin is fixed.");
436                arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(crate::proxy_config::PluginMisconfigured))
437            }
438        };
439    }
440
441    // ── Authorization (inside auth, which sets the caller) ─────────────────
442    if let Some(ref rule) = mw.authz {
443        let layer = match crate::authz::config::current() {
444            Some(Ok(authorizer)) => crate::authz::AuthzLayer::new(authorizer, &rule.relation, &rule.object),
445            Some(Err(e)) => Err(format!("[authz] couldn't be built: {e}")),
446            None => Err("the route has [route.middleware.authz] but there's no [authz] section".to_string()),
447        };
448        app = match layer {
449            Ok(layer) => arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(layer)),
450            Err(e) => {
451                eprintln!("[proxy_config] ERROR: authz: {e} — this route answers 503 until it's fixed.");
452                arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(AuthMisconfigured))
453            }
454        };
455    }
456
457    // ── Auth ───────────────────────────────────────────────────────────────
458    // Fails closed: an auth setting that can't be honoured (secret unset,
459    // htpasswd missing, feature not compiled in) puts AuthMisconfigured in
460    // front of the route instead of silently serving it unauthenticated.
461    if let Some(ref auth_cfg) = mw.auth {
462        let deny = |reason: String| -> Arc<dyn crate::application::Application + Send + Sync> {
463            eprintln!(
464                "[proxy_config] ERROR: {reason} — this route answers 503 until the auth configuration is fixed."
465            );
466            arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(AuthMisconfigured))
467        };
468        app = match auth_cfg {
469            AuthConfig::Bearer { token_env } => {
470                let token = std::env::var(token_env).unwrap_or_default();
471                if token.is_empty() {
472                    deny(format!("bearer auth: env var '{token_env}' is unset or empty"))
473                } else {
474                    arc_app(
475                        WithMiddleware::new(ArcApp(Arc::clone(&app)))
476                            .wrap(BearerAuthMiddleware { token: Arc::new(token) }),
477                    )
478                }
479            }
480            #[cfg(feature = "auth")]
481            AuthConfig::Jwt { secret_env, previous_secret_env } => {
482                let secret = std::env::var(secret_env).unwrap_or_default();
483                let previous = (!previous_secret_env.is_empty()).then(|| std::env::var(previous_secret_env).unwrap_or_default()).filter(|s| !s.is_empty());
484                if secret.is_empty() {
485                    deny(format!("JWT auth: env var '{secret_env}' is unset or empty"))
486                } else {
487                    arc_app(
488                        WithMiddleware::new(ArcApp(Arc::clone(&app)))
489                            .wrap(crate::auth::JwtLayer::secrets(std::iter::once(secret).chain(previous))),
490                    )
491                }
492            }
493            #[cfg(not(feature = "auth"))]
494            AuthConfig::Jwt { .. } => {
495                deny("JWT auth requires the 'auth' feature, which this build doesn't include".to_string())
496            }
497            #[cfg(feature = "auth")]
498            AuthConfig::Basic { htpasswd_file } => {
499                match crate::auth::BasicAuthLayer::from_htpasswd_file(htpasswd_file) {
500                    Ok(layer) => arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(layer)),
501                    Err(e) => deny(format!("basic auth: {e}")),
502                }
503            }
504            #[cfg(not(feature = "auth"))]
505            AuthConfig::Basic { .. } => {
506                deny("basic auth requires the 'auth' feature, which this build doesn't include".to_string())
507            }
508            #[cfg(feature = "sso")]
509            AuthConfig::Oidc(oidc) => match crate::proxy_config::oidc_route::LazyOidc::new((**oidc).clone()) {
510                Ok(layer) => arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(layer)),
511                Err(e) => deny(e),
512            },
513            #[cfg(not(feature = "sso"))]
514            AuthConfig::Oidc(_) => deny("oidc auth requires the 'sso' feature, which this build doesn't include".to_string()),
515            #[cfg(feature = "auth")]
516            AuthConfig::Forward { url, copy_headers, timeout_ms } => {
517                if url.starts_with("http://") || url.starts_with("https://") {
518                    let layer = copy_headers.iter().fold(crate::auth::forward::ForwardAuthLayer::new(url.clone()).timeout_ms(*timeout_ms), |l, h| l.copy_header(h.clone()));
519                    arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(layer))
520                } else {
521                    deny(format!("forward auth: url {url:?} is not an http(s) URL"))
522                }
523            }
524            AuthConfig::Unknown(kind) => deny(format!("auth type {kind:?} is not one of bearer, jwt, basic, oidc, forward")),
525            #[cfg(not(feature = "auth"))]
526            AuthConfig::Forward { .. } => deny("forward auth requires the 'auth' feature, which this build doesn't include".to_string()),
527        };
528    }
529
530    // ── Rate limit ─────────────────────────────────────────────────────────
531    if let Some(ref rl_cfg) = mw.rate_limit {
532        let limiter = Arc::new(crate::rate_limit::RateLimiter::new(
533            rl_cfg.max_requests,
534            rl_cfg.window_secs,
535        ));
536        app = arc_app(
537            WithMiddleware::new(ArcApp(Arc::clone(&app)))
538                .wrap(PerRouteRateLimit(limiter)),
539        );
540    }
541
542    // ── IP filter ────────────────────────────────────────────────────────────
543    if !mw.ip_allow.is_empty() {
544        let filter = crate::ip_filter::IpFilter::allow(mw.ip_allow.iter().map(|s| s.as_str()));
545        app = arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(filter));
546    } else if !mw.ip_deny.is_empty() {
547        let filter = crate::ip_filter::IpFilter::deny(mw.ip_deny.iter().map(|s| s.as_str()));
548        app = arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(filter));
549    }
550
551    // ── Timeout (bounds this route's total time, including every other
552    // middleware above) ─────────────────────────────────────────────────────
553    if let Some(timeout_ms) = mw.timeout_ms {
554        app = arc_app(crate::timeout::TimeoutLayer::from_arc(
555            app,
556            std::time::Duration::from_millis(timeout_ms),
557        ));
558    }
559
560    // ── Max body size (outermost — see PerRouteMaxBodySize's docs for why
561    // this is not a substitute for RWS_CONFIG_MAX_BODY_SIZE_IN_BYTES) ──────
562    if let Some(max_body_size) = mw.max_body_size {
563        app = arc_app(
564            WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(PerRouteMaxBodySize(max_body_size)),
565        );
566    }
567
568    app
569}
570
571fn apply_request_rewrite_rule(
572    layer: crate::rewrite::RewriteLayer,
573    rule: &crate::proxy_config::RewriteRuleConfig,
574) -> crate::rewrite::RewriteLayer {
575    match rule.type_.as_str() {
576        "header_set" => {
577            if let (Some(name), Some(value)) = (&rule.name, &rule.value) {
578                return layer.request_header_set(name, value);
579            }
580        }
581        "header_remove" => {
582            if let Some(name) = &rule.name {
583                return layer.request_header_remove(name);
584            }
585        }
586        "uri_set" => {
587            if let Some(value) = &rule.value {
588                return layer.request_uri_set(value);
589            }
590        }
591        "uri_strip_prefix" | "strip_prefix" => {
592            if let Some(prefix) = rule.prefix.as_ref().or(rule.value.as_ref()) {
593                return layer.request_uri_strip_prefix(prefix);
594            }
595        }
596        "uri_add_prefix" | "add_prefix" => {
597            if let Some(prefix) = rule.prefix.as_ref().or(rule.value.as_ref()) {
598                return layer.request_uri_add_prefix(prefix);
599            }
600        }
601        _ => {}
602    }
603    layer
604}
605
606fn apply_response_rewrite_rule(
607    layer: crate::rewrite::RewriteLayer,
608    rule: &crate::proxy_config::RewriteRuleConfig,
609) -> crate::rewrite::RewriteLayer {
610    match rule.type_.as_str() {
611        "header_set" => {
612            if let (Some(name), Some(value)) = (&rule.name, &rule.value) {
613                return layer.response_header_set(name, value);
614            }
615        }
616        "header_remove" => {
617            if let Some(name) = &rule.name {
618                return layer.response_header_remove(name);
619            }
620        }
621        "status" => {
622            if let (Some(code), Some(reason)) = (&rule.code, &rule.reason) {
623                return layer.response_status(*code as i16, reason);
624            }
625        }
626        "body_replace" => {
627            if let (Some(from), Some(to)) = (&rule.from, &rule.to) {
628                return layer.response_body_replace(from, to);
629            }
630        }
631        _ => {}
632    }
633    layer
634}
635
636// ── ArcApp adapter ─────────────────────────────────────────────────────────────
637
638/// Wraps `Arc<dyn Application + Send + Sync>` to implement `Application`
639/// (needed because you can't implement a foreign trait on a foreign type).
640pub(crate) struct ArcApp(pub(crate) Arc<dyn crate::application::Application + Send + Sync>);
641
642impl crate::application::Application for ArcApp {
643    fn execute(
644        &self,
645        request: &crate::request::Request,
646        conn: &crate::server::ConnectionInfo,
647    ) -> Result<crate::response::Response, String> {
648        self.0.execute(request, conn)
649    }
650
651    fn streams_body(&self, request: &crate::request::Request, conn: &crate::server::ConnectionInfo) -> bool {
652        self.0.streams_body(request, conn)
653    }
654}
655
656impl Clone for ArcApp {
657    fn clone(&self) -> Self {
658        ArcApp(Arc::clone(&self.0))
659    }
660}
661
662/// The authorizer `[authz]` describes: its schema, the process-wide tuple
663/// store, the seed tuples written. `None` without `[authz]`.
664pub(crate) fn config_authorizer(config: &ProxyConfig) -> Option<Result<crate::authz::Authorizer, String>> {
665    config_authorizer_with(config, None)
666}
667
668/// [`config_authorizer`], or over `check_store` whatever `store` says — a
669/// throwaway store for `rws --check`, which must not connect or write.
670pub(crate) fn config_authorizer_with(
671    config: &ProxyConfig,
672    check_store: Option<Arc<dyn crate::authz::TupleStore>>,
673) -> Option<Result<crate::authz::Authorizer, String>> {
674    let authz = config.authz.as_ref()?;
675    Some((|| {
676        let mut schema = crate::authz::Schema::new();
677        for (kind, relations) in &authz.types {
678            schema = if relations.is_empty() { schema.object_type(kind) } else { Ok(schema) }.map_err(|e| e.to_string())?;
679            for (relation, definition) in relations {
680                schema = schema.relation(kind, relation, definition).map_err(|e| format!("type {kind}, relation {relation}: {e}"))?;
681            }
682        }
683        let store = match (authz.store.as_str(), check_store) {
684            ("" | "memory" | "sql", Some(store)) => store,
685            ("" | "memory", None) => crate::authz::config::memory_store(),
686            #[cfg(any(feature = "model-sqlite", feature = "model-postgres", feature = "model-mysql"))]
687            ("sql", None) => crate::authz::sql::config_store()?,
688            #[cfg(not(any(feature = "model-sqlite", feature = "model-postgres", feature = "model-mysql")))]
689            ("sql", None) => return Err("store = \"sql\" needs a build with a model-sqlite / model-postgres / model-mysql feature".to_string()),
690            (other, _) => return Err(format!("store = \"{other}\" isn't supported (memory or sql)")),
691        };
692        let authorizer = crate::authz::Authorizer::with_store(schema, store).map_err(|e| e.to_string())?;
693        for tuple in &authz.tuples {
694            authorizer.write_str(tuple).map_err(|e| format!("tuple {tuple:?}: {e}"))?;
695        }
696        Ok(authorizer)
697    })())
698}