use crate::config::GarrisonConfig;
use crate::error::{GarrisonError, GarrisonResult};
use http::HeaderMap;
pub trait HeaderLookup {
fn get_header(&self, name: &str) -> Option<&str>;
}
impl HeaderLookup for HeaderMap {
fn get_header(&self, name: &str) -> Option<&str> {
self.get(name).and_then(|v| v.to_str().ok())
}
}
pub fn strip_bearer_prefix(auth_str: &str) -> Option<&str> {
let prefix = "bearer ";
let head = auth_str.get(..prefix.len())?;
if head.eq_ignore_ascii_case(prefix) {
let rest = &auth_str[prefix.len()..];
if rest.is_empty() {
return None;
}
Some(rest)
} else {
None
}
}
pub fn parse_cookie_value(cookie_header: &str, name: &str) -> Option<String> {
if cookie_header.is_empty() {
return None;
}
for cookie in cookie_header.split(';') {
let cookie = cookie.trim();
if let Some(eq_pos) = cookie.find('=') {
let (k, v) = cookie.split_at(eq_pos);
if k == name {
return v.get(1..).map(|s| s.to_string());
}
}
}
None
}
pub fn is_body_token_allowed_method(method: &str) -> bool {
method.eq_ignore_ascii_case("POST")
|| method.eq_ignore_ascii_case("PUT")
|| method.eq_ignore_ascii_case("PATCH")
}
pub fn extract_token_from_headers<H: HeaderLookup>(
headers: &H,
config: &GarrisonConfig,
) -> Result<Option<String>, GarrisonError> {
if config.is_read_header {
if let Some(auth) = headers.get_header("authorization") {
if let Some(token) = strip_bearer_prefix(auth) {
return Ok(Some(token.to_string()));
}
}
if let Some(token) = headers.get_header(&config.token_name) {
return Ok(Some(token.to_string()));
}
}
if config.is_read_cookie {
if let Some(token) = parse_cookie_value(
headers.get_header("cookie").unwrap_or(""),
&crate::context::token_cookie_name(config),
) {
return Ok(Some(token));
}
}
Ok(None)
}
pub fn extract_token_from_request_parts(
config: &GarrisonConfig,
body_bytes: &[u8],
method: &str,
mut header_fn: impl FnMut(&str) -> GarrisonResult<Option<String>>,
mut cookie_fn: impl FnMut(&str) -> GarrisonResult<Option<String>>,
) -> GarrisonResult<Option<String>> {
if config.is_read_header {
if let Some(auth) = header_fn("Authorization")? {
if let Some(token) = strip_bearer_prefix(&auth) {
return Ok(Some(token.to_string()));
}
}
if let Some(token) = header_fn(&config.token_name)? {
return Ok(Some(token));
}
}
if config.is_read_cookie {
if let Some(token) = cookie_fn(&crate::context::token_cookie_name(config))? {
return Ok(Some(token));
}
}
if config.is_read_body && !body_bytes.is_empty() {
return extract_token_from_body(config, body_bytes, method, header_fn);
}
Ok(None)
}
fn extract_token_from_body(
config: &GarrisonConfig,
body_bytes: &[u8],
method: &str,
mut header_fn: impl FnMut(&str) -> GarrisonResult<Option<String>>,
) -> GarrisonResult<Option<String>> {
if !is_body_token_allowed_method(method) {
tracing::warn!(
method = method,
"C7: HTTP method does not allow extracting token from body, skipping body read"
);
return Ok(None);
}
const MAX_BODY_TOKEN_PARSE_BYTES: usize = 1024 * 1024;
if body_bytes.len() > MAX_BODY_TOKEN_PARSE_BYTES {
tracing::warn!(
size = body_bytes.len(),
limit = MAX_BODY_TOKEN_PARSE_BYTES,
"request body exceeds token-extraction parse limit, skipping body token read"
);
return Ok(None);
}
let content_type = header_fn("Content-Type")?.unwrap_or_default();
if content_type
.to_ascii_lowercase()
.contains("application/json")
{
if let Ok(value) = serde_json::from_slice::<serde_json::Value>(body_bytes) {
if let Some(token) = value.get(&config.token_name).and_then(|v| v.as_str()) {
return Ok(Some(token.to_string()));
}
}
}
Ok(None)
}
#[cfg(test)]
mod tests {
use super::*;
use http::header;
use http::HeaderValue;
#[test]
fn strip_bearer_prefix_standard() {
assert_eq!(strip_bearer_prefix("Bearer my_token"), Some("my_token"));
}
#[test]
fn strip_bearer_prefix_lowercase() {
assert_eq!(strip_bearer_prefix("bearer my_token"), Some("my_token"));
}
#[test]
fn strip_bearer_prefix_uppercase() {
assert_eq!(strip_bearer_prefix("BEARER my_token"), Some("my_token"));
}
#[test]
fn strip_bearer_prefix_mixed_case() {
assert_eq!(strip_bearer_prefix("BeArEr my_token"), Some("my_token"));
}
#[test]
fn strip_bearer_prefix_no_prefix() {
assert_eq!(strip_bearer_prefix("my_token"), None);
assert_eq!(strip_bearer_prefix("Basic abc123"), None);
}
#[test]
fn strip_bearer_prefix_empty() {
assert_eq!(strip_bearer_prefix(""), None);
}
#[test]
fn strip_bearer_prefix_shorter_than_prefix() {
assert_eq!(strip_bearer_prefix("Bear"), None);
assert_eq!(strip_bearer_prefix("bearer"), None);
}
#[test]
fn strip_bearer_prefix_multibyte_no_panic() {
let auth_str = "éééé"; assert_eq!(strip_bearer_prefix(auth_str), None);
}
#[test]
fn strip_bearer_prefix_only_prefix() {
assert_eq!(strip_bearer_prefix("Bearer "), None);
}
#[test]
fn parse_cookie_value_single() {
assert_eq!(
parse_cookie_value("token=abc123", "token"),
Some("abc123".to_string())
);
}
#[test]
fn parse_cookie_value_multiple() {
assert_eq!(
parse_cookie_value("session=xyz; token=target_tok; other=val", "token"),
Some("target_tok".to_string())
);
}
#[test]
fn parse_cookie_value_not_found() {
assert_eq!(parse_cookie_value("session=abc", "token"), None);
}
#[test]
fn parse_cookie_value_empty_header() {
assert_eq!(parse_cookie_value("", "token"), None);
}
#[test]
fn parse_cookie_value_empty_value_no_panic() {
assert_eq!(parse_cookie_value("name=", "name"), Some("".to_string()));
}
#[test]
fn extract_token_from_bearer_header() {
let mut headers = HeaderMap::new();
headers.insert(
header::AUTHORIZATION,
HeaderValue::from_static("Bearer my_token_123"),
);
let config = GarrisonConfig::default_config();
let token = extract_token_from_headers(&headers, &config).unwrap();
assert_eq!(token, Some("my_token_123".to_string()));
}
#[test]
fn extract_token_bearer_case_insensitive() {
let config = GarrisonConfig::default_config();
for prefix in &["Bearer", "bearer", "BEARER", "BeArEr"] {
let mut headers = HeaderMap::new();
headers.insert(
header::AUTHORIZATION,
HeaderValue::from_str(&format!("{} tok_{}", prefix, prefix)).unwrap(),
);
let token = extract_token_from_headers(&headers, &config).unwrap();
assert_eq!(
token,
Some(format!("tok_{}", prefix)),
"前缀 '{}' 应能提取 token",
prefix
);
}
}
#[test]
fn extract_token_from_custom_token_name_header() {
let mut headers = HeaderMap::new();
headers.insert(
"garrison_token",
HeaderValue::from_static("custom_header_tok"),
);
let config = GarrisonConfig::default_config();
let token = extract_token_from_headers(&headers, &config).unwrap();
assert_eq!(token, Some("custom_header_tok".to_string()));
}
#[test]
fn extract_token_from_cookie() {
let config = GarrisonConfig::default_config();
let cookie_value = format!(
"{}=cookie_tok_456",
crate::context::token_cookie_name(&config)
);
let mut headers = HeaderMap::new();
headers.insert(
header::COOKIE,
HeaderValue::from_str(&cookie_value).unwrap(),
);
let token = extract_token_from_headers(&headers, &config).unwrap();
assert_eq!(token, Some("cookie_tok_456".to_string()));
}
#[test]
fn extract_token_returns_none_when_missing() {
let headers = HeaderMap::new();
let config = GarrisonConfig::default_config();
let token = extract_token_from_headers(&headers, &config).unwrap();
assert_eq!(token, None);
}
#[test]
fn extract_token_bearer_priority_over_cookie() {
let config = GarrisonConfig::default_config();
let cookie_value = format!("{}=cookie_tok", crate::context::token_cookie_name(&config));
let mut headers = HeaderMap::new();
headers.insert(
header::AUTHORIZATION,
HeaderValue::from_static("Bearer header_tok"),
);
headers.insert(
header::COOKIE,
HeaderValue::from_str(&cookie_value).unwrap(),
);
let token = extract_token_from_headers(&headers, &config).unwrap();
assert_eq!(token, Some("header_tok".to_string()));
}
#[test]
fn extract_token_custom_header_priority_over_cookie() {
let config = GarrisonConfig::default_config();
let cookie_value = format!("{}=cookie_tok", crate::context::token_cookie_name(&config));
let mut headers = HeaderMap::new();
headers.insert(
"garrison_token",
HeaderValue::from_static("custom_header_tok"),
);
headers.insert(
header::COOKIE,
HeaderValue::from_str(&cookie_value).unwrap(),
);
let token = extract_token_from_headers(&headers, &config).unwrap();
assert_eq!(token, Some("custom_header_tok".to_string()));
}
#[test]
fn extract_token_skips_header_when_disabled() {
let config = GarrisonConfig::default_config();
let cookie_value = format!("{}=cookie_tok", crate::context::token_cookie_name(&config));
let mut headers = HeaderMap::new();
headers.insert(
header::AUTHORIZATION,
HeaderValue::from_static("Bearer header_tok"),
);
headers.insert(
header::COOKIE,
HeaderValue::from_str(&cookie_value).unwrap(),
);
let mut config = config;
config.is_read_header = false;
let token = extract_token_from_headers(&headers, &config).unwrap();
assert_eq!(token, Some("cookie_tok".to_string()));
}
#[test]
fn extract_token_skips_cookie_when_disabled() {
let mut headers = HeaderMap::new();
headers.insert(
header::AUTHORIZATION,
HeaderValue::from_static("Bearer header_tok"),
);
headers.insert(
header::COOKIE,
HeaderValue::from_static("garrison_token=cookie_tok"),
);
let mut config = GarrisonConfig::default_config();
config.is_read_cookie = false;
let token = extract_token_from_headers(&headers, &config).unwrap();
assert_eq!(token, Some("header_tok".to_string()));
}
#[test]
fn extract_token_returns_none_when_both_disabled() {
let mut headers = HeaderMap::new();
headers.insert(
header::AUTHORIZATION,
HeaderValue::from_static("Bearer header_tok"),
);
headers.insert(
header::COOKIE,
HeaderValue::from_static("garrison_token=cookie_tok"),
);
let mut config = GarrisonConfig::default_config();
config.is_read_header = false;
config.is_read_cookie = false;
let token = extract_token_from_headers(&headers, &config).unwrap();
assert_eq!(token, None);
}
#[test]
fn extract_token_from_cookie_with_multiple_pairs() {
let config = GarrisonConfig::default_config();
let cookie_value = format!(
"session=abc; {}=target_tok; other=val",
crate::context::token_cookie_name(&config)
);
let mut headers = HeaderMap::new();
headers.insert(
header::COOKIE,
HeaderValue::from_str(&cookie_value).unwrap(),
);
let token = extract_token_from_headers(&headers, &config).unwrap();
assert_eq!(token, Some("target_tok".to_string()));
}
#[test]
fn extract_token_falls_back_when_no_bearer_prefix() {
let config = GarrisonConfig::default_config();
let cookie_value = format!("{}=cookie_tok", crate::context::token_cookie_name(&config));
let mut headers = HeaderMap::new();
headers.insert(
header::AUTHORIZATION,
HeaderValue::from_static("Basic abc123"),
);
headers.insert(
header::COOKIE,
HeaderValue::from_str(&cookie_value).unwrap(),
);
let token = extract_token_from_headers(&headers, &config).unwrap();
assert_eq!(token, Some("cookie_tok".to_string()));
}
#[test]
fn c7_is_body_token_allowed_method_post() {
assert!(is_body_token_allowed_method("POST"));
}
#[test]
fn c7_is_body_token_allowed_method_put_patch() {
assert!(is_body_token_allowed_method("PUT"));
assert!(is_body_token_allowed_method("PATCH"));
}
#[test]
fn c7_is_body_token_allowed_method_rejects_others() {
assert!(!is_body_token_allowed_method("GET"));
assert!(!is_body_token_allowed_method("HEAD"));
assert!(!is_body_token_allowed_method("DELETE"));
assert!(!is_body_token_allowed_method("OPTIONS"));
assert!(!is_body_token_allowed_method("CONNECT"));
assert!(!is_body_token_allowed_method("TRACE"));
}
#[test]
fn c7_is_body_token_allowed_method_case_insensitive_and_edge() {
assert!(is_body_token_allowed_method("post"));
assert!(is_body_token_allowed_method("Put"));
assert!(is_body_token_allowed_method("pAtCh"));
assert!(is_body_token_allowed_method("PoSt"));
assert!(!is_body_token_allowed_method(""));
assert!(!is_body_token_allowed_method("unknown"));
assert!(!is_body_token_allowed_method("POST ")); assert!(!is_body_token_allowed_method(" POST")); }
#[test]
fn extract_from_body_content_type_case_insensitive() {
let config = GarrisonConfig::default_config();
let mut config = config;
config.is_read_header = false;
config.is_read_cookie = false;
config.is_read_body = true;
config.token_name = "token".to_string();
let body = br#"{"token":"case_tok"}"#;
for ct in &[
"application/json",
"Application/JSON",
"APPLICATION/JSON; charset=utf-8",
] {
let token = extract_token_from_request_parts(
&config,
body,
"POST",
|name| {
if name == "Content-Type" {
Ok(Some(ct.to_string()))
} else {
Ok(None)
}
},
|_| Ok(None),
)
.unwrap();
assert_eq!(
token,
Some("case_tok".to_string()),
"Content-Type '{ct}' 应大小写不敏感地命中 body 提取"
);
}
}
#[test]
fn extract_from_body_skips_oversized_body() {
let mut config = GarrisonConfig::default_config();
config.is_read_header = false;
config.is_read_cookie = false;
config.is_read_body = true;
config.token_name = "token".to_string();
let mut body = String::from(r#"{"pad":""#);
body.push_str(&"a".repeat(1024 * 1024 + 1));
body.push_str(r#"","token":"big_tok"}"#);
let token = extract_token_from_request_parts(
&config,
body.as_bytes(),
"POST",
|name| {
if name == "Content-Type" {
Ok(Some("application/json".to_string()))
} else {
Ok(None)
}
},
|_| Ok(None),
)
.unwrap();
assert_eq!(
token, None,
"超过 1MB 的 body 不应解析(防 DoS),应返回 None"
);
}
#[test]
fn extract_from_parts_empty_bearer_returns_none() {
let config = GarrisonConfig::default_config();
let token = extract_token_from_request_parts(
&config,
&[],
"GET",
|name| {
if name == "Authorization" {
Ok(Some("Bearer ".to_string()))
} else {
Ok(None)
}
},
|_| Ok(None),
)
.unwrap();
assert_eq!(token, None, "空前缀 Bearer 应返回 None 而非 Some(\"\")");
}
#[cfg(feature = "production")]
#[test]
fn extract_token_from_headers_hits_host_prefixed_cookie() {
let mut headers = HeaderMap::new();
headers.insert(
header::COOKIE,
HeaderValue::from_static("__Host-garrison_token=host_prefixed_tok"),
);
let config = GarrisonConfig::default_config();
let token = extract_token_from_headers(&headers, &config).unwrap();
assert_eq!(token, Some("host_prefixed_tok".to_string()));
}
#[cfg(feature = "production")]
#[test]
fn extract_from_parts_queries_host_prefixed_cookie_name() {
let mut config = GarrisonConfig::default_config();
config.is_read_header = false;
config.is_read_cookie = true;
let token = extract_token_from_request_parts(
&config,
&[],
"GET",
|_| Ok(None),
|name| {
assert_eq!(
name, "__Host-garrison_token",
"cookie 查询名应与 production 写侧前缀名一致"
);
Ok(Some("parts_tok".to_string()))
},
)
.unwrap();
assert_eq!(token, Some("parts_tok".to_string()));
}
}