yang_base/action/auth/
browser_session.rs1use crate::action::{ApiResponse, Request};
11use schemars::JsonSchema;
12use serde::Serialize;
13use yang_base::BaseError;
14
15#[derive(Debug, Serialize, JsonSchema)]
17pub struct BrowserAccessToken {
18 pub access_token: String,
20}
21
22#[derive(Debug, Serialize, JsonSchema)]
24pub struct ReloginRequired {
25 pub relogin_required: bool,
27}
28
29#[derive(Debug, Clone)]
31pub struct BrowserSession {
32 cookie_name: String,
33 cookie_path: String,
34}
35
36impl BrowserSession {
37 pub fn new(cookie_name: impl Into<String>, cookie_path: impl Into<String>) -> Self {
39 Self {
40 cookie_name: cookie_name.into(),
41 cookie_path: cookie_path.into(),
42 }
43 }
44
45 pub fn refresh_token(&self, request: &Request) -> Result<String, BaseError> {
47 request
48 .cookie()
49 .and_then(|header| {
50 header.split(';').find_map(|part| {
51 let (name, value) = part.trim().split_once('=')?;
52 (name == self.cookie_name && !value.is_empty()).then(|| value.to_string())
53 })
54 })
55 .ok_or_else(|| BaseError::Unauthorized("刷新会话 Cookie 缺失".to_string()))
56 }
57
58 pub fn validate_same_origin(request: &Request) -> Result<bool, BaseError> {
63 if request
64 .get_header("sec-fetch-site")
65 .is_some_and(|value| !matches!(value, "same-origin" | "none"))
66 {
67 return Err(BaseError::PermissionDenied(
68 "浏览器会话请求必须来自同源页面".to_string(),
69 ));
70 }
71
72 let source = request
73 .get_header("origin")
74 .or_else(|| request.get_header("referer"));
75 let Some(source) = source else {
76 return Ok(false);
77 };
78 let host = request
79 .get_header("host")
80 .ok_or_else(|| BaseError::PermissionDenied("同源校验缺少 Host".to_string()))?;
81 let uri = source
82 .parse::<http_uri::Uri>()
83 .map_err(|_| BaseError::PermissionDenied("Origin/Referer 非法".to_string()))?;
84 let source_host = uri
85 .authority()
86 .map(|authority| authority.as_str())
87 .ok_or_else(|| BaseError::PermissionDenied("Origin/Referer 缺少主机".to_string()))?;
88 if !source_host.eq_ignore_ascii_case(host.trim()) {
89 return Err(BaseError::PermissionDenied(
90 "浏览器会话请求必须来自同源页面".to_string(),
91 ));
92 }
93 Ok(uri.scheme_str() == Some("https"))
94 }
95
96 pub fn token_response(
98 &self,
99 access_token: String,
100 refresh_token: String,
101 secure: bool,
102 ) -> Result<ApiResponse, BaseError> {
103 no_store(
104 ApiResponse::success(BrowserAccessToken { access_token }, "会话已建立")?
105 .with_header("set-cookie", self.refresh_cookie(&refresh_token, secure))?,
106 )
107 }
108
109 pub fn clear_response(
111 &self,
112 response: ApiResponse,
113 secure: bool,
114 ) -> Result<ApiResponse, BaseError> {
115 no_store(response.with_header("set-cookie", self.clear_refresh_cookie(secure))?)
116 }
117
118 pub fn relogin_response(&self, message: &str, secure: bool) -> Result<ApiResponse, BaseError> {
120 self.clear_response(
121 ApiResponse::success(
122 ReloginRequired {
123 relogin_required: true,
124 },
125 message,
126 )?,
127 secure,
128 )
129 }
130
131 fn refresh_cookie(&self, token: &str, secure: bool) -> String {
132 format!(
133 "{}={token}; Path={}; HttpOnly; SameSite=Strict{}",
134 self.cookie_name,
135 self.cookie_path,
136 if secure { "; Secure" } else { "" }
137 )
138 }
139
140 fn clear_refresh_cookie(&self, secure: bool) -> String {
141 format!(
142 "{}=; Path={}; HttpOnly; SameSite=Strict; Max-Age=0{}",
143 self.cookie_name,
144 self.cookie_path,
145 if secure { "; Secure" } else { "" }
146 )
147 }
148}
149
150fn no_store(response: ApiResponse) -> Result<ApiResponse, BaseError> {
151 response
152 .with_header("cache-control", "no-store")?
153 .with_header("pragma", "no-cache")
154}
155
156#[cfg(test)]
157mod tests {
158 use super::*;
159 use std::collections::HashMap;
160
161 fn session() -> BrowserSession {
162 BrowserSession::new("yang_refresh", "/api/v1/users")
163 }
164
165 #[test]
166 fn refresh_cookie_is_http_only_strict_and_host_only() {
167 let cookie = session().refresh_cookie("secret", true);
168 assert!(cookie.contains("HttpOnly"));
169 assert!(cookie.contains("SameSite=Strict"));
170 assert!(cookie.contains("Secure"));
171 assert!(cookie.contains("Path=/api/v1/users"));
172 assert!(!cookie.contains("Domain="));
173 }
174
175 #[test]
176 fn browser_posts_require_exact_origin() {
177 let mut headers = HashMap::new();
178 headers.insert("host".to_string(), "app.example.com".to_string());
179 headers.insert("origin".to_string(), "https://app.example.com".to_string());
180 headers.insert("sec-fetch-site".to_string(), "same-origin".to_string());
181 assert!(BrowserSession::validate_same_origin(
182 &Request::new(serde_json::json!({})).headers(headers.clone())
183 )
184 .unwrap_or(false));
185 headers.insert("origin".to_string(), "https://evil.example.com".to_string());
186 assert!(BrowserSession::validate_same_origin(
187 &Request::new(serde_json::json!({})).headers(headers)
188 )
189 .is_err());
190 }
191}