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-waf")]
pub mod waf;
#[cfg(feature = "web-cors")]
pub mod cors;
#[cfg(feature = "web-csrf")]
pub mod csrf;
#[cfg(feature = "firewall-waf")]
pub mod axum;
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_ORIGIN, DEFAULT_CORS_ALLOW_ORIGIN)?;
response.set_header(CORS_ALLOW_HEADERS, DEFAULT_CORS_ALLOW_HEADERS)?;
response.set_header(CORS_ALLOW_METHODS, DEFAULT_CORS_ALLOW_METHODS)?;
}
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_eq!(
resp.headers.get(CORS_ALLOW_ORIGIN),
Some(&DEFAULT_CORS_ALLOW_ORIGIN.to_string())
);
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 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());
}
}