Skip to main content

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