use crate::config::GarrisonConfig;
use crate::context::token_extract::{extract_token_from_request_parts, parse_cookie_value};
use crate::context::{GarrisonContext, GarrisonRequest, GarrisonResponse, GarrisonStorage};
use crate::error::{GarrisonError, GarrisonResult};
use std::collections::HashMap;
use warp::http::header::{HeaderMap, HeaderName, HeaderValue};
use warp::http::StatusCode;
pub struct WarpRequest {
path: String,
method: String,
headers: HeaderMap,
body_bytes: Vec<u8>,
}
impl WarpRequest {
pub fn new(path: String, method: String, headers: HeaderMap) -> Self {
Self {
path,
method,
headers,
body_bytes: Vec::new(),
}
}
pub fn with_body(
path: String,
method: String,
headers: HeaderMap,
body_bytes: Vec<u8>,
) -> Self {
Self {
path,
method,
headers,
body_bytes,
}
}
}
impl GarrisonRequest for WarpRequest {
fn path(&self) -> GarrisonResult<String> {
Ok(self.path.clone())
}
fn method(&self) -> GarrisonResult<String> {
Ok(self.method.clone())
}
fn header(&self, name: &str) -> GarrisonResult<Option<String>> {
let header_name: HeaderName = name.parse().map_err(|e| {
GarrisonError::Context(format!("ctx-invalid-header-name::{}::{}", name, e))
})?;
Ok(self
.headers
.get(header_name)
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string()))
}
fn cookie(&self, name: &str) -> GarrisonResult<Option<String>> {
let cookie_header = self
.headers
.get("cookie")
.and_then(|v| v.to_str().ok())
.unwrap_or("");
Ok(parse_cookie_value(cookie_header, name))
}
fn get_token(&self, config: &GarrisonConfig) -> GarrisonResult<Option<String>> {
extract_token_from_request_parts(
config,
&self.body_bytes,
&self.method,
|name| self.header(name),
|name| self.cookie(name),
)
}
}
pub struct WarpResponse {
headers: HeaderMap,
status: StatusCode,
}
impl WarpResponse {
pub fn new() -> Self {
Self {
headers: HeaderMap::new(),
status: StatusCode::OK,
}
}
}
impl Default for WarpResponse {
fn default() -> Self {
Self::new()
}
}
impl GarrisonResponse for WarpResponse {
fn set_status(&mut self, code: u16) -> GarrisonResult<()> {
self.status = StatusCode::from_u16(code).map_err(|e| {
GarrisonError::Context(format!("ctx-invalid-status-code::{}::{}", code, e))
})?;
Ok(())
}
fn set_header(&mut self, name: &str, value: &str) -> GarrisonResult<()> {
let header_name: HeaderName = name.parse().map_err(|e| {
GarrisonError::Context(format!("ctx-invalid-header-name::{}::{}", name, e))
})?;
let header_value = HeaderValue::from_str(value).map_err(|e| {
GarrisonError::Context(format!("ctx-invalid-header-value::{}::{}", value, e))
})?;
self.headers.insert(header_name, header_value);
Ok(())
}
}
pub struct WarpStorage {
map: HashMap<String, String>,
}
impl WarpStorage {
pub fn new() -> Self {
Self {
map: HashMap::new(),
}
}
}
impl Default for WarpStorage {
fn default() -> Self {
Self::new()
}
}
impl GarrisonStorage for WarpStorage {
fn set(&mut self, key: &str, value: &str) -> GarrisonResult<()> {
self.map.insert(key.to_string(), value.to_string());
Ok(())
}
fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
Ok(self.map.get(key).cloned())
}
fn delete(&mut self, key: &str) -> GarrisonResult<()> {
self.map.remove(key);
Ok(())
}
}
pub struct WarpContext {
request_data: WarpRequest,
response: WarpResponse,
storage: WarpStorage,
}
impl WarpContext {
pub fn new(path: String, method: String, headers: HeaderMap) -> Self {
Self {
request_data: WarpRequest::new(path, method, headers),
response: WarpResponse::new(),
storage: WarpStorage::new(),
}
}
pub fn with_body(
path: String,
method: String,
headers: HeaderMap,
body_bytes: Vec<u8>,
) -> Self {
Self {
request_data: WarpRequest::with_body(path, method, headers, body_bytes),
response: WarpResponse::new(),
storage: WarpStorage::new(),
}
}
pub fn raw_response(&self) -> &WarpResponse {
&self.response
}
pub fn raw_response_mut(&mut self) -> &mut WarpResponse {
&mut self.response
}
pub fn raw_storage(&self) -> &WarpStorage {
&self.storage
}
pub fn raw_storage_mut(&mut self) -> &mut WarpStorage {
&mut self.storage
}
}
impl GarrisonContext for WarpContext {
fn request(&self) -> GarrisonResult<Box<dyn GarrisonRequest>> {
Ok(Box::new(WarpRequest::with_body(
self.request_data.path.clone(),
self.request_data.method.clone(),
self.request_data.headers.clone(),
self.request_data.body_bytes.clone(),
)))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn make_headers(headers: &[(&str, &str)]) -> HeaderMap {
let mut map = HeaderMap::new();
for (name, value) in headers {
map.insert(
name.parse::<HeaderName>().unwrap(),
value.parse::<HeaderValue>().unwrap(),
);
}
map
}
fn make_warp_request(path: &str, method: &str, headers: &[(&str, &str)]) -> WarpRequest {
WarpRequest::new(path.to_string(), method.to_string(), make_headers(headers))
}
#[test]
fn warp_request_path() {
let req = make_warp_request("/api/users", "GET", &[]);
assert_eq!(req.path().unwrap(), "/api/users");
}
#[test]
fn warp_request_method() {
let req = make_warp_request("/", "POST", &[]);
assert_eq!(req.method().unwrap(), "POST");
}
#[test]
fn warp_request_header_returns_value() {
let req = make_warp_request("/", "GET", &[("X-Token", "abc123")]);
assert_eq!(req.header("X-Token").unwrap(), Some("abc123".to_string()));
assert_eq!(req.header("Not-Exist").unwrap(), None);
}
#[test]
fn warp_request_cookie_returns_value() {
let req = make_warp_request(
"/",
"GET",
&[("Cookie", "garrison_token=tok123; other=val")],
);
assert_eq!(
req.cookie("garrison_token").unwrap(),
Some("tok123".to_string())
);
assert_eq!(req.cookie("other").unwrap(), Some("val".to_string()));
assert_eq!(req.cookie("missing").unwrap(), None);
}
#[test]
fn warp_request_cookie_empty_header_returns_none() {
let req = make_warp_request("/", "GET", &[]);
assert_eq!(req.cookie("any").unwrap(), None);
}
#[test]
fn warp_request_cookie_skips_pair_without_equals() {
let req = make_warp_request("/", "GET", &[("Cookie", "invalidpair; valid=val")]);
assert_eq!(req.cookie("valid").unwrap(), Some("val".to_string()));
assert_eq!(req.cookie("invalidpair").unwrap(), None);
}
#[test]
fn warp_request_header_invalid_name_errors() {
let _locale_guard = crate::i18n::set_locale(crate::i18n::GarrisonLocale::Zh);
let req = make_warp_request("/", "GET", &[]);
let result = req.header("invalid header");
assert!(result.is_err());
let err = result.unwrap_err();
assert!(matches!(err, GarrisonError::Context(_)));
assert!(err.to_string().contains("非法 header 名称"));
}
#[test]
fn warp_request_get_token_from_header() {
let req = make_warp_request("/", "GET", &[("Authorization", "Bearer my_token_123")]);
let config = GarrisonConfig::default_config();
let token = req.get_token(&config).unwrap();
assert_eq!(token, Some("my_token_123".to_string()));
}
#[test]
fn warp_request_bearer_prefix_case_insensitive() {
let config = GarrisonConfig::default_config();
for prefix in &["Bearer", "bearer", "BEARER", "BeArEr"] {
let auth_value = format!("{} tok_{}", prefix, prefix);
let req = make_warp_request("/", "GET", &[("Authorization", auth_value.as_str())]);
let token = req.get_token(&config).unwrap();
assert_eq!(
token,
Some(format!("tok_{}", prefix)),
"前缀 '{}' 应能提取 token(大小写不敏感)",
prefix
);
}
}
#[test]
fn warp_request_get_token_from_custom_header() {
let req = make_warp_request("/", "GET", &[("garrison_token", "header_token_456")]);
let config = GarrisonConfig::default_config();
let token = req.get_token(&config).unwrap();
assert_eq!(token, Some("header_token_456".to_string()));
}
#[test]
fn warp_request_get_token_from_cookie() {
let req = make_warp_request("/", "GET", &[("Cookie", "garrison_token=cookie_token_789")]);
let config = GarrisonConfig::default_config();
let token = req.get_token(&config).unwrap();
assert_eq!(token, Some("cookie_token_789".to_string()));
}
#[test]
fn warp_request_get_token_header_priority_over_cookie() {
let req = make_warp_request(
"/",
"GET",
&[
("Authorization", "Bearer header_token"),
("Cookie", "garrison_token=cookie_token"),
],
);
let config = GarrisonConfig::default_config();
let token = req.get_token(&config).unwrap();
assert_eq!(token, Some("header_token".to_string()));
}
#[test]
fn warp_request_get_token_returns_none_when_missing() {
let req = make_warp_request("/", "GET", &[]);
let config = GarrisonConfig::default_config();
let token = req.get_token(&config).unwrap();
assert_eq!(token, None);
}
#[test]
fn warp_request_get_token_skips_header_when_disabled() {
let req = make_warp_request("/", "GET", &[("Authorization", "Bearer header_token")]);
let mut config = GarrisonConfig::default_config();
config.is_read_header = false;
config.is_read_cookie = false;
let token = req.get_token(&config).unwrap();
assert_eq!(token, None);
}
#[test]
fn warp_response_set_status() {
let mut resp = WarpResponse::new();
resp.set_status(401).unwrap();
assert_eq!(resp.status, StatusCode::UNAUTHORIZED);
}
#[test]
fn warp_response_set_header() {
let mut resp = WarpResponse::new();
resp.set_header("Authorization", "my_token").unwrap();
assert_eq!(
resp.headers
.get("Authorization")
.and_then(|v| v.to_str().ok()),
Some("my_token")
);
}
#[test]
fn warp_response_set_cookie_writes_header() {
let mut resp = WarpResponse::new();
resp.set_cookie("garrison_token", "cookie_value").unwrap();
let set_cookie = resp
.headers
.get("Set-Cookie")
.and_then(|v| v.to_str().ok())
.unwrap();
assert!(set_cookie.contains("garrison_token=cookie_value"));
assert!(set_cookie.contains("HttpOnly"));
assert!(set_cookie.contains("Secure"));
assert!(set_cookie.contains("SameSite=Lax"));
assert!(set_cookie.contains("Path=/"));
}
#[test]
fn warp_response_set_cookie_with_config_dev() {
let mut resp = WarpResponse::new();
let mut config = GarrisonConfig::default_config();
config.cookie_secure = false;
config.cookie_same_site = "Strict".to_string();
resp.set_cookie_with_config("token", "v", &config).unwrap();
let set_cookie = resp
.headers
.get("Set-Cookie")
.and_then(|v| v.to_str().ok())
.unwrap();
assert!(set_cookie.contains("HttpOnly"));
assert!(!set_cookie.contains("Secure"));
assert!(set_cookie.contains("SameSite=Strict"));
}
#[test]
fn warp_response_set_cookie_none_insecure_downgrades_to_lax() {
let mut resp = WarpResponse::new();
let mut config = GarrisonConfig::default_config();
config.cookie_secure = false;
config.cookie_same_site = "None".to_string();
resp.set_cookie_with_config("token", "v", &config).unwrap();
let set_cookie = resp
.headers
.get("Set-Cookie")
.and_then(|v| v.to_str().ok())
.unwrap();
assert!(
set_cookie.contains("SameSite=Lax"),
"应降级为 SameSite=Lax,实际: {}",
set_cookie
);
assert!(
!set_cookie.contains("SameSite=None"),
"不得输出 SameSite=None,实际: {}",
set_cookie
);
assert!(!set_cookie.contains("Secure"), "实际: {}", set_cookie);
}
#[test]
fn warp_response_set_status_invalid_code_errors() {
let _locale_guard = crate::i18n::set_locale(crate::i18n::GarrisonLocale::Zh);
let mut resp = WarpResponse::new();
let result = resp.set_status(1000);
assert!(result.is_err());
let err = result.unwrap_err();
assert!(matches!(err, GarrisonError::Context(_)));
assert!(err.to_string().contains("非法状态码"));
}
#[test]
fn warp_response_set_header_invalid_value_errors() {
let _locale_guard = crate::i18n::set_locale(crate::i18n::GarrisonLocale::Zh);
let mut resp = WarpResponse::new();
let result = resp.set_header("X-Test", "bad\0value");
assert!(result.is_err());
let err = result.unwrap_err();
assert!(matches!(err, GarrisonError::Context(_)));
assert!(err.to_string().contains("非法 header 值"));
}
#[test]
fn warp_response_set_header_invalid_name_errors() {
let mut resp = WarpResponse::new();
let result = resp.set_header("invalid header", "value");
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), GarrisonError::Context(_)));
}
#[test]
fn warp_response_default_impl() {
let resp = WarpResponse::default();
assert_eq!(resp.status, StatusCode::OK);
assert!(resp.headers.is_empty());
}
#[test]
fn warp_storage_set_get_delete() {
let mut storage = WarpStorage::new();
storage.set("trace_id", "abc-123").unwrap();
assert_eq!(
storage.get("trace_id").unwrap(),
Some("abc-123".to_string())
);
storage.delete("trace_id").unwrap();
assert_eq!(storage.get("trace_id").unwrap(), None);
}
#[test]
fn warp_storage_request_isolation() {
let mut storage_a = WarpStorage::new();
storage_a.set("trace_id", "A").unwrap();
let mut storage_b = WarpStorage::new();
storage_b.set("trace_id", "B").unwrap();
assert_eq!(storage_a.get("trace_id").unwrap(), Some("A".to_string()));
assert_eq!(storage_b.get("trace_id").unwrap(), Some("B".to_string()));
}
#[test]
fn warp_storage_missing_key_returns_none() {
let storage = WarpStorage::new();
assert_eq!(storage.get("missing").unwrap(), None);
}
#[test]
fn warp_storage_default_impl() {
let storage = WarpStorage::default();
assert_eq!(storage.get("any").unwrap(), None);
}
#[test]
fn warp_context_request_returns_box() {
let ctx = WarpContext::new(
"/api/test".to_string(),
"GET".to_string(),
make_headers(&[("Authorization", "Bearer abc")]),
);
let request = ctx.request().unwrap();
let config = GarrisonConfig::default_config();
let token = request.get_token(&config).unwrap();
assert_eq!(token, Some("abc".to_string()));
}
#[test]
fn warp_context_wrapper_path() {
let ctx = WarpContext::new(
"/api/v1/users".to_string(),
"GET".to_string(),
make_headers(&[]),
);
let request = ctx.request().unwrap();
assert_eq!(request.path().unwrap(), "/api/v1/users");
}
#[test]
fn warp_context_wrapper_method() {
let ctx = WarpContext::new("/".to_string(), "PUT".to_string(), make_headers(&[]));
let request = ctx.request().unwrap();
assert_eq!(request.method().unwrap(), "PUT");
}
#[test]
fn warp_context_wrapper_header() {
let ctx = WarpContext::new(
"/".to_string(),
"GET".to_string(),
make_headers(&[("X-Custom", "hello")]),
);
let request = ctx.request().unwrap();
assert_eq!(
request.header("X-Custom").unwrap(),
Some("hello".to_string())
);
assert_eq!(request.header("Missing").unwrap(), None);
}
#[test]
fn warp_context_wrapper_get_token_from_cookie() {
let ctx = WarpContext::new(
"/".to_string(),
"GET".to_string(),
make_headers(&[("Cookie", "garrison_token=cookie_tok")]),
);
let request = ctx.request().unwrap();
let mut config = GarrisonConfig::default_config();
config.is_read_header = false;
config.is_read_cookie = true;
let token = request.get_token(&config).unwrap();
assert_eq!(token, Some("cookie_tok".to_string()));
}
#[test]
fn warp_context_raw_response_mut_writable() {
let mut ctx = WarpContext::new("/".to_string(), "GET".to_string(), make_headers(&[]));
ctx.raw_response_mut().set_status(404).unwrap();
ctx.raw_response_mut()
.set_header("X-Trace", "trace-123")
.unwrap();
assert_eq!(ctx.raw_response().status, StatusCode::NOT_FOUND);
}
#[test]
fn warp_context_raw_storage_mut_writable() {
let mut ctx = WarpContext::new("/".to_string(), "GET".to_string(), make_headers(&[]));
ctx.raw_storage_mut().set("key", "value").unwrap();
assert_eq!(
ctx.raw_storage().get("key").unwrap(),
Some("value".to_string())
);
}
#[test]
fn extract_token_from_body_when_is_read_body_true() {
let req = WarpRequest::with_body(
"/".to_string(),
"POST".to_string(),
make_headers(&[("Content-Type", "application/json")]),
br#"{"garrison_token":"body_token_456"}"#.to_vec(),
);
let mut config = GarrisonConfig::default_config();
config.is_read_header = false;
config.is_read_cookie = false;
config.is_read_body = true;
let token = req.get_token(&config).unwrap();
assert_eq!(token, Some("body_token_456".to_string()));
}
#[test]
fn warp_context_with_body_extracts_token_from_body() {
let ctx = WarpContext::with_body(
"/".to_string(),
"POST".to_string(),
make_headers(&[("Content-Type", "application/json")]),
br#"{"garrison_token":"ctx_body_token"}"#.to_vec(),
);
let request = ctx.request().unwrap();
let mut config = GarrisonConfig::default_config();
config.is_read_header = false;
config.is_read_cookie = false;
config.is_read_body = true;
let token = request.get_token(&config).unwrap();
assert_eq!(
token,
Some("ctx_body_token".to_string()),
"WarpContext::with_body 应通过 request() 传递 body_bytes,使 get_token 能从 body 提取 token"
);
}
#[test]
fn c7_warp_request_get_method_skips_body_token() {
let req = WarpRequest::with_body(
"/".to_string(),
"GET".to_string(),
make_headers(&[("Content-Type", "application/json")]),
br#"{"garrison_token":"body_token_should_be_skipped"}"#.to_vec(),
);
let mut config = GarrisonConfig::default_config();
config.is_read_header = false;
config.is_read_cookie = false;
config.is_read_body = true;
let token = req.get_token(&config).unwrap();
assert_eq!(
token, None,
"C7: GET 方法不应从 body 提取 token(防 body 注入攻击)"
);
}
#[test]
fn c7_warp_request_post_put_patch_methods_allow_body_token() {
for method in &["POST", "PUT", "PATCH"] {
let body_bytes = format!(r#"{{"garrison_token":"tok_{}"}}"#, method).into_bytes();
let req = WarpRequest::with_body(
"/".to_string(),
method.to_string(),
make_headers(&[("Content-Type", "application/json")]),
body_bytes,
);
let mut config = GarrisonConfig::default_config();
config.is_read_header = false;
config.is_read_cookie = false;
config.is_read_body = true;
let token = req.get_token(&config).unwrap();
assert_eq!(
token,
Some(format!("tok_{}", method)),
"C7: {} 方法应允许从 body 提取 token",
method
);
}
}
#[test]
fn c7_warp_context_get_method_skips_body_token_via_wrapper() {
let ctx = WarpContext::with_body(
"/".to_string(),
"GET".to_string(),
make_headers(&[("Content-Type", "application/json")]),
br#"{"garrison_token":"wrapper_skipped"}"#.to_vec(),
);
let request = ctx.request().unwrap();
let mut config = GarrisonConfig::default_config();
config.is_read_header = false;
config.is_read_cookie = false;
config.is_read_body = true;
let token = request.get_token(&config).unwrap();
assert_eq!(
token, None,
"C7: 通过 WarpContext 的 GET 方法不应从 body 提取 token"
);
}
}