1use actix_cors::Cors;
23use actix_web::body::MessageBody;
24use actix_web::dev::{ServiceFactory, ServiceRequest, ServiceResponse};
25use actix_web::http::header;
26use actix_web::middleware::{Condition, DefaultHeaders, Next};
27use actix_web::App;
28use std::collections::HashSet;
29use std::net::IpAddr;
30use tracing::info;
31use tracing::warn;
32
33use crate::rate_limit::{KeyExtractor, RateLimit, RateLimiterConfig, SimpleKeyExtractionError};
34
35const DEFAULT_RATE_LIMIT_PER_SECOND: u64 = 10;
38const DEFAULT_RATE_LIMIT_BURST: u32 = 20;
40
41#[derive(Clone, Debug)]
52pub struct ClientIpKeyExtractor {
53 trust_xff: bool,
54 trusted_hops: usize,
58}
59
60impl ClientIpKeyExtractor {
61 #[cfg(test)]
63 fn peer_ip() -> Self {
64 Self {
65 trust_xff: false,
66 trusted_hops: 1,
67 }
68 }
69
70 fn client_ip_from_xff(&self, req: &ServiceRequest) -> Option<IpAddr> {
71 let hops = self.trusted_hops.max(1);
72 let entries: Vec<&str> = req
78 .headers()
79 .get_all("x-forwarded-for")
80 .filter_map(|v| v.to_str().ok())
81 .flat_map(|line| line.split(','))
82 .map(|s| s.trim())
83 .filter(|s| !s.is_empty())
84 .collect();
85 if entries.len() < hops {
88 return None;
89 }
90 parse_forwarded_ip(entries[entries.len() - hops])
91 }
92}
93
94impl KeyExtractor for ClientIpKeyExtractor {
95 type Key = IpAddr;
96 type KeyExtractionError = SimpleKeyExtractionError;
97
98 fn extract(&self, req: &ServiceRequest) -> Result<Self::Key, Self::KeyExtractionError> {
99 if self.trust_xff {
100 if let Some(client) = self.client_ip_from_xff(req) {
101 return Ok(mask_ipv6_prefix(client));
102 }
103 }
105 let ip = req.peer_addr().map(|socket| socket.ip()).ok_or_else(|| {
106 SimpleKeyExtractionError::new("Could not extract peer IP address from request")
107 })?;
108 Ok(mask_ipv6_prefix(ip))
109 }
110}
111
112fn mask_ipv6_prefix(ip: IpAddr) -> IpAddr {
115 match ip {
116 IpAddr::V6(v6) => {
117 let mut octets = v6.octets();
118 octets[7..16].fill(0);
119 IpAddr::V6(octets.into())
120 }
121 v4 => v4,
122 }
123}
124
125fn parse_forwarded_ip(s: &str) -> Option<IpAddr> {
128 let s = s.trim();
129 if let Ok(ip) = s.parse::<IpAddr>() {
130 return Some(ip);
131 }
132 if let Ok(sa) = s.parse::<std::net::SocketAddr>() {
133 return Some(sa.ip());
134 }
135 let unbracketed = s.strip_prefix('[').and_then(|x| x.strip_suffix(']'))?;
137 unbracketed.parse::<IpAddr>().ok()
138}
139
140fn rate_limiter_config(
141 per_second: u64,
142 burst: u32,
143 key_extractor: ClientIpKeyExtractor,
144) -> RateLimiterConfig<ClientIpKeyExtractor> {
145 let ms_per_request = (1000 / per_second.max(1)).max(1);
149 RateLimiterConfig::new(
150 std::time::Duration::from_millis(ms_per_request),
151 burst.max(1),
152 key_extractor,
153 )
154}
155
156pub fn build_rate_limiter() -> RateLimiterConfig<ClientIpKeyExtractor> {
169 let per_second = std::env::var("BAMBOO_RATE_LIMIT_PER_SECOND")
170 .ok()
171 .and_then(|v| v.trim().parse::<u64>().ok())
172 .unwrap_or(DEFAULT_RATE_LIMIT_PER_SECOND);
173 let burst = std::env::var("BAMBOO_RATE_LIMIT_BURST")
174 .ok()
175 .and_then(|v| v.trim().parse::<u32>().ok())
176 .unwrap_or(DEFAULT_RATE_LIMIT_BURST);
177
178 let trust_xff = std::env::var("BAMBOO_RATE_LIMIT_TRUST_XFF")
179 .ok()
180 .map(|v| {
181 let t = v.trim();
182 t == "1" || t.eq_ignore_ascii_case("true")
183 })
184 .unwrap_or(false);
185 let trusted_hops = std::env::var("BAMBOO_RATE_LIMIT_TRUSTED_HOPS")
186 .ok()
187 .and_then(|v| v.trim().parse::<usize>().ok())
188 .filter(|n| *n >= 1)
189 .unwrap_or(1);
190
191 if trust_xff {
192 warn!(
193 "Rate limiter is trusting X-Forwarded-For (trusted_hops={trusted_hops}). \
194 Only enable this when the server is reachable exclusively through a trusted \
195 reverse proxy — otherwise clients can spoof their rate-limit key."
196 );
197 }
198
199 rate_limiter_config(
200 per_second,
201 burst,
202 ClientIpKeyExtractor {
203 trust_xff,
204 trusted_hops,
205 },
206 )
207}
208
209pub fn is_loopback_bind(bind: &str) -> bool {
224 let candidate = bind.trim();
225 let unbracketed = candidate
226 .strip_prefix('[')
227 .and_then(|s| s.strip_suffix(']'))
228 .unwrap_or(candidate);
229
230 if unbracketed.eq_ignore_ascii_case("localhost") {
231 return true;
232 }
233
234 unbracketed
235 .parse::<IpAddr>()
236 .map(|ip| ip.is_loopback())
237 .unwrap_or(false)
238}
239
240pub fn require_limiter_for_nonloopback(bind: &str, limiter_applied: bool) -> Result<(), String> {
255 if !limiter_applied && !is_loopback_bind(bind) {
256 return Err(format!(
257 "refusing to serve on non-loopback bind '{bind}' without a rate limiter: it would \
258 run unthrottled and re-open the per-IP DoS surface closed by #13. Use a \
259 limiter-applying serve path (e.g. start_with_bind_and_static / run_with_bind) or \
260 bind to loopback (127.0.0.1 / localhost / ::1)."
261 ));
262 }
263 Ok(())
264}
265
266const DEFAULT_CSP: &str = concat!(
271 "default-src 'self'; ",
272 "base-uri 'self'; ",
273 "object-src 'none'; ",
274 "frame-ancestors 'none'; ",
275 "script-src 'self'; ",
276 "style-src 'self' 'unsafe-inline'; ",
277 "img-src 'self' data: https:; ",
278 "font-src 'self' data:; ",
279 "connect-src 'self' ws: wss: http://127.0.0.1:* http://localhost:* http://bodhi.bigduu.com:9562 https://bodhi.bigduu.com:9562; ",
280 "form-action 'self';"
281);
282
283fn normalize_csp_source_token(token: &str) -> Option<String> {
284 let trimmed = token.trim();
285 if trimmed.is_empty() {
286 return None;
287 }
288
289 if trimmed.starts_with("'") {
290 return Some(trimmed.to_string());
291 }
292
293 normalize_origin(trimmed).or_else(|| Some(trimmed.to_string()))
294}
295
296fn parse_csp_connect_src_append(raw: &str) -> Vec<String> {
297 raw.split(|c: char| c == ',' || c.is_ascii_whitespace())
298 .filter_map(normalize_csp_source_token)
299 .collect()
300}
301
302fn append_connect_src_sources(base_csp: &str, extra_sources: &[String]) -> String {
303 if extra_sources.is_empty() {
304 return base_csp.to_string();
305 }
306
307 let connect_src_marker = "connect-src ";
308 if let Some(start) = base_csp.find(connect_src_marker) {
309 let value_start = start + connect_src_marker.len();
310 if let Some(relative_end) = base_csp[value_start..].find(';') {
311 let value_end = value_start + relative_end;
312 let existing_value = base_csp[value_start..value_end].trim();
313 let mut merged = if existing_value.is_empty() {
314 String::new()
315 } else {
316 existing_value.to_string()
317 };
318
319 for source in extra_sources {
320 if merged.split_whitespace().any(|token| token == source) {
321 continue;
322 }
323 if !merged.is_empty() {
324 merged.push(' ');
325 }
326 merged.push_str(source);
327 }
328
329 let mut result = String::with_capacity(base_csp.len() + merged.len() + 1);
330 result.push_str(&base_csp[..value_start]);
331 result.push_str(&merged);
332 result.push_str(&base_csp[value_end..]);
333 return result;
334 }
335 }
336
337 base_csp.to_string()
338}
339
340fn resolve_default_csp() -> String {
341 const ENV_KEY: &str = "BAMBOO_CSP_CONNECT_SRC";
342
343 let extra_sources = match std::env::var(ENV_KEY) {
344 Ok(raw) => parse_csp_connect_src_append(&raw),
345 Err(_) => Vec::new(),
346 };
347
348 if !extra_sources.is_empty() {
349 info!(
350 "Extending CSP connect-src via {} with {} source(s)",
351 ENV_KEY,
352 extra_sources.len()
353 );
354 }
355
356 append_connect_src_sources(DEFAULT_CSP, &extra_sources)
357}
358
359fn resolve_csp_header_value(override_value: Option<&str>) -> header::HeaderValue {
360 let default_csp = resolve_default_csp();
361 let csp = override_value.unwrap_or(default_csp.as_str());
362 match header::HeaderValue::from_str(csp) {
363 Ok(v) => v,
364 Err(e) => {
365 warn!(
367 "Invalid BAMBOO_CSP value ({}); falling back to DEFAULT_CSP",
368 e
369 );
370 header::HeaderValue::from_str(default_csp.as_str())
371 .unwrap_or_else(|_| header::HeaderValue::from_static(DEFAULT_CSP))
372 }
373 }
374}
375
376#[derive(Debug, Clone, Default)]
383struct CorsAllowlist {
384 exact_origins: HashSet<String>,
385 hosts: Vec<HostPattern>,
386}
387
388#[derive(Debug, Clone, PartialEq, Eq)]
389enum HostPattern {
390 Exact(String),
391 Suffix(String), }
393
394fn normalize_origin(origin: &str) -> Option<String> {
395 let url = url::Url::parse(origin).ok()?;
396
397 let scheme = url.scheme().to_ascii_lowercase();
398 let host = url.host()?;
399 let host_str = match host {
400 url::Host::Domain(d) => d.to_ascii_lowercase(),
401 url::Host::Ipv4(v4) => v4.to_string(),
402 url::Host::Ipv6(v6) => format!("[{v6}]"),
403 };
404
405 let port = url.port();
406 let default_port = match scheme.as_str() {
407 "http" => Some(80),
408 "https" => Some(443),
409 _ => None,
410 };
411 let port = match (port, default_port) {
412 (Some(p), Some(d)) if p == d => None,
413 (p, _) => p,
414 };
415
416 Some(match port {
417 Some(p) => format!("{scheme}://{host_str}:{p}"),
418 None => format!("{scheme}://{host_str}"),
419 })
420}
421
422fn parse_cors_allowlist(raw: &str) -> CorsAllowlist {
423 let mut allow = CorsAllowlist::default();
424
425 for item in raw.split(',') {
426 let token = item.trim();
427 if token.is_empty() {
428 continue;
429 }
430
431 if token.contains("://") {
432 match normalize_origin(token) {
435 Some(origin) => {
436 allow.exact_origins.insert(origin);
437 }
438 None => {
439 warn!(
440 "Invalid CORS origin entry '{}'; expected an origin like https://app.example.com",
441 token
442 );
443 }
444 }
445 continue;
446 }
447
448 let host = token.to_ascii_lowercase();
450 if let Some(rest) = host.strip_prefix("*.") {
451 if !rest.is_empty() {
453 allow.hosts.push(HostPattern::Suffix(format!(".{rest}")));
454 }
455 } else {
456 allow.hosts.push(HostPattern::Exact(host));
457 }
458 }
459
460 allow
461}
462
463fn parse_cors_allowlist_env() -> CorsAllowlist {
464 const ENV_KEY: &str = "BAMBOO_CORS_ALLOW_ORIGINS";
468
469 let raw = match std::env::var(ENV_KEY) {
470 Ok(v) => v,
471 Err(_) => return CorsAllowlist::default(),
472 };
473
474 let allow = parse_cors_allowlist(&raw);
475
476 if !allow.exact_origins.is_empty() || !allow.hosts.is_empty() {
477 info!(
478 "CORS allowlist enabled via BAMBOO_CORS_ALLOW_ORIGINS ({} exact origin(s), {} host pattern(s))",
479 allow.exact_origins.len(),
480 allow.hosts.len()
481 );
482 }
483
484 allow
485}
486
487fn is_allowed_by_allowlist(origin: &str, allow: &CorsAllowlist) -> bool {
488 if let Some(normalized) = normalize_origin(origin) {
489 if allow.exact_origins.contains(&normalized) {
490 return true;
491 }
492 }
493
494 if allow.exact_origins.contains(origin) {
496 return true;
497 }
498
499 let url = match url::Url::parse(origin) {
504 Ok(u) => u,
505 Err(_) => return false,
506 };
507
508 let host = match url.host_str() {
509 Some(h) => h.to_ascii_lowercase(),
510 None => return false,
511 };
512
513 for pat in &allow.hosts {
514 match pat {
515 HostPattern::Exact(h) => {
516 if &host == h {
517 return true;
518 }
519 }
520 HostPattern::Suffix(suffix) => {
521 if host.ends_with(suffix) {
522 return true;
525 }
526 }
527 }
528 }
529
530 false
531}
532
533fn is_local_dev_origin(o: &str) -> bool {
534 o.starts_with("http://localhost:")
535 || o.starts_with("http://127.0.0.1:")
536 || o.starts_with("https://localhost:")
537 || o.starts_with("https://127.0.0.1:")
538 || o.starts_with("http://mac.local:")
539 || o.starts_with("https://mac.local:")
540 || o.starts_with("http://bodhi.bigduu.com:")
541 || o.starts_with("https://bodhi.bigduu.com:")
542 || o.starts_with("http://[::1]:")
543 || o.starts_with("https://[::1]:")
544}
545
546pub fn build_security_headers() -> DefaultHeaders {
565 let csp_override = std::env::var("BAMBOO_CSP").ok();
566 let csp_value = resolve_csp_header_value(csp_override.as_deref());
567
568 DefaultHeaders::new()
569 .add(("X-Frame-Options", "DENY"))
570 .add(("X-Content-Type-Options", "nosniff"))
571 .add(("X-XSS-Protection", "1; mode=block"))
572 .add(("Referrer-Policy", "strict-origin-when-cross-origin"))
573 .add((header::CONTENT_SECURITY_POLICY, csp_value))
575}
576
577pub async fn add_asset_cache_headers<B: MessageBody + 'static>(
591 req: ServiceRequest,
592 next: Next<B>,
593) -> Result<ServiceResponse<B>, actix_web::Error> {
594 let is_asset = req.path().starts_with("/assets/");
595 let mut res = next.call(req).await?;
596 if is_asset {
597 res.headers_mut().insert(
598 header::CACHE_CONTROL,
599 header::HeaderValue::from_static("public, max-age=31536000, immutable"),
600 );
601 }
602 Ok(res)
603}
604
605pub fn build_cors(bind_addr: &str, port: u16) -> Cors {
644 let allowlist = parse_cors_allowlist_env();
645
646 let cors = if bind_addr == "127.0.0.1" || bind_addr == "localhost" || bind_addr == "::1" {
647 info!("CORS configured for development mode: allowing local/Tauri origins (+ optional allowlist)");
651 Cors::default()
652 .allowed_origin_fn(move |origin, _req_head| {
653 let o = match origin.to_str() {
654 Ok(v) => v,
655 Err(_) => return false,
656 };
657
658 if is_allowed_by_allowlist(o, &allowlist) {
659 return true;
660 }
661
662 if is_local_dev_origin(o) {
663 return true;
664 }
665
666 o == "tauri://localhost"
667 || o == "https://tauri.localhost"
668 || o == "http://tauri.localhost"
669 })
670 .allow_any_method()
671 .allow_any_header()
672 .supports_credentials()
673 .max_age(3600)
674 } else if bind_addr == "0.0.0.0" {
675 info!("CORS configured for 0.0.0.0 bind: allowing localhost/loopback origins (+ optional allowlist)");
685 Cors::default()
686 .allowed_origin_fn(move |origin, _req_head| {
687 let o = match origin.to_str() {
688 Ok(v) => v,
689 Err(_) => return false,
690 };
691
692 if is_allowed_by_allowlist(o, &allowlist) {
694 return true;
695 }
696
697 if is_local_dev_origin(o) {
699 return true;
700 }
701
702 if o == "tauri://localhost"
704 || o == "https://tauri.localhost"
705 || o == "http://tauri.localhost"
706 {
707 return true;
708 }
709
710 if o == format!("http://localhost:{port}")
712 || o == format!("http://127.0.0.1:{port}")
713 {
714 return true;
715 }
716
717 false
718 })
719 .allow_any_method()
722 .allow_any_header()
725 .supports_credentials()
726 .max_age(3600)
727 } else {
728 info!(
730 "CORS configured for custom bind address: {} (+ optional allowlist)",
731 bind_addr
732 );
733 let bind_host = bind_addr.to_ascii_lowercase();
734 let allowlist = allowlist.clone();
735 Cors::default()
736 .allowed_origin_fn(move |origin, _req_head| {
737 let o = match origin.to_str() {
738 Ok(v) => v,
739 Err(_) => return false,
740 };
741
742 if is_allowed_by_allowlist(o, &allowlist) {
743 return true;
744 }
745
746 let url = match url::Url::parse(o) {
749 Ok(u) => u,
750 Err(_) => return false,
751 };
752 let Some(host) = url.host_str() else {
753 return false;
754 };
755 host.eq_ignore_ascii_case(&bind_host)
756 })
757 .allow_any_method()
758 .allow_any_header()
759 .supports_credentials()
760 .max_age(3600)
761 };
762
763 cors
764}
765
766pub fn wrap_governor_and_cors<T, B>(
788 app: App<T>,
789 rate_limiter: &RateLimiterConfig<ClientIpKeyExtractor>,
790 apply_rate_limit: bool,
791 bind_addr: &str,
792 port: u16,
793) -> App<
794 impl ServiceFactory<
795 ServiceRequest,
796 Config = (),
797 Response = ServiceResponse<impl MessageBody>,
798 Error = actix_web::Error,
799 InitError = (),
800 >,
801>
802where
803 T: ServiceFactory<
804 ServiceRequest,
805 Config = (),
806 Response = ServiceResponse<B>,
807 Error = actix_web::Error,
808 InitError = (),
809 > + 'static,
810 B: MessageBody + 'static,
811{
812 app.wrap(Condition::new(
813 apply_rate_limit,
814 RateLimit::new(rate_limiter),
815 ))
816 .wrap(build_cors(bind_addr, port))
817}
818
819#[cfg(test)]
820mod tests {
821 use super::*;
822
823 #[test]
824 fn rate_limiter_config_clamps_degenerate_values() {
825 let _ = rate_limiter_config(0, 0, ClientIpKeyExtractor::peer_ip());
828 let _ = rate_limiter_config(1000, 1, ClientIpKeyExtractor::peer_ip());
829 }
830
831 #[test]
832 fn loopback_binds_skip_rate_limiter() {
833 for b in ["127.0.0.1", "localhost", "::1"] {
836 assert!(
837 is_loopback_bind(b),
838 "{b} should be loopback (limiter skipped)"
839 );
840 }
841 for b in ["0.0.0.0", "192.168.1.10", "::"] {
842 assert!(!is_loopback_bind(b), "{b} should be throttled");
843 }
844 }
845
846 #[test]
847 fn loopback_binds_recognizes_full_loopback_range_and_bracketed_ipv6() {
848 for b in ["127.0.0.2", "127.255.255.255", "[::1]", "LOCALHOST"] {
852 assert!(is_loopback_bind(b), "{b} is a loopback address/host");
853 }
854 }
855
856 #[actix_web::test]
857 async fn asset_cache_headers_only_tag_hashed_assets() {
858 use actix_web::http::header::CACHE_CONTROL;
859 use actix_web::{test, web, App, HttpResponse};
860
861 let app = test::init_service(
862 App::new()
863 .wrap(actix_web::middleware::from_fn(add_asset_cache_headers))
864 .route(
865 "/assets/main-abc123.css",
866 web::get().to(|| async { HttpResponse::Ok().finish() }),
867 )
868 .route(
869 "/index.html",
870 web::get().to(|| async { HttpResponse::Ok().finish() }),
871 ),
872 )
873 .await;
874
875 let req = test::TestRequest::get()
877 .uri("/assets/main-abc123.css")
878 .to_request();
879 let res = test::call_service(&app, req).await;
880 assert_eq!(
881 res.headers()
882 .get(CACHE_CONTROL)
883 .and_then(|v| v.to_str().ok()),
884 Some("public, max-age=31536000, immutable"),
885 );
886
887 let req = test::TestRequest::get().uri("/index.html").to_request();
890 let res = test::call_service(&app, req).await;
891 assert!(
892 res.headers().get(CACHE_CONTROL).is_none(),
893 "non-asset routes must not be long-cached"
894 );
895 }
896
897 #[actix_web::test]
898 async fn rate_limiter_throttles_with_429_after_burst() {
899 use crate::rate_limit::RateLimit;
900 use actix_web::http::StatusCode;
901 use actix_web::{test, web, App, HttpResponse};
902 use std::net::{IpAddr, Ipv4Addr, SocketAddr};
903
904 let conf = rate_limiter_config(1, 2, ClientIpKeyExtractor::peer_ip());
906 let app = test::init_service(
907 App::new()
908 .wrap(RateLimit::new(&conf))
909 .route("/", web::get().to(|| async { HttpResponse::Ok().finish() })),
910 )
911 .await;
912
913 let ip = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 7)), 9999);
914 let (mut saw_ok, mut saw_429) = (false, false);
915 for _ in 0..6 {
916 let req = test::TestRequest::get().uri("/").peer_addr(ip).to_request();
917 match test::call_service(&app, req).await.status() {
918 StatusCode::OK => saw_ok = true,
919 StatusCode::TOO_MANY_REQUESTS => saw_429 = true,
920 other => panic!("unexpected status {other}"),
921 }
922 }
923 assert!(saw_ok, "requests within the burst must pass");
924 assert!(saw_429, "requests beyond the burst must be 429'd (#13)");
925
926 let other_ip = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(198, 51, 100, 9)), 8888);
930 let req = test::TestRequest::get()
931 .uri("/")
932 .peer_addr(other_ip)
933 .to_request();
934 assert_eq!(
935 test::call_service(&app, req).await.status(),
936 StatusCode::OK,
937 "a different IP gets its own fresh bucket (per-IP, not global)"
938 );
939 }
940
941 #[actix_web::test]
942 async fn key_extractor_default_ignores_xff_and_uses_peer_ip() {
943 use actix_web::test;
944 use std::net::{Ipv4Addr, SocketAddr};
945
946 let ke = ClientIpKeyExtractor::peer_ip();
949 let peer = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 7)), 5000);
950 let req = test::TestRequest::get()
951 .peer_addr(peer)
952 .insert_header(("x-forwarded-for", "1.2.3.4"))
953 .to_srv_request();
954 assert_eq!(
955 ke.extract(&req).unwrap(),
956 IpAddr::V4(Ipv4Addr::new(203, 0, 113, 7))
957 );
958 }
959
960 #[actix_web::test]
961 async fn key_extractor_xff_uses_rightmost_at_one_hop_not_client_prefix() {
962 use actix_web::test;
963 use std::net::{Ipv4Addr, SocketAddr};
964
965 let ke = ClientIpKeyExtractor {
968 trust_xff: true,
969 trusted_hops: 1,
970 };
971 let peer = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)), 5000); let req = test::TestRequest::get()
973 .peer_addr(peer)
974 .insert_header(("x-forwarded-for", "1.1.1.1, 2.2.2.2"))
975 .to_srv_request();
976 assert_eq!(
977 ke.extract(&req).unwrap(),
978 IpAddr::V4(Ipv4Addr::new(2, 2, 2, 2))
979 );
980 }
981
982 #[actix_web::test]
983 async fn key_extractor_xff_two_hops_takes_second_from_right() {
984 use actix_web::test;
985 use std::net::{Ipv4Addr, SocketAddr};
986
987 let ke = ClientIpKeyExtractor {
988 trust_xff: true,
989 trusted_hops: 2,
990 };
991 let peer = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)), 5000);
992 let req = test::TestRequest::get()
993 .peer_addr(peer)
994 .insert_header(("x-forwarded-for", "1.1.1.1, 2.2.2.2, 3.3.3.3"))
995 .to_srv_request();
996 assert_eq!(
997 ke.extract(&req).unwrap(),
998 IpAddr::V4(Ipv4Addr::new(2, 2, 2, 2))
999 );
1000 }
1001
1002 #[actix_web::test]
1003 async fn key_extractor_xff_fails_closed_to_peer_when_header_too_short_or_absent() {
1004 use actix_web::test;
1005 use std::net::{Ipv4Addr, SocketAddr};
1006
1007 let ke = ClientIpKeyExtractor {
1008 trust_xff: true,
1009 trusted_hops: 2,
1010 };
1011 let peer = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)), 5000);
1012
1013 let short = test::TestRequest::get()
1015 .peer_addr(peer)
1016 .insert_header(("x-forwarded-for", "9.9.9.9"))
1017 .to_srv_request();
1018 assert_eq!(
1019 ke.extract(&short).unwrap(),
1020 IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))
1021 );
1022
1023 let none = test::TestRequest::get().peer_addr(peer).to_srv_request();
1025 assert_eq!(
1026 ke.extract(&none).unwrap(),
1027 IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))
1028 );
1029 }
1030
1031 #[actix_web::test]
1032 async fn key_extractor_xff_flattens_multiple_header_lines_in_order() {
1033 use actix_web::test;
1034 use std::net::{Ipv4Addr, SocketAddr};
1035
1036 let ke = ClientIpKeyExtractor {
1041 trust_xff: true,
1042 trusted_hops: 1,
1043 };
1044 let peer = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)), 5000);
1045 let req = test::TestRequest::get()
1046 .peer_addr(peer)
1047 .append_header(("x-forwarded-for", "1.1.1.1"))
1048 .append_header(("x-forwarded-for", "2.2.2.2"))
1049 .to_srv_request();
1050 assert_eq!(
1051 ke.extract(&req).unwrap(),
1052 IpAddr::V4(Ipv4Addr::new(2, 2, 2, 2))
1053 );
1054 }
1055
1056 #[test]
1057 fn parse_forwarded_ip_handles_bare_port_and_bracketed_forms() {
1058 use std::net::{Ipv4Addr, Ipv6Addr};
1059
1060 assert_eq!(
1061 parse_forwarded_ip("1.2.3.4"),
1062 Some(IpAddr::V4(Ipv4Addr::new(1, 2, 3, 4)))
1063 );
1064 assert_eq!(
1065 parse_forwarded_ip("1.2.3.4:5678"),
1066 Some(IpAddr::V4(Ipv4Addr::new(1, 2, 3, 4)))
1067 );
1068 assert_eq!(
1069 parse_forwarded_ip("[::1]:9000"),
1070 Some(IpAddr::V6(Ipv6Addr::LOCALHOST))
1071 );
1072 assert_eq!(
1073 parse_forwarded_ip("[::1]"),
1074 Some(IpAddr::V6(Ipv6Addr::LOCALHOST))
1075 );
1076 assert_eq!(parse_forwarded_ip("not-an-ip"), None);
1077 }
1078
1079 #[test]
1080 fn mask_ipv6_prefix_zeroes_lower_bytes_and_leaves_ipv4() {
1081 use std::net::{Ipv4Addr, Ipv6Addr};
1082
1083 let v4 = IpAddr::V4(Ipv4Addr::new(1, 2, 3, 4));
1084 assert_eq!(mask_ipv6_prefix(v4), v4);
1085
1086 let v6 = IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6));
1087 assert_eq!(
1089 mask_ipv6_prefix(v6),
1090 IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0))
1091 );
1092 }
1093
1094 macro_rules! probe_cors_and_preflight {
1102 ($app:expr, $ip:expr, $origin:expr, $gets:expr) => {{
1103 use actix_web::http::header;
1104 use actix_web::test;
1105
1106 let mut status = actix_web::http::StatusCode::OK;
1107 let mut has_acao = false;
1108 for _ in 0..$gets {
1109 let res = test::call_service(
1110 &$app,
1111 test::TestRequest::get()
1112 .uri("/")
1113 .peer_addr($ip)
1114 .insert_header((header::ORIGIN, $origin))
1115 .to_request(),
1116 )
1117 .await;
1118 status = res.status();
1119 has_acao = res
1120 .headers()
1121 .contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN);
1122 }
1123
1124 let pre = test::call_service(
1125 &$app,
1126 test::TestRequest::default()
1127 .method(actix_web::http::Method::OPTIONS)
1128 .uri("/")
1129 .peer_addr($ip)
1130 .insert_header((header::ORIGIN, $origin))
1131 .insert_header((header::ACCESS_CONTROL_REQUEST_METHOD, "GET"))
1132 .to_request(),
1133 )
1134 .await;
1135
1136 (status, has_acao, pre.status())
1137 }};
1138 }
1139
1140 #[actix_web::test]
1152 async fn governor_inside_cors_makes_429_cors_readable_and_exempts_preflight() {
1153 use actix_web::http::StatusCode;
1154 use actix_web::{test, web, App, HttpResponse};
1155 use std::net::{IpAddr, Ipv4Addr, SocketAddr};
1156
1157 let conf = rate_limiter_config(1, 1, ClientIpKeyExtractor::peer_ip());
1159 let app = test::init_service(
1160 wrap_governor_and_cors(
1161 App::new(),
1162 &conf,
1163 true,
1164 "0.0.0.0",
1165 9562,
1166 )
1167 .route("/", web::get().to(|| async { HttpResponse::Ok().finish() })),
1168 )
1169 .await;
1170
1171 let ip = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 7)), 9999);
1172 let (get_status, get_has_acao, preflight_status) =
1173 probe_cors_and_preflight!(app, ip, "http://localhost:5173", 2);
1174
1175 assert_eq!(
1176 get_status,
1177 StatusCode::TOO_MANY_REQUESTS,
1178 "the 2nd GET past the burst must be throttled (#13 guarantee intact)"
1179 );
1180 assert!(
1181 get_has_acao,
1182 "a 429 must carry Access-Control-Allow-Origin so a browser sees a readable 429, \
1183 not an opaque network error (#169 part 2)"
1184 );
1185 assert_ne!(
1186 preflight_status,
1187 StatusCode::TOO_MANY_REQUESTS,
1188 "a CORS preflight must NOT be throttled — it never reaches Governor (#169 part 2)"
1189 );
1190 }
1191
1192 #[actix_web::test]
1201 async fn governor_outside_cors_regression_drops_cors_and_throttles_preflight() {
1202 use crate::rate_limit::RateLimit;
1203 use actix_web::http::StatusCode;
1204 use actix_web::{test, web, App, HttpResponse};
1205 use std::net::{IpAddr, Ipv4Addr, SocketAddr};
1206
1207 let conf = rate_limiter_config(1, 1, ClientIpKeyExtractor::peer_ip());
1208 let app = test::init_service(
1209 App::new()
1210 .wrap(build_cors("0.0.0.0", 9562)) .wrap(RateLimit::new(&conf)) .route("/", web::get().to(|| async { HttpResponse::Ok().finish() })),
1213 )
1214 .await;
1215
1216 let ip = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 8)), 9999);
1217 let (get_status, get_has_acao, preflight_status) =
1218 probe_cors_and_preflight!(app, ip, "http://localhost:5173", 2);
1219
1220 assert_eq!(
1221 get_status,
1222 StatusCode::TOO_MANY_REQUESTS,
1223 "still a 429 in the wrong order..."
1224 );
1225 assert!(
1226 !get_has_acao,
1227 "...but WITHOUT CORS headers — the browser-opaque failure #169 part 2 fixes"
1228 );
1229 assert_eq!(
1230 preflight_status,
1231 StatusCode::TOO_MANY_REQUESTS,
1232 "and the preflight IS throttled in the wrong order (counted against the bucket)"
1233 );
1234 }
1235
1236 #[test]
1239 fn require_limiter_rejects_nonloopback_without_limiter() {
1240 for b in ["0.0.0.0", "192.168.1.10", "::"] {
1242 assert!(
1243 require_limiter_for_nonloopback(b, false).is_err(),
1244 "{b} without a limiter must be rejected (#169 part 3)"
1245 );
1246 }
1247 }
1248
1249 #[test]
1250 fn require_limiter_allows_loopback_and_limited_binds() {
1251 for b in ["127.0.0.1", "localhost", "::1"] {
1254 assert!(
1255 require_limiter_for_nonloopback(b, false).is_ok(),
1256 "{b} loopback must stay allowed without a limiter (desktop behavior)"
1257 );
1258 }
1259 for b in ["0.0.0.0", "192.168.1.10"] {
1261 assert!(
1262 require_limiter_for_nonloopback(b, true).is_ok(),
1263 "{b} with a limiter applied must be allowed"
1264 );
1265 }
1266 }
1267
1268 #[test]
1269 fn default_csp_keeps_scripts_strict_but_allows_inline_styles() {
1270 assert!(DEFAULT_CSP.contains("script-src 'self'"));
1271 assert!(DEFAULT_CSP.contains("style-src 'self' 'unsafe-inline'"));
1272 assert!(!DEFAULT_CSP.contains("unsafe-eval"));
1273 }
1274
1275 #[test]
1276 fn connect_src_append_normalizes_explicit_origins() {
1277 let sources = parse_csp_connect_src_append(
1278 "https://bodhi.bigduu.com:9562, http://bodhi.bigduu.com:9562/",
1279 );
1280 assert_eq!(
1281 sources,
1282 vec![
1283 "https://bodhi.bigduu.com:9562".to_string(),
1284 "http://bodhi.bigduu.com:9562".to_string(),
1285 ]
1286 );
1287 }
1288
1289 #[test]
1290 fn append_connect_src_sources_extends_default_csp() {
1291 let csp = append_connect_src_sources(
1292 DEFAULT_CSP,
1293 &[
1294 "https://bodhi.bigduu.com:9562".to_string(),
1295 "http://bodhi.bigduu.com:9562".to_string(),
1296 ],
1297 );
1298
1299 assert!(csp.contains("connect-src 'self' ws: wss:"));
1300 assert!(csp.contains("https://bodhi.bigduu.com:9562"));
1301 assert!(csp.contains("http://bodhi.bigduu.com:9562"));
1302 }
1303
1304 #[test]
1305 fn invalid_override_falls_back_to_default() {
1306 let v = resolve_csp_header_value(Some("default-src 'self'\nscript-src 'self'"));
1308 let rendered = v.to_str().expect("header should be valid utf-8");
1309 assert!(rendered.contains("connect-src 'self' ws: wss:"));
1310 assert!(rendered.contains("http://127.0.0.1:*"));
1311 assert!(rendered.contains("http://localhost:*"));
1312 assert!(rendered.contains("http://bodhi.bigduu.com:9562"));
1313 assert!(rendered.contains("https://bodhi.bigduu.com:9562"));
1314 assert!(rendered.contains("style-src 'self' 'unsafe-inline'"));
1315 }
1316
1317 #[test]
1318 fn cors_allowlist_parses_hosts_and_origins() {
1319 let allow = parse_cors_allowlist(
1320 "https://app.example.com/, app.example2.com, *.example.net , http://localhost:5173",
1321 );
1322 assert!(allow.exact_origins.contains("https://app.example.com"));
1323 assert!(allow.exact_origins.contains("http://localhost:5173"));
1324 assert!(allow
1325 .hosts
1326 .contains(&HostPattern::Exact("app.example2.com".to_string())));
1327 assert!(allow
1328 .hosts
1329 .contains(&HostPattern::Suffix(".example.net".to_string())));
1330 }
1331
1332 #[test]
1333 fn cors_allowlist_matches_exact_and_wildcard_hosts() {
1334 let mut allow = CorsAllowlist::default();
1335 allow
1336 .exact_origins
1337 .insert("https://app.example.com".to_string());
1338 allow
1339 .hosts
1340 .push(HostPattern::Exact("app2.example.com".to_string()));
1341 allow
1342 .hosts
1343 .push(HostPattern::Suffix(".example.net".to_string()));
1344
1345 assert!(is_allowed_by_allowlist("https://app.example.com", &allow));
1346 assert!(is_allowed_by_allowlist(
1347 "https://app.example.com:443",
1348 &allow
1349 ));
1350 assert!(is_allowed_by_allowlist(
1351 "http://app2.example.com:5173",
1352 &allow
1353 ));
1354 assert!(is_allowed_by_allowlist("https://x.example.net", &allow));
1355 assert!(!is_allowed_by_allowlist("https://example.net", &allow));
1356 assert!(!is_allowed_by_allowlist("https://evil.com", &allow));
1357 }
1358
1359 #[test]
1360 fn local_dev_origin_allows_mac_local_and_bodhi_domain() {
1361 assert!(is_local_dev_origin("http://mac.local:1420"));
1362 assert!(is_local_dev_origin("https://mac.local:1420"));
1363 assert!(is_local_dev_origin("http://bodhi.bigduu.com:9562"));
1364 assert!(is_local_dev_origin("https://bodhi.bigduu.com:9562"));
1365 assert!(!is_local_dev_origin("http://evil.com:1420"));
1366 }
1367}