use crate::context::GarrisonResponse;
use crate::error::GarrisonResult;
pub const CORS_ALLOW_ORIGIN: &str = "Access-Control-Allow-Origin";
pub const CORS_ALLOW_HEADERS: &str = "Access-Control-Allow-Headers";
pub const CORS_ALLOW_METHODS: &str = "Access-Control-Allow-Methods";
pub const DEFAULT_CORS_ALLOW_ORIGIN: &str = "*";
pub const DEFAULT_CORS_ALLOW_HEADERS: &str = "Authorization, Content-Type";
pub const DEFAULT_CORS_ALLOW_METHODS: &str = "GET, POST, PUT, DELETE, OPTIONS";
#[cfg(feature = "web-cors")]
pub mod cors;
#[cfg(feature = "web-csrf")]
pub mod csrf;
#[cfg(feature = "web-security-headers")]
pub mod security_headers;
#[cfg(feature = "web-axum")]
pub mod request_id;
#[cfg(feature = "firewall-waf")]
pub mod axum;
#[cfg(feature = "web-cors")]
fn warn_missing_allowlist_once() {
static WARN: std::sync::Once = std::sync::Once::new();
WARN.call_once(|| {
tracing::warn!(
"{}",
crate::i18n::translate_detail("logs-cors-allowlist-not-configured", &[])
);
});
}
#[cfg(not(feature = "web-cors"))]
fn warn_no_cors_feature_once() {
static WARN: std::sync::Once = std::sync::Once::new();
WARN.call_once(|| {
tracing::warn!(
"{}",
crate::i18n::translate_detail("logs-cors-feature-disabled", &[])
);
});
}
pub fn apply_frontend_separation_cors_with_origin<R: GarrisonResponse>(
response: &mut R,
config: &crate::config::GarrisonConfig,
request_origin: Option<&str>,
) -> GarrisonResult<()> {
if config.frontend_separation {
if let Some(origin) = request_origin {
#[cfg(feature = "web-cors")]
{
let allowed = &config.cors_config.allowed_origins;
if allowed.is_empty() {
warn_missing_allowlist_once();
} else if !crate::web::cors::origin_matches(origin, allowed) {
tracing::debug!(
origin = %origin,
"{}",
crate::i18n::translate_detail("logs-cors-origin-not-allowed", &[])
);
response.set_header(CORS_ALLOW_HEADERS, DEFAULT_CORS_ALLOW_HEADERS)?;
response.set_header(CORS_ALLOW_METHODS, DEFAULT_CORS_ALLOW_METHODS)?;
response.set_header("Vary", "Origin")?;
return Ok(());
}
}
#[cfg(not(feature = "web-cors"))]
{
warn_no_cors_feature_once();
}
response.set_header(CORS_ALLOW_ORIGIN, origin)?;
}
response.set_header(CORS_ALLOW_HEADERS, DEFAULT_CORS_ALLOW_HEADERS)?;
response.set_header(CORS_ALLOW_METHODS, DEFAULT_CORS_ALLOW_METHODS)?;
response.set_header("Vary", "Origin")?;
}
Ok(())
}
pub fn apply_frontend_separation_cors<R: GarrisonResponse>(
response: &mut R,
config: &crate::config::GarrisonConfig,
) -> GarrisonResult<()> {
if config.frontend_separation {
response.set_header(CORS_ALLOW_HEADERS, DEFAULT_CORS_ALLOW_HEADERS)?;
response.set_header(CORS_ALLOW_METHODS, DEFAULT_CORS_ALLOW_METHODS)?;
response.set_header("Vary", "Origin")?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
struct WebMockResponse {
headers: HashMap<String, String>,
}
impl WebMockResponse {
fn new() -> Self {
Self {
headers: HashMap::new(),
}
}
}
impl GarrisonResponse for WebMockResponse {
fn set_status(&mut self, _code: u16) -> GarrisonResult<()> {
Ok(())
}
fn set_header(&mut self, name: &str, value: &str) -> GarrisonResult<()> {
self.headers.insert(name.to_string(), value.to_string());
Ok(())
}
fn set_cookie_with_config(
&mut self,
_name: &str,
_value: &str,
_config: &crate::config::GarrisonConfig,
) -> GarrisonResult<()> {
Ok(())
}
}
#[test]
fn t011_apply_cors_separation_adds_headers() {
let mut resp = WebMockResponse::new();
let mut config = crate::config::GarrisonConfig::default_config();
config.frontend_separation = true;
let result = apply_frontend_separation_cors(&mut resp, &config);
assert!(result.is_ok());
assert!(!resp.headers.contains_key(CORS_ALLOW_ORIGIN));
assert_eq!(
resp.headers.get(CORS_ALLOW_HEADERS),
Some(&DEFAULT_CORS_ALLOW_HEADERS.to_string())
);
assert_eq!(
resp.headers.get(CORS_ALLOW_METHODS),
Some(&DEFAULT_CORS_ALLOW_METHODS.to_string())
);
}
#[test]
fn cors_with_origin_echoes_request_origin() {
let mut resp = WebMockResponse::new();
let mut config = crate::config::GarrisonConfig::default_config();
config.frontend_separation = true;
let result = apply_frontend_separation_cors_with_origin(
&mut resp,
&config,
Some("https://example.com"),
);
assert!(result.is_ok());
assert_eq!(
resp.headers.get(CORS_ALLOW_ORIGIN),
Some(&"https://example.com".to_string()),
"应回显请求 Origin 而非 wildcard *"
);
assert_eq!(resp.headers.get("Vary"), Some(&"Origin".to_string()));
}
#[test]
fn cors_without_origin_skips_allow_origin() {
let mut resp = WebMockResponse::new();
let mut config = crate::config::GarrisonConfig::default_config();
config.frontend_separation = true;
let result = apply_frontend_separation_cors_with_origin(&mut resp, &config, None);
assert!(result.is_ok());
assert!(
!resp.headers.contains_key(CORS_ALLOW_ORIGIN),
"无 Origin 时不应设置 Allow-Origin"
);
assert_eq!(
resp.headers.get(CORS_ALLOW_HEADERS),
Some(&DEFAULT_CORS_ALLOW_HEADERS.to_string())
);
}
#[test]
fn cors_with_different_origins_echoes_differently() {
let mut config = crate::config::GarrisonConfig::default_config();
config.frontend_separation = true;
let mut resp1 = WebMockResponse::new();
apply_frontend_separation_cors_with_origin(&mut resp1, &config, Some("https://a.com"))
.unwrap();
let mut resp2 = WebMockResponse::new();
apply_frontend_separation_cors_with_origin(&mut resp2, &config, Some("https://b.com"))
.unwrap();
assert_eq!(
resp1.headers.get(CORS_ALLOW_ORIGIN),
Some(&"https://a.com".to_string())
);
assert_eq!(
resp2.headers.get(CORS_ALLOW_ORIGIN),
Some(&"https://b.com".to_string())
);
}
#[test]
fn t011_apply_cors_no_separation_no_headers() {
let mut resp = WebMockResponse::new();
let mut config = crate::config::GarrisonConfig::default_config();
config.frontend_separation = false;
let result = apply_frontend_separation_cors(&mut resp, &config);
assert!(result.is_ok());
assert!(resp.headers.is_empty());
}
#[test]
fn cors_sets_vary_origin_header() {
let mut resp = WebMockResponse::new();
let mut config = crate::config::GarrisonConfig::default_config();
config.frontend_separation = true;
let result = apply_frontend_separation_cors(&mut resp, &config);
assert!(result.is_ok());
assert_eq!(
resp.headers.get("Vary"),
Some(&"Origin".to_string()),
"应设置 Vary: Origin 确保缓存正确性"
);
}
#[test]
fn mock_response_set_cookie_with_config_is_noop_ok() {
let mut resp = WebMockResponse::new();
let config = crate::config::GarrisonConfig::default_config();
assert!(
resp.set_cookie_with_config("session", "token", &config)
.is_ok(),
"mock 实现应返回 Ok(不产生副作用)"
);
assert!(resp.headers.is_empty(), "mock 不应写入任何 header");
}
}