use std::sync::Once;
use crate::config::GarrisonConfig;
use crate::context::validate_cookie_name_value;
use crate::error::{GarrisonError, GarrisonResult};
static NONE_DOWNGRADE_WARN: Once = Once::new();
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CookieScope {
LaxHttpOnly,
StrictHttpOnly,
NoneHttpOnly,
}
impl CookieScope {
pub fn from_same_site(same_site: &str) -> GarrisonResult<Self> {
match same_site {
"Lax" => Ok(Self::LaxHttpOnly),
"Strict" => Ok(Self::StrictHttpOnly),
"None" => Ok(Self::NoneHttpOnly),
other => Err(GarrisonError::Context(format!(
"ctx-invalid-cookie-same-site::{other}"
))),
}
}
fn same_site_attr(&self, secure: bool) -> &'static str {
match self {
Self::LaxHttpOnly => "Lax",
Self::StrictHttpOnly => "Strict",
Self::NoneHttpOnly if secure => "None",
Self::NoneHttpOnly => {
NONE_DOWNGRADE_WARN.call_once(|| {
tracing::warn!(
"{}",
crate::i18n::translate_detail(
"logs-cookie-same-site-none-without-secure",
&[]
)
);
});
"Lax"
},
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CookiePath {
Root,
Of(String),
}
impl CookiePath {
pub fn as_str(&self) -> &str {
match self {
Self::Root => "/",
Self::Of(p) => p,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CookieType {
pub name: String,
pub scope: CookieScope,
pub path: CookiePath,
pub domain: Option<String>,
pub max_age: Option<i64>,
}
impl CookieType {
pub fn token(config: &GarrisonConfig) -> GarrisonResult<Self> {
Self::session(config.token_name.clone(), config)
}
pub fn session(name: impl Into<String>, config: &GarrisonConfig) -> GarrisonResult<Self> {
Ok(Self {
name: name.into(),
scope: CookieScope::from_same_site(&config.cookie_same_site)?,
path: CookiePath::Root,
domain: None,
max_age: None,
})
}
pub fn resolved_name(&self, secure: bool) -> String {
resolve_cookie_name(&self.name, secure, &self.path, self.domain.as_deref())
}
}
fn resolve_cookie_name(
name: &str,
secure: bool,
path: &CookiePath,
domain: Option<&str>,
) -> String {
#[cfg(feature = "production")]
{
if secure {
if matches!(path, CookiePath::Root) && domain.is_none() {
return format!("__Host-{}", name);
}
return format!("__Secure-{}", name);
}
}
#[cfg(not(feature = "production"))]
{
let _ = (secure, path, domain);
}
name.to_string()
}
pub fn token_cookie_name(config: &GarrisonConfig) -> String {
resolve_cookie_name(
&config.token_name,
config.cookie_secure,
&CookiePath::Root,
None,
)
}
fn validate_cookie_domain(domain: &str, cookie_name: &str) -> GarrisonResult<()> {
let domain_ok = !domain.is_empty()
&& domain
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'.');
if !domain_ok {
return Err(GarrisonError::Context(format!(
"ctx-invalid-cookie-domain::{cookie_name}"
)));
}
Ok(())
}
fn validate_cookie_path(path: &str, cookie_name: &str) -> GarrisonResult<()> {
let path_ok = path.bytes().all(|b| b != b';' && (0x20..0x7f).contains(&b));
if !path_ok {
return Err(GarrisonError::Context(format!(
"ctx-invalid-cookie-path::{cookie_name}"
)));
}
Ok(())
}
pub fn build_set_cookie_value(
cookie: &CookieType,
value: &str,
secure: bool,
) -> GarrisonResult<String> {
validate_cookie_name_value(&cookie.name, value)?;
let path = cookie.path.as_str();
if path.is_empty() {
return Err(GarrisonError::Context(format!(
"ctx-invalid-cookie-path::{}",
cookie.name
)));
}
validate_cookie_path(path, &cookie.name)?;
let domain = cookie.domain.as_deref().filter(|d| !d.is_empty());
if let Some(d) = domain {
validate_cookie_domain(d, &cookie.name)?;
}
if cookie.max_age.is_some_and(|max_age| max_age < 0) {
return Err(GarrisonError::Context(format!(
"ctx-invalid-cookie-max-age::{}",
cookie.name
)));
}
let name = resolve_cookie_name(&cookie.name, secure, &cookie.path, domain);
let mut out = format!("{}={}; HttpOnly", name, value);
if secure {
out.push_str("; Secure");
}
out.push_str("; SameSite=");
out.push_str(cookie.scope.same_site_attr(secure));
out.push_str("; Path=");
out.push_str(path);
if let Some(d) = domain {
out.push_str("; Domain=");
out.push_str(d);
}
if let Some(max_age) = cookie.max_age {
out.push_str("; Max-Age=");
out.push_str(&max_age.to_string());
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
fn cookie_type(scope: CookieScope) -> CookieType {
CookieType {
name: "garrison_token".to_string(),
scope,
path: CookiePath::Root,
domain: None,
max_age: None,
}
}
#[test]
fn none_scope_insecure_downgrades_to_lax() {
let value =
build_set_cookie_value(&cookie_type(CookieScope::NoneHttpOnly), "tok", false).unwrap();
assert!(
value.contains("SameSite=Lax"),
"应降级为 Lax,实际: {}",
value
);
assert!(
!value.contains("SameSite=None"),
"非 Secure 上下文不得输出 SameSite=None,实际: {}",
value
);
assert!(
!value.contains("Secure"),
"非 Secure 上下文不得输出 Secure,实际: {}",
value
);
assert!(value.contains("HttpOnly"));
}
#[test]
fn none_scope_secure_emits_none_with_secure() {
let value =
build_set_cookie_value(&cookie_type(CookieScope::NoneHttpOnly), "tok", true).unwrap();
assert!(value.contains("SameSite=None"));
assert!(value.contains("Secure"));
}
#[test]
fn all_scopes_emit_httponly() {
for scope in [
CookieScope::LaxHttpOnly,
CookieScope::StrictHttpOnly,
CookieScope::NoneHttpOnly,
] {
let value = build_set_cookie_value(&cookie_type(scope.clone()), "tok", true).unwrap();
assert!(
value.contains("HttpOnly"),
"scope {:?} 应输出 HttpOnly,实际: {}",
scope,
value
);
}
}
#[cfg(feature = "production")]
mod production_prefix {
use super::*;
#[test]
fn host_prefix_when_secure_root_no_domain() {
let value = build_set_cookie_value(&cookie_type(CookieScope::LaxHttpOnly), "tok", true)
.unwrap();
assert!(
value.starts_with("__Host-garrison_token="),
"实际: {}",
value
);
}
#[test]
fn secure_prefix_when_path_scoped() {
let cookie = CookieType {
path: CookiePath::Of("/api/device-login/exchange".to_string()),
..cookie_type(CookieScope::LaxHttpOnly)
};
let value = build_set_cookie_value(&cookie, "tok", true).unwrap();
assert!(
value.starts_with("__Secure-garrison_token="),
"实际: {}",
value
);
}
#[test]
fn secure_prefix_when_domain_present() {
let cookie = CookieType {
domain: Some("example.com".to_string()),
..cookie_type(CookieScope::LaxHttpOnly)
};
let value = build_set_cookie_value(&cookie, "tok", true).unwrap();
assert!(
value.starts_with("__Secure-garrison_token="),
"实际: {}",
value
);
}
#[test]
fn no_prefix_when_insecure() {
for (path, domain) in [
(CookiePath::Root, None),
(
CookiePath::Of("/api/x".to_string()),
Some("example.com".to_string()),
),
] {
let cookie = CookieType {
path,
domain,
..cookie_type(CookieScope::LaxHttpOnly)
};
let value = build_set_cookie_value(&cookie, "tok", false).unwrap();
assert!(
value.starts_with("garrison_token="),
"http 降级无前缀,实际: {}",
value
);
}
}
#[test]
fn host_prefix_invariants() {
for scope in [
CookieScope::LaxHttpOnly,
CookieScope::StrictHttpOnly,
CookieScope::NoneHttpOnly,
] {
let value = build_set_cookie_value(&cookie_type(scope), "tok", true).unwrap();
assert!(
value.contains("__Host-"),
"Secure 上下文 + Root + 无 Domain 应带 __Host- 前缀,实际: {}",
value
);
assert!(value.contains("Path=/"), "实际: {}", value);
assert!(value.contains("Secure"), "实际: {}", value);
assert!(!value.contains("Domain="), "实际: {}", value);
}
}
#[test]
fn token_cookie_name_matches_written_name() {
let config = GarrisonConfig::default_config();
let cookie = CookieType::token(&config).unwrap();
let value = build_set_cookie_value(&cookie, "tok", config.cookie_secure).unwrap();
assert!(
value.starts_with(&format!("{}=", token_cookie_name(&config))),
"写读名字应一致,实际: {}",
value
);
}
}
#[cfg(not(feature = "production"))]
mod non_production_regression {
use super::*;
#[test]
fn no_prefix_in_any_combination() {
for (secure, path, domain) in [
(true, CookiePath::Root, None),
(true, CookiePath::Of("/api/x".to_string()), None),
(true, CookiePath::Root, Some("example.com".to_string())),
(false, CookiePath::Root, None),
] {
let cookie = CookieType {
path,
domain,
..cookie_type(CookieScope::LaxHttpOnly)
};
let value = build_set_cookie_value(&cookie, "tok", secure).unwrap();
assert!(
value.starts_with("garrison_token="),
"非 production 构建不应有前缀,实际: {}",
value
);
assert!(!value.contains("__Host-"));
assert!(!value.contains("__Secure-"));
}
}
#[test]
fn token_cookie_name_matches_written_name() {
let config = GarrisonConfig::default_config();
let cookie = CookieType::token(&config).unwrap();
let value = build_set_cookie_value(&cookie, "tok", config.cookie_secure).unwrap();
assert!(
value.starts_with(&format!("{}=", token_cookie_name(&config))),
"写读名字应一致,实际: {}",
value
);
}
}
#[test]
fn token_constructor_rejects_invalid_same_site() {
for same_site in ["lax", "", "None ", "none", "LAX", "Strict;"] {
let mut config = GarrisonConfig::default_config();
config.cookie_same_site = same_site.to_string();
let result =
CookieType::token(&config).and_then(|c| build_set_cookie_value(&c, "tok", true));
assert!(
matches!(result, Err(GarrisonError::Context(_))),
"same_site={:?} 应 fail-fast,实际: {:?}",
same_site,
result.map(|_| ())
);
}
}
#[test]
fn same_site_whitelist_matches_scope_variants() {
for value in crate::config::COOKIE_SAME_SITE_VALUES {
let scope = CookieScope::from_same_site(value)
.unwrap_or_else(|e| panic!("白名单值 {:?} 应被 from_same_site 接受: {}", value, e));
assert_eq!(
scope.same_site_attr(true),
*value,
"白名单值 {:?} 应与作用域属性输出一一对应(不得落兜底)",
value
);
}
}
#[test]
fn token_constructor_accepts_valid_same_site() {
for (same_site, attr) in [
("Lax", "SameSite=Lax"),
("Strict", "SameSite=Strict"),
("None", "SameSite=None"),
] {
let mut config = GarrisonConfig::default_config();
config.cookie_same_site = same_site.to_string();
let cookie = CookieType::token(&config).unwrap();
let value = build_set_cookie_value(&cookie, "tok", true).unwrap();
assert!(
value.contains(attr),
"same_site={} 应输出 {},实际: {}",
same_site,
attr,
value
);
}
}
#[test]
fn rejects_injected_value() {
for bad in [
"abc; Domain=evil.com",
"bad\nvalue",
"a b",
"a,b",
"a\\b",
"a\"b",
] {
let result = build_set_cookie_value(&cookie_type(CookieScope::LaxHttpOnly), bad, true);
assert!(
matches!(result, Err(GarrisonError::Context(_))),
"value={:?} 应被拒绝,实际: {:?}",
bad,
result.map(|_| ())
);
}
}
#[test]
fn rejects_injected_domain() {
for bad in [
"evil.com; SameSite=None",
"evil.com Domain=x",
"bad\nexample.com",
"evil\u{7f}.com",
"例子.com",
] {
let cookie = CookieType {
domain: Some(bad.to_string()),
..cookie_type(CookieScope::LaxHttpOnly)
};
let result = build_set_cookie_value(&cookie, "tok", true);
assert!(
matches!(result, Err(GarrisonError::Context(_))),
"domain={:?} 应被拒绝,实际: {:?}",
bad,
result.map(|_| ())
);
}
}
#[test]
fn rejects_injected_path() {
for bad in ["/a;b", "/a\nb", "/api\u{7f}x"] {
let cookie = CookieType {
path: CookiePath::Of(bad.to_string()),
..cookie_type(CookieScope::LaxHttpOnly)
};
let result = build_set_cookie_value(&cookie, "tok", true);
assert!(
matches!(result, Err(GarrisonError::Context(_))),
"path={:?} 应被拒绝,实际: {:?}",
bad,
result.map(|_| ())
);
}
}
#[test]
fn accepts_valid_domain() {
for domain in ["example.com", "api.example.com", "sub-domain.example.com"] {
let cookie = CookieType {
domain: Some(domain.to_string()),
..cookie_type(CookieScope::LaxHttpOnly)
};
let value = build_set_cookie_value(&cookie, "tok", true).unwrap();
assert!(
value.contains(&format!("Domain={}", domain)),
"domain={} 应放行,实际: {}",
domain,
value
);
}
}
#[test]
fn max_age_emitted_only_when_present() {
let with = CookieType {
max_age: Some(600),
..cookie_type(CookieScope::LaxHttpOnly)
};
let value = build_set_cookie_value(&with, "tok", true).unwrap();
assert!(value.contains("Max-Age=600"), "实际: {}", value);
let without = cookie_type(CookieScope::LaxHttpOnly);
let value = build_set_cookie_value(&without, "tok", true).unwrap();
assert!(!value.contains("Max-Age"), "实际: {}", value);
}
#[test]
fn rejects_negative_max_age_allows_zero() {
let negative = CookieType {
max_age: Some(-1),
..cookie_type(CookieScope::LaxHttpOnly)
};
let result = build_set_cookie_value(&negative, "tok", true);
assert!(
matches!(result, Err(GarrisonError::Context(_))),
"max_age=-1 应被拒绝,实际: {:?}",
result.map(|_| ())
);
let zero = CookieType {
max_age: Some(0),
..cookie_type(CookieScope::LaxHttpOnly)
};
let value = build_set_cookie_value(&zero, "tok", true).unwrap();
assert!(value.contains("Max-Age=0"), "实际: {}", value);
}
#[test]
fn path_scope_emitted() {
let scoped = CookieType {
path: CookiePath::Of("/api/device-login/exchange".to_string()),
..cookie_type(CookieScope::LaxHttpOnly)
};
let value = build_set_cookie_value(&scoped, "tok", true).unwrap();
assert!(
value.contains("Path=/api/device-login/exchange"),
"实际: {}",
value
);
let root = cookie_type(CookieScope::LaxHttpOnly);
let value = build_set_cookie_value(&root, "tok", true).unwrap();
assert!(value.contains("Path=/"), "实际: {}", value);
let empty = CookieType {
path: CookiePath::Of(String::new()),
..cookie_type(CookieScope::LaxHttpOnly)
};
assert!(build_set_cookie_value(&empty, "tok", true).is_err());
}
#[test]
fn domain_emitted_only_when_present() {
let with = CookieType {
domain: Some("example.com".to_string()),
..cookie_type(CookieScope::LaxHttpOnly)
};
let value = build_set_cookie_value(&with, "tok", true).unwrap();
assert!(value.contains("Domain=example.com"), "实际: {}", value);
let empty = CookieType {
domain: Some(String::new()),
..cookie_type(CookieScope::LaxHttpOnly)
};
let value = build_set_cookie_value(&empty, "tok", true).unwrap();
assert!(!value.contains("Domain="), "实际: {}", value);
}
}