Skip to main content

bamboo_server/
config.rs

1//! Server configuration utilities
2//!
3//! This module provides functions to configure security headers and CORS policies
4//! for the Actix-web server based on the deployment environment.
5//!
6//! # Security Headers
7//!
8//! The server applies production-ready security headers:
9//! - X-Frame-Options: DENY
10//! - X-Content-Type-Options: nosniff
11//! - X-XSS-Protection: 1; mode=block
12//! - Referrer-Policy: strict-origin-when-cross-origin
13//! - Content-Security-Policy: Customizable CSP
14//!
15//! # CORS Configuration
16//!
17//! CORS policies are automatically adjusted based on bind address:
18//! - **localhost**: Development mode with permissive CORS
19//! - **0.0.0.0**: Docker production mode (localhost only via reverse proxy)
20//! - **Custom**: Restrictive CORS for specific addresses
21
22use 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
35/// Default sustained per-IP request rate (requests/second) for the production
36/// (network-exposed) server. Overridable via `BAMBOO_RATE_LIMIT_PER_SECOND`.
37const DEFAULT_RATE_LIMIT_PER_SECOND: u64 = 10;
38/// Default per-IP burst allowance. Overridable via `BAMBOO_RATE_LIMIT_BURST`.
39const DEFAULT_RATE_LIMIT_BURST: u32 = 20;
40
41/// Rate-limiter key extractor. Defaults to the TCP peer IP (non-spoofable), but
42/// can be switched to an OPT-IN `X-Forwarded-For` mode for reverse-proxy
43/// deployments where the peer IP is always the proxy (which would otherwise
44/// collapse the per-IP limit to global). #169.
45///
46/// SECURITY: XFF mode is only safe behind a trusted proxy — a directly-reachable
47/// server trusting XFF lets any client spoof its key and bypass the limiter. It
48/// is therefore off unless `BAMBOO_RATE_LIMIT_TRUST_XFF` is set, and it fails
49/// CLOSED to the peer IP whenever the header is absent, unparseable, or shorter
50/// than the configured trusted-hop count (so a rogue/short XFF can't inject a key).
51#[derive(Clone, Debug)]
52pub struct ClientIpKeyExtractor {
53    trust_xff: bool,
54    /// Number of trusted proxies between us and the client. The real client is
55    /// the `trusted_hops`-th entry from the RIGHT of `X-Forwarded-For` (each proxy
56    /// appends the peer it saw as the request travels outward-to-inward).
57    trusted_hops: usize,
58}
59
60impl ClientIpKeyExtractor {
61    /// The default, non-spoofable peer-IP extractor.
62    #[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        // Consider EVERY `X-Forwarded-For` header line, in order, not just the
73        // first: some proxies append a second header line rather than extending
74        // the comma-joined value, and reading only the first could let an
75        // attacker-supplied line win. Flatten all lines into one ordered list of
76        // entries (client-first ... nearest-proxy-last).
77        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        // Fail closed: a header with fewer entries than the trusted hop count is
86        // not the shape a trusted proxy chain produces, so don't trust it.
87        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            // else: fall through to the peer IP (fail closed).
104        }
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
112/// Rate-limit IPv6 clients per /56 prefix rather than per address (customers are
113/// often handed a whole prefix), mirroring `PeerIpKeyExtractor`. IPv4 is unchanged.
114fn 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
125/// Parse one `X-Forwarded-For` entry into an IP, tolerating a `host:port` or
126/// bracketed-IPv6 form some proxies emit.
127fn 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    // Bracketed IPv6 without a port, e.g. "[::1]".
136    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    // One cell replenishes every `1000 / per_second` ms (>=1), allowing `per_second`
146    // sustained req/s with a `burst` bucket. Clamp to >=1 so a bad env value can't
147    // produce a zero period/burst (which `RateLimiterConfig::new` would panic on).
148    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
156/// Build the per-IP rate-limiter config applied to the PRODUCTION (network-bound)
157/// server via the [`crate::rate_limit`] middleware. Throttles each client IP to
158/// `BAMBOO_RATE_LIMIT_PER_SECOND` (default 10) req/s with a `BAMBOO_RATE_LIMIT_BURST`
159/// (default 20) burst, returning 429 Too Many Requests when exceeded. Desktop
160/// (localhost) mode does not apply it. #13.
161///
162/// Keys on the TCP PEER IP by default (non-spoofable). Behind a reverse proxy
163/// every client shares the proxy's IP, collapsing the per-IP limit to global; set
164/// `BAMBOO_RATE_LIMIT_TRUST_XFF=1` to key on `X-Forwarded-For` instead (with
165/// `BAMBOO_RATE_LIMIT_TRUSTED_HOPS`, default one hop). #169. XFF mode is OPT-IN
166/// because trusting the header when NOT behind a trusted proxy lets any client
167/// spoof its rate-limit key; see [`ClientIpKeyExtractor`].
168pub 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
209/// True when `bind` is a loopback/desktop address, for which the per-IP DoS
210/// rate limiter ([`build_rate_limiter`], #13) is intentionally SKIPPED. The
211/// desktop sidecar serves the local frontend, which legitimately bursts ~45
212/// hashed `/assets/*` requests on load and would otherwise trip the 429 limit
213/// (`burst` default 20). Mirrors the loopback special-casing already used for
214/// CORS; network binds (`0.0.0.0`) are still throttled.
215///
216/// Classification is via [`IpAddr::is_loopback`] (so the whole `127.0.0.0/8`
217/// range, not just `127.0.0.1`, and a bracketed IPv6 literal like `[::1]` are
218/// correctly recognized) plus a literal `"localhost"` match, since that's a
219/// hostname rather than an address `IpAddr` can parse. #428: previously this
220/// was a strict string allowlist (`127.0.0.1` / `localhost` / `::1`), so e.g.
221/// `127.0.0.2` or `[::1]` were misclassified as non-loopback — which failed
222/// SAFE (the limiter was applied) but was still wrong.
223pub 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
240/// Bind-aware limiter guard (#169 part 3).
241///
242/// The per-IP rate limiter (#13) is what protects a network-exposed bind from a
243/// DoS flood. Some serve paths (notably [`crate::server::WebService::start_with_bind`])
244/// never install the limiter, and every bind-accepting path takes an arbitrary
245/// `bind` string — so a caller COULD start an unthrottled server on `0.0.0.0`
246/// (or another routable interface) and silently re-open the surface #13 closed.
247///
248/// This guard rejects exactly that combination: a NON-loopback bind with NO
249/// limiter applied. Loopback binds (see [`is_loopback_bind`]) are exempt because
250/// the desktop sidecar intentionally runs un-throttled to serve its local
251/// frontend — so this never weakens the established localhost behavior. Paths
252/// that DO apply the limiter pass `limiter_applied = true` and are always
253/// accepted, regardless of bind.
254pub 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
266// Keep the default CSP reasonably strict while remaining compatible with the Lotus UI runtime.
267// Lotus + Ant Design inject runtime styles, so `style-src 'unsafe-inline'` is required for the
268// current frontend bundle. Keep scripts strict (no `unsafe-eval`) and allow operators to override
269// via `BAMBOO_CSP` when needed.
270const 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            // Avoid failing to start due to a malformed override; fall back to the safe default.
366            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/// CORS allowlist sourced from env vars.
377///
378/// Supported entries:
379/// - Exact origins: `https://app.example.com`, `http://localhost:5173`
380/// - Hosts (any scheme/port): `app.example.com`, `127.0.0.1`
381/// - Wildcard subdomains (any scheme/port): `*.example.com`
382#[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), // stored with leading dot, e.g. ".example.com"
392}
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            // Exact origin match. Normalize to an origin-like form so common inputs
433            // (trailing slashes, explicit :443, etc.) still match real Origin headers.
434            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        // Host-based match.
449        let host = token.to_ascii_lowercase();
450        if let Some(rest) = host.strip_prefix("*.") {
451            // Wildcard subdomains.
452            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    // Comma-separated list. Examples:
465    //   BAMBOO_CORS_ALLOW_ORIGINS="https://app.example.com,http://localhost:5173,*.example.com"
466    //   BAMBOO_CORS_ALLOW_ORIGINS="app.example.com,127.0.0.1"
467    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    // Keep a strict string match fallback (covers unusual schemes like tauri://).
495    if allow.exact_origins.contains(origin) {
496        return true;
497    }
498
499    // Try to parse a host from the origin. Origin header values are serialized origins like:
500    // - https://app.example.com
501    // - http://127.0.0.1:5173
502    // - http://[::1]:5173
503    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                    // Ensure we only match subdomains, not the apex itself when suffix is ".example.com".
523                    // (host == "example.com" should not match ".example.com".)
524                    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
546/// Build security headers middleware for production deployments
547///
548/// Applies standard security headers to all HTTP responses:
549/// - Prevents clickjacking (X-Frame-Options)
550/// - Prevents MIME type sniffing (X-Content-Type-Options)
551/// - Enables XSS protection (X-XSS-Protection)
552/// - Controls referrer information (Referrer-Policy)
553/// - Restricts resource loading (Content-Security-Policy)
554///
555/// # Example
556///
557/// ```rust,ignore
558/// use actix_web::App;
559/// use bamboo_agent::server::config::build_security_headers;
560///
561/// let app = App::new()
562///     .wrap(build_security_headers());
563/// ```
564pub 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        // Note: customize at runtime via `BAMBOO_CSP` if your frontend requires a relaxed policy.
574        .add((header::CONTENT_SECURITY_POLICY, csp_value))
575}
576
577/// Long-cache content-hashed frontend assets at the proxy/CDN edge.
578///
579/// Vite emits hashed filenames under `/assets/` (e.g. `main-B6snAd4S.css`), so
580/// they are inherently immutable — any content change yields a NEW filename.
581/// Tagging them `immutable, max-age=1y` lets Cloudflare and browsers cache them
582/// at the edge instead of round-tripping every chunk through the tunnel to
583/// origin. Besides being faster, this removes the transient per-asset failures
584/// (an occasional reset of one of many parallel preload requests over a
585/// cloudflared tunnel) that surface in the browser as Vite's
586/// "Unable to preload CSS for …" / "Failed to fetch dynamically imported module".
587///
588/// Only `/assets/*` is affected; `index.html` and API routes are left untouched
589/// so they always serve fresh (a new deploy must be picked up immediately).
590pub 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
605/// Build CORS middleware based on bind address and port
606///
607/// Automatically configures CORS policy based on deployment environment:
608///
609/// # Development Mode (localhost)
610///
611/// When binding to `127.0.0.1`, `localhost`, or `::1`:
612/// - Allows all origins, methods, and headers
613/// - Suitable for local development
614/// - Safe because server is only accessible locally
615///
616/// # Docker Production Mode (0.0.0.0)
617///
618/// When binding to `0.0.0.0`:
619/// - Only allows `http://localhost:{port}`
620/// - Requires reverse proxy for external access
621/// - Restrictive CORS for security
622///
623/// # Custom Address
624///
625/// For any other bind address:
626/// - Only allows that specific address
627/// - Most restrictive configuration
628///
629/// # Arguments
630///
631/// * `bind_addr` - The address the server binds to
632/// * `port` - The port number the server listens on
633///
634/// # Example
635///
636/// ```rust,ignore
637/// use actix_web::HttpServer;
638/// use bambooagent::server::config::build_cors;
639///
640/// let cors = build_cors("127.0.0.1", 9562);
641/// // Use cors middleware in HttpServer
642/// ```
643pub 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        // Development/Desktop mode. Keep origins permissive for local/Tauri callers, but do not
648        // combine wildcard `Access-Control-Allow-Origin: *` with credentialed requests. The Lotus
649        // client sends `credentials: "include"` so browsers require a concrete echoed Origin.
650        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        // Docker/sidecar mode.
676        //
677        // We still want to restrict origins to "local" callers, but ports and schemes
678        // can differ between:
679        // - Vite dev server (http://127.0.0.1:5173, http://localhost:5173)
680        // - Tauri webview (tauri://localhost, https://tauri.localhost)
681        // - Reverse proxy setups (http://localhost:{port})
682        //
683        // Accept any localhost/loopback origin (any port) and common Tauri origins.
684        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                // Explicit allowlist (for remote UI domains, etc).
693                if is_allowed_by_allowlist(o, &allowlist) {
694                    return true;
695                }
696
697                // Common local HTTP(S) dev origins (any port).
698                if is_local_dev_origin(o) {
699                    return true;
700                }
701
702                // Tauri webview origins (vary by version/config).
703                if o == "tauri://localhost"
704                    || o == "https://tauri.localhost"
705                    || o == "http://tauri.localhost"
706                {
707                    return true;
708                }
709
710                // Some setups might load the UI from the same port as the backend.
711                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            // This server is commonly used as a local relay for multiple upstream clients
720            // (OpenAI/Anthropic/Gemini). Avoid CORS preflight failures by not restricting methods.
721            .allow_any_method()
722            // OpenAI's official JS client sends additional `x-stainless-*` headers which would
723            // otherwise fail preflight; keep headers permissive while origin stays locked down.
724            .allow_any_header()
725            .supports_credentials()
726            .max_age(3600)
727    } else {
728        // Custom bind address - restrictive by default, but allow explicit env allowlist.
729        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                // Allow same-host origins (any scheme/port) for the bind address itself.
747                // This keeps the default "tight" without requiring users to enumerate ports.
748                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
766/// Apply the Governor (rate limiter) + CORS middleware pair to `app`, IN THE
767/// ORDER THAT MATTERS (#169 part 2, #428).
768///
769/// Governor is wrapped first (the INNER layer) and `build_cors` second (the
770/// OUTER layer). This ordering is load-bearing: (1) a genuine CORS preflight
771/// is short-circuited by CORS and never reaches Governor, so it isn't counted
772/// against the rate-limit bucket; and (2) a 429 from Governor propagates back
773/// OUT through CORS, which adds `Access-Control-Allow-Origin` so a browser
774/// receives a readable 429 instead of an opaque network error. Reversing the
775/// two wraps regresses both (see the `governor_inside_cors_*` /
776/// `governor_outside_cors_regression_*` tests below).
777///
778/// This is the ONE place the wrap order is spelled out — every production app
779/// factory (`entrypoints.rs`, `web_service.rs`) AND the ordering-invariant
780/// regression tests call this helper instead of each re-declaring the two
781/// `.wrap()` calls inline. That means a future edit can no longer swap the
782/// order in just one of those call sites without also changing this function,
783/// and changing this function is exactly what the regression tests cover
784/// (#428 — prior to this, the tests built their own hand-rolled `App` with the
785/// order spelled out separately from production, so a production-only swap
786/// would NOT have failed them).
787pub 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        // 0 per_second / 0 burst would make finish() reject; the clamps keep it
826        // valid (no panic).
827        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        // Desktop sidecar binds must be exempt (frontend bursts asset requests);
834        // network-exposed binds must stay throttled.
835        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        // #428: a strict `127.0.0.1`/`localhost`/`::1` string allowlist
849        // misclassifies other loopback forms as non-loopback (failing safe,
850        // but wrong). Classifying via `IpAddr::is_loopback` fixes it.
851        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        // A hashed `/assets/*` file gets the immutable long-cache header.
876        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        // `index.html` (and anything outside `/assets/`) must stay fresh so a new
888        // deploy is picked up immediately — no long-cache header added.
889        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        // burst=2: the first two requests from an IP pass, the rest are throttled.
905        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        // A DIFFERENT client IP has its OWN bucket — proving per-IP keying (a
927        // global bucket would 429 this too); guards against a regression to a
928        // global key extractor.
929        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        // Default (trust_xff = false): a client-supplied XFF must be ignored so it
947        // can't spoof its rate-limit key on a directly-exposed server.
948        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        // trusted_hops = 1: only the entry OUR proxy appended (rightmost) is
966        // trusted; a client prepending a fake IP can't change the key.
967        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); // proxy
972        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        // Fewer entries than trusted hops → not a trusted-proxy shape → peer IP.
1014        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        // No XFF at all → peer IP.
1024        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        // A proxy chain that appends a SECOND header line rather than extending
1037        // the comma-joined value: the entries must be treated as one ordered list
1038        // (client-first ... proxy-last), so 1-hop still selects the true rightmost
1039        // entry authored by the nearest proxy — not the first line's value.
1040        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        // /56: first 7 bytes preserved, remaining 9 zeroed.
1088        assert_eq!(
1089            mask_ipv6_prefix(v6),
1090            IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0))
1091        );
1092    }
1093
1094    // --- #169 part 2: preflight/CORS-safe 429 -----------------------------------
1095    //
1096    // These build the REAL production wrap order (Governor registered *before*
1097    // CORS, i.e. Governor is the INNER wrap and CORS is OUTER) and a browser
1098    // request, then assert what a browser actually receives. `probe!` drains the
1099    // burst with `gets` GETs (allowed Origin) then sends one CORS preflight,
1100    // yielding `(last_get_status, last_get_has_acao, preflight_status)`.
1101    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    /// The production order — enforced by the shared [`wrap_governor_and_cors`]
1141    /// helper (Governor inner, CORS outer) and used by BOTH the real app
1142    /// factories (`entrypoints.rs`, `web_service.rs`) and this test — must give
1143    /// a browser a READABLE 429: the throttled response carries
1144    /// `Access-Control-Allow-Origin`, and a CORS preflight is NOT counted
1145    /// against the bucket (CORS answers it before it reaches Governor).
1146    ///
1147    /// Because this test calls the SAME helper the production factories call
1148    /// (rather than hand-rolling the wrap order itself, #428), a future edit
1149    /// that swaps the wrap order in `wrap_governor_and_cors` — the only place
1150    /// production spells the order out — fails this test.
1151    #[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        // burst=1: the 2nd GET from an IP is throttled.
1158        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                /* apply_rate_limit */ 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    /// Guards the ordering as load-bearing: the REVERSED order
1193    /// (`.wrap(build_cors).wrap(Governor)` → Governor OUTSIDE CORS) is the pre-fix
1194    /// state that motivated #169 — a 429 escapes without CORS headers and the
1195    /// preflight is throttled. If a refactor ever flips the wrap order back
1196    /// inside [`wrap_governor_and_cors`], the positive test above breaks; this
1197    /// test intentionally does NOT use that helper — it hand-rolls the WRONG
1198    /// order to document *why* the order matters, by asserting the broken
1199    /// behavior that would result.
1200    #[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)) // inner (WRONG)
1211                .wrap(RateLimit::new(&conf)) // outer (WRONG)
1212                .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    // --- #169 part 3: bind-aware limiter guard ----------------------------------
1237
1238    #[test]
1239    fn require_limiter_rejects_nonloopback_without_limiter() {
1240        // The dangerous combination: a routable bind with no limiter → rejected.
1241        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        // Loopback with no limiter is preserved (desktop sidecar, intentionally
1252        // un-throttled) — the guard must NOT weaken it.
1253        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        // A non-loopback bind IS allowed once a limiter is applied.
1260        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        // Header values cannot contain newlines.
1307        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}