rust_web_server/proxy_config/
builder.rs1use 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
15pub 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
38pub 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
50pub(crate) fn compile_routes(config: &ProxyConfig, health_stop: &Arc<AtomicBool>) -> Vec<CompiledRoute> {
54 let mut upstream_lives: HashMap<String, Arc<RwLock<Vec<String>>>> = HashMap::new();
56 let mut upstream_trust: HashMap<String, Arc<crate::proxy::UpstreamTls>> = HashMap::new();
60 let mut upstream_policies: HashMap<String, Arc<crate::proxy_config::upstream::UpstreamPolicy>> = HashMap::new();
63
64 for upstream in &config.upstreams {
65 let live = Arc::new(RwLock::new(upstream.backends.clone()));
66 upstream_lives.insert(upstream.name.clone(), Arc::clone(&live));
67 upstream_policies.insert(
68 upstream.name.clone(),
69 Arc::new(crate::proxy_config::upstream::UpstreamPolicy::new(
70 &upstream.name,
71 Arc::clone(&live),
72 &upstream.backends,
73 &upstream.weights,
74 upstream.sticky.clone(),
75 upstream.circuit_breaker.as_ref(),
76 upstream.retry.clone(),
77 )),
78 );
79
80 let client = upstream.tls_client_cert_file.as_deref().zip(upstream.tls_client_key_file.as_deref());
81 let configured = upstream.tls_ca_file.is_some() || upstream.tls_client_cert_file.is_some() || upstream.tls_client_key_file.is_some();
82 let trust = configured.then(|| {
83 Arc::new(crate::proxy::UpstreamTls::new(upstream.tls_ca_file.as_deref(), client).unwrap_or_else(|e| {
84 eprintln!("[proxy_config] ERROR: upstream '{}': {e} — its TLS backends answer 502 until this is fixed", upstream.name);
85 crate::proxy::UpstreamTls::reject_all(&upstream.name)
86 }))
87 });
88 if let Some(trust) = &trust {
89 upstream_trust.insert(upstream.name.clone(), Arc::clone(trust));
90 }
91
92 if let Some(ref hc) = upstream.health_check {
93 crate::proxy_config::health::start_health_checker(
94 upstream.name.clone(),
95 upstream.backends.clone(),
96 Arc::clone(&live),
97 hc.clone(),
98 Arc::clone(health_stop),
99 trust,
100 );
101 }
102 }
103
104 crate::proxy_config::upstream::register(upstream_policies.values().cloned().collect());
105
106 let mut compiled: Vec<CompiledRoute> = Vec::new();
108
109 for route in &config.routes {
110 let matcher = RouteMatcher::from_match_config(&route.match_);
111
112 let mut async_proxy: Option<Arc<DynamicProxy>> = None;
113
114 let base_handler: Arc<dyn crate::application::Application + Send + Sync> =
116 match &route.action {
117 ActionConfig::Proxy {
118 upstream,
119 connect_timeout_ms,
120 read_timeout_ms,
121 strip_path_prefix,
122 add_path_prefix,
123 } => {
124 let live = upstream_lives
125 .get(upstream.as_str())
126 .cloned()
127 .unwrap_or_else(|| {
128 Arc::new(RwLock::new(vec![upstream.clone()]))
130 });
131 let upstream_cfg = config.upstreams.iter().find(|u| u.name == *upstream);
132 let upstream_tls = upstream_cfg.map_or_else(|| upstream.starts_with("https://"), |u| u.tls);
133 let upstream_strategy = upstream_cfg
134 .map(|u| u.strategy.clone())
135 .unwrap_or_else(|| "round_robin".to_string());
136 let proxy = Arc::new(DynamicProxy::new(
137 live,
138 *connect_timeout_ms,
139 *read_timeout_ms,
140 strip_path_prefix.clone(),
141 add_path_prefix.clone(),
142 upstream_tls,
143 upstream_strategy,
144 )
145 .with_trust(upstream_trust.get(upstream.as_str()).cloned())
146 .with_policy(upstream, upstream_policies.get(upstream.as_str()).cloned()));
147 if proxy.supports_async() && route.middleware.is_empty() {
148 async_proxy = Some(Arc::clone(&proxy));
149 }
150 proxy
151 }
152
153 ActionConfig::Redirect { location, status } => {
154 arc_app(RedirectAdapter::new(location.clone(), *status))
155 }
156
157 ActionConfig::Respond { status, body, content_type } => {
158 arc_app(RespondAdapter::new(*status, body.clone(), content_type.clone()))
159 }
160
161 ActionConfig::Static { root, index } => {
162 arc_app(StaticAdapter::new(root.clone(), index.clone()))
163 }
164
165 ActionConfig::Grpc { upstream, connect_timeout_ms, read_timeout_ms } => {
168 let live = upstream_lives
169 .get(upstream.as_str())
170 .cloned()
171 .unwrap_or_else(|| Arc::new(RwLock::new(vec![upstream.clone()])));
172 let upstream_cfg = config.upstreams.iter().find(|u| u.name == *upstream);
173 let upstream_tls = upstream_cfg.map_or_else(|| upstream.starts_with("https://"), |u| u.tls);
174 #[cfg(feature = "http2")]
175 {
176 let _ = upstream_cfg;
177 arc_app(crate::proxy_config::H2Route::new(
178 live,
179 upstream_tls,
180 upstream_trust.get(upstream.as_str()).cloned(),
181 *connect_timeout_ms,
182 *read_timeout_ms,
183 ))
184 }
185 #[cfg(not(feature = "http2"))]
186 {
187 let upstream_strategy = upstream_cfg
188 .map(|u| u.strategy.clone())
189 .unwrap_or_else(|| "round_robin".to_string());
190 arc_app(
191 DynamicProxy::new(live, *connect_timeout_ms, *read_timeout_ms, None, None, upstream_tls, upstream_strategy)
192 .with_trust(upstream_trust.get(upstream.as_str()).cloned())
193 .with_policy(upstream, upstream_policies.get(upstream.as_str()).cloned()),
194 )
195 }
196 }
197
198 ActionConfig::Mcp | ActionConfig::Unknown(_) => {
199 arc_app(crate::proxy_config::NullApp)
201 }
202 };
203
204 let handler = apply_middleware(base_handler, &route.middleware);
206
207 compiled.push(CompiledRoute { matcher, handler, async_proxy });
208 }
209 compiled
210}
211
212fn spawn_listeners(config: &ProxyConfig) -> Vec<std::thread::JoinHandle<()>> {
216 let mut handles: Vec<std::thread::JoinHandle<()>> = Vec::new();
217
218 for tcp_cfg in &config.tcp_proxies {
219 let listen = tcp_cfg.listen.clone();
220 let backends = tcp_cfg.backends.clone();
221 let timeout_ms = tcp_cfg.connect_timeout_ms;
222 let name = tcp_cfg.name.clone();
223 let h = std::thread::Builder::new()
224 .name(format!("tcp-proxy-{}", name))
225 .spawn(move || {
226 let proxy = crate::tcp_proxy::TcpProxy::new(backends)
227 .connect_timeout_ms(timeout_ms);
228 if let Err(e) = proxy.bind(&listen) {
229 eprintln!("[tcp_proxy:{}] {}", name, e);
230 }
231 })
232 .expect("failed to spawn tcp proxy thread");
233 handles.push(h);
234 }
235
236 for udp_cfg in &config.udp_proxies {
237 let listen = udp_cfg.listen.clone();
238 let backends = udp_cfg.backends.clone();
239 let reply_timeout_ms = udp_cfg.reply_timeout_ms;
240 let buffer_size = udp_cfg.buffer_size;
241 let name = udp_cfg.name.clone();
242 let h = std::thread::Builder::new()
243 .name(format!("udp-proxy-{}", name))
244 .spawn(move || {
245 let proxy = crate::udp_proxy::UdpProxy::new(backends)
246 .reply_timeout_ms(reply_timeout_ms)
247 .buffer_size(buffer_size);
248 if let Err(e) = proxy.bind(&listen) {
249 eprintln!("[udp_proxy:{}] {}", name, e);
250 }
251 })
252 .expect("failed to spawn udp proxy thread");
253 handles.push(h);
254 }
255
256 for ws_cfg in &config.ws_proxies {
257 let listen = ws_cfg.listen.clone();
258 let backends = ws_cfg.backends.clone();
259 let connect_timeout_ms = ws_cfg.connect_timeout_ms;
260 let read_timeout_ms = ws_cfg.read_timeout_ms;
261 let name = ws_cfg.name.clone();
262
263 let live = Arc::new(RwLock::new(backends.clone()));
267 if let Some(ref hc) = ws_cfg.health_check {
268 crate::proxy_config::health::start_health_checker(
269 name.clone(),
270 backends.clone(),
271 Arc::clone(&live),
272 hc.clone(),
273 Arc::new(AtomicBool::new(false)),
274 None,
275 );
276 }
277
278 let h = std::thread::Builder::new()
279 .name(format!("ws-proxy-{}", name))
280 .spawn(move || {
281 let proxy = crate::ws_proxy::WsProxy::with_live_backends(backends, live)
282 .connect_timeout_ms(connect_timeout_ms)
283 .read_timeout_ms(read_timeout_ms);
284 if let Err(e) = proxy.bind(&listen) {
285 eprintln!("[ws_proxy:{}] {}", name, e);
286 }
287 })
288 .expect("failed to spawn ws proxy thread");
289 handles.push(h);
290 }
291
292 handles
293}
294
295pub(crate) fn apply_middleware(
309 handler: Arc<dyn crate::application::Application + Send + Sync>,
310 mw: &MiddlewareConfig,
311) -> Arc<dyn crate::application::Application + Send + Sync> {
312 let mut app: Arc<dyn crate::application::Application + Send + Sync> = handler;
315
316 if let Some(ref cache_cfg) = mw.cache {
318 let mut layer = crate::cache::CacheLayer::memory(1000).ttl(cache_cfg.ttl_secs);
319 for vh in &cache_cfg.vary_by {
320 layer = layer.vary_by_header(vh.as_str());
321 }
322 app = arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(layer));
323 }
324
325 if !mw.rewrite_request.is_empty() || !mw.rewrite_response.is_empty() {
327 let mut layer = crate::rewrite::RewriteLayer::new();
328 for rule in &mw.rewrite_request {
329 layer = apply_request_rewrite_rule(layer, rule);
330 }
331 for rule in &mw.rewrite_response {
332 layer = apply_response_rewrite_rule(layer, rule);
333 }
334 app = arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(layer));
335 }
336
337 if let Some(ref auth_cfg) = mw.auth {
342 let deny = |reason: String| -> Arc<dyn crate::application::Application + Send + Sync> {
343 eprintln!(
344 "[proxy_config] ERROR: {reason} — this route answers 503 until the auth configuration is fixed."
345 );
346 arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(AuthMisconfigured))
347 };
348 app = match auth_cfg {
349 AuthConfig::Bearer { token_env } => {
350 let token = std::env::var(token_env).unwrap_or_default();
351 if token.is_empty() {
352 deny(format!("bearer auth: env var '{token_env}' is unset or empty"))
353 } else {
354 arc_app(
355 WithMiddleware::new(ArcApp(Arc::clone(&app)))
356 .wrap(BearerAuthMiddleware { token: Arc::new(token) }),
357 )
358 }
359 }
360 #[cfg(feature = "auth")]
361 AuthConfig::Jwt { secret_env } => {
362 let secret = std::env::var(secret_env).unwrap_or_default();
363 if secret.is_empty() {
364 deny(format!("JWT auth: env var '{secret_env}' is unset or empty"))
365 } else {
366 arc_app(
367 WithMiddleware::new(ArcApp(Arc::clone(&app)))
368 .wrap(crate::auth::JwtLayer::new(secret)),
369 )
370 }
371 }
372 #[cfg(not(feature = "auth"))]
373 AuthConfig::Jwt { .. } => {
374 deny("JWT auth requires the 'auth' feature, which this build doesn't include".to_string())
375 }
376 #[cfg(feature = "auth")]
377 AuthConfig::Basic { htpasswd_file } => {
378 match crate::auth::BasicAuthLayer::from_htpasswd_file(htpasswd_file) {
379 Ok(layer) => arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(layer)),
380 Err(e) => deny(format!("basic auth: {e}")),
381 }
382 }
383 #[cfg(not(feature = "auth"))]
384 AuthConfig::Basic { .. } => {
385 deny("basic auth requires the 'auth' feature, which this build doesn't include".to_string())
386 }
387 };
388 }
389
390 if let Some(ref rl_cfg) = mw.rate_limit {
392 let limiter = Arc::new(crate::rate_limit::RateLimiter::new(
393 rl_cfg.max_requests,
394 rl_cfg.window_secs,
395 ));
396 app = arc_app(
397 WithMiddleware::new(ArcApp(Arc::clone(&app)))
398 .wrap(PerRouteRateLimit(limiter)),
399 );
400 }
401
402 if !mw.ip_allow.is_empty() {
404 let filter = crate::ip_filter::IpFilter::allow(mw.ip_allow.iter().map(|s| s.as_str()));
405 app = arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(filter));
406 } else if !mw.ip_deny.is_empty() {
407 let filter = crate::ip_filter::IpFilter::deny(mw.ip_deny.iter().map(|s| s.as_str()));
408 app = arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(filter));
409 }
410
411 if let Some(timeout_ms) = mw.timeout_ms {
414 app = arc_app(crate::timeout::TimeoutLayer::from_arc(
415 app,
416 std::time::Duration::from_millis(timeout_ms),
417 ));
418 }
419
420 if let Some(max_body_size) = mw.max_body_size {
423 app = arc_app(
424 WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(PerRouteMaxBodySize(max_body_size)),
425 );
426 }
427
428 app
429}
430
431fn apply_request_rewrite_rule(
432 layer: crate::rewrite::RewriteLayer,
433 rule: &crate::proxy_config::RewriteRuleConfig,
434) -> crate::rewrite::RewriteLayer {
435 match rule.type_.as_str() {
436 "header_set" => {
437 if let (Some(name), Some(value)) = (&rule.name, &rule.value) {
438 return layer.request_header_set(name, value);
439 }
440 }
441 "header_remove" => {
442 if let Some(name) = &rule.name {
443 return layer.request_header_remove(name);
444 }
445 }
446 "uri_set" => {
447 if let Some(value) = &rule.value {
448 return layer.request_uri_set(value);
449 }
450 }
451 "uri_strip_prefix" | "strip_prefix" => {
452 if let Some(prefix) = rule.prefix.as_ref().or(rule.value.as_ref()) {
453 return layer.request_uri_strip_prefix(prefix);
454 }
455 }
456 "uri_add_prefix" | "add_prefix" => {
457 if let Some(prefix) = rule.prefix.as_ref().or(rule.value.as_ref()) {
458 return layer.request_uri_add_prefix(prefix);
459 }
460 }
461 _ => {}
462 }
463 layer
464}
465
466fn apply_response_rewrite_rule(
467 layer: crate::rewrite::RewriteLayer,
468 rule: &crate::proxy_config::RewriteRuleConfig,
469) -> crate::rewrite::RewriteLayer {
470 match rule.type_.as_str() {
471 "header_set" => {
472 if let (Some(name), Some(value)) = (&rule.name, &rule.value) {
473 return layer.response_header_set(name, value);
474 }
475 }
476 "header_remove" => {
477 if let Some(name) = &rule.name {
478 return layer.response_header_remove(name);
479 }
480 }
481 "status" => {
482 if let (Some(code), Some(reason)) = (&rule.code, &rule.reason) {
483 return layer.response_status(*code as i16, reason);
484 }
485 }
486 "body_replace" => {
487 if let (Some(from), Some(to)) = (&rule.from, &rule.to) {
488 return layer.response_body_replace(from, to);
489 }
490 }
491 _ => {}
492 }
493 layer
494}
495
496struct ArcApp(Arc<dyn crate::application::Application + Send + Sync>);
501
502impl crate::application::Application for ArcApp {
503 fn execute(
504 &self,
505 request: &crate::request::Request,
506 conn: &crate::server::ConnectionInfo,
507 ) -> Result<crate::response::Response, String> {
508 self.0.execute(request, conn)
509 }
510
511 fn streams_body(&self, request: &crate::request::Request, conn: &crate::server::ConnectionInfo) -> bool {
512 self.0.streams_body(request, conn)
513 }
514}
515
516impl Clone for ArcApp {
517 fn clone(&self) -> Self {
518 ArcApp(Arc::clone(&self.0))
519 }
520}