| 1 | //! 认证:argon2 密码哈希 + JWT(HttpOnly Cookie,同时接受 Bearer)。 |
| 2 | //! Cookie 本身是会话 cookie,过期由 JWT 的 exp 控制(7 天)。 |
| 3 | |
| 4 | use argon2::password_hash::rand_core::OsRng; |
| 5 | use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString}; |
| 6 | use argon2::Argon2; |
| 7 | use axum::extract::FromRequestParts; |
| 8 | use axum::http::request::Parts; |
| 9 | use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite}; |
| 10 | use chrono::Utc; |
| 11 | use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation}; |
| 12 | use serde::{Deserialize, Serialize}; |
| 13 | use utopia_core::models::User; |
| 14 | use utopia_core::AppError; |
| 15 | use uuid::Uuid; |
| 16 | |
| 17 | use crate::error::ApiErr; |
| 18 | use crate::state::AppState; |
| 19 | |
| 20 | pub const COOKIE_NAME: &str = "utopia_token"; |
| 21 | const TOKEN_TTL_DAYS: i64 = 7; |
| 22 | |
| 23 | #[derive(Debug, Serialize, Deserialize)] |
| 24 | struct Claims { |
| 25 | sub: Uuid, |
| 26 | exp: i64, |
| 27 | } |
| 28 | |
| 29 | pub fn hash_password(password: &str) -> Result<String, AppError> { |
| 30 | let salt = SaltString::generate(&mut OsRng); |
| 31 | Argon2::default() |
| 32 | .hash_password(password.as_bytes(), &salt) |
| 33 | .map(|h| h.to_string()) |
| 34 | .map_err(|e| AppError::Other(anyhow::anyhow!("Password hashing failed: {e}"))) |
| 35 | } |
| 36 | |
| 37 | pub fn verify_password(password: &str, hash: &str) -> bool { |
| 38 | PasswordHash::new(hash) |
| 39 | .map(|parsed| { |
| 40 | Argon2::default() |
| 41 | .verify_password(password.as_bytes(), &parsed) |
| 42 | .is_ok() |
| 43 | }) |
| 44 | .unwrap_or(false) |
| 45 | } |
| 46 | |
| 47 | pub fn issue_token(state: &AppState, user_id: Uuid) -> Result<String, AppError> { |
| 48 | let claims = Claims { |
| 49 | sub: user_id, |
| 50 | exp: (Utc::now() + chrono::Duration::days(TOKEN_TTL_DAYS)).timestamp(), |
| 51 | }; |
| 52 | encode( |
| 53 | &Header::default(), |
| 54 | &claims, |
| 55 | &EncodingKey::from_secret(state.jwt_secret.as_bytes()), |
| 56 | ) |
| 57 | .map_err(|e| AppError::Other(anyhow::anyhow!("Token issuance failed: {e}"))) |
| 58 | } |
| 59 | |
| 60 | /// 外层是否在跑 TLS。反代都会带 `X-Forwarded-Proto`;没有这个头(本地直连、 |
| 61 | /// 开发环境)就当明文,Secure 不打,登录照常工作。 |
| 62 | /// |
| 63 | /// 不需要「信任的代理」名单:伪造这个头只会让攻击者自己的 cookie 变成 Secure, |
| 64 | /// 更严格而不是更宽松,没有攻击价值。`UTOPIA_COOKIE_SECURE=true` 可强制打开, |
| 65 | /// 给那些不发这个头的代理兜底。 |
| 66 | pub fn behind_tls(headers: &axum::http::HeaderMap, forced: bool) -> bool { |
| 67 | forced |
| 68 | || headers |
| 69 | .get("x-forwarded-proto") |
| 70 | .and_then(|v| v.to_str().ok()) |
| 71 | // 经过多层代理时这个头是逗号分隔的链,最左边是最初那一跳 |
| 72 | .and_then(|v| v.split(',').next()) |
| 73 | .is_some_and(|p| p.trim().eq_ignore_ascii_case("https")) |
| 74 | } |
| 75 | |
| 76 | /// 会话 cookie。`secure` 由 [`behind_tls`] 判定——HTTPS 下打上 Secure, |
| 77 | /// 浏览器就不会再把它经明文链路发出去。 |
| 78 | pub fn auth_cookie(token: String, secure: bool) -> Cookie<'static> { |
| 79 | Cookie::build((COOKIE_NAME, token)) |
| 80 | .path("/") |
| 81 | .http_only(true) |
| 82 | .secure(secure) |
| 83 | .same_site(SameSite::Lax) |
| 84 | .build() |
| 85 | } |
| 86 | |
| 87 | /// 注销用的删除指令。**属性必须和签发时一致**:浏览器按 name + domain + path |
| 88 | /// 匹配才认得出要删哪一条,只给名字的话 path 会退化成当前请求路径 |
| 89 | /// (`/api/v1/auth`),和签发时的 `/` 对不上——cookie 留在浏览器里,人以为 |
| 90 | /// 自己登出了。 |
| 91 | pub fn clear_auth_cookie(secure: bool) -> Cookie<'static> { |
| 92 | Cookie::build((COOKIE_NAME, "")) |
| 93 | .path("/") |
| 94 | .http_only(true) |
| 95 | .secure(secure) |
| 96 | .same_site(SameSite::Lax) |
| 97 | .build() |
| 98 | } |
| 99 | |
| 100 | pub(crate) fn decode_user_id(state: &AppState, token: &str) -> Result<Uuid, AppError> { |
| 101 | let data = decode::<Claims>( |
| 102 | token, |
| 103 | &DecodingKey::from_secret(state.jwt_secret.as_bytes()), |
| 104 | &Validation::default(), |
| 105 | ) |
| 106 | .map_err(|_| AppError::Unauthorized)?; |
| 107 | Ok(data.claims.sub) |
| 108 | } |
| 109 | |
| 110 | /// 已登录用户提取器:Cookie `utopia_token` 或 `Authorization: Bearer`。 |
| 111 | pub struct AuthUser(pub User); |
| 112 | |
| 113 | impl FromRequestParts<AppState> for AuthUser { |
| 114 | type Rejection = ApiErr; |
| 115 | |
| 116 | async fn from_request_parts( |
| 117 | parts: &mut Parts, |
| 118 | state: &AppState, |
| 119 | ) -> Result<Self, Self::Rejection> { |
| 120 | let jar = CookieJar::from_headers(&parts.headers); |
| 121 | let token = jar |
| 122 | .get(COOKIE_NAME) |
| 123 | .map(|c| c.value().to_string()) |
| 124 | .or_else(|| { |
| 125 | parts |
| 126 | .headers |
| 127 | .get(axum::http::header::AUTHORIZATION) |
| 128 | .and_then(|v| v.to_str().ok()) |
| 129 | .and_then(|v| v.strip_prefix("Bearer ")) |
| 130 | .map(|v| v.to_string()) |
| 131 | }) |
| 132 | .ok_or(AppError::Unauthorized)?; |
| 133 | |
| 134 | let user_id = decode_user_id(state, &token)?; |
| 135 | let user = utopia_store::accounts::find_user_by_id(&state.pool, user_id) |
| 136 | .await? |
| 137 | .ok_or(AppError::Unauthorized)?; |
| 138 | Ok(AuthUser(user)) |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | /// 生成一条 JWT 签名密钥:32 字节 CSPRNG,hex 编码成 64 个字符。 |
| 143 | /// |
| 144 | /// 长度取 32 字节是因为 HS256 的 HMAC 块就是 32 字节——再长会被先哈希一遍, |
| 145 | /// 并不增加强度。hex 而非 base64:这个值会出现在日志、环境变量和运维的复制粘贴里, |
| 146 | /// 不带 +/= 省去一整类转义问题。 |
| 147 | pub fn generate_jwt_secret() -> String { |
| 148 | use argon2::password_hash::rand_core::RngCore; |
| 149 | let mut buf = [0u8; 32]; |
| 150 | OsRng.fill_bytes(&mut buf); |
| 151 | buf.iter().map(|b| format!("{b:02x}")).collect() |
| 152 | } |
| 153 | |
| 154 | #[cfg(test)] |
| 155 | mod tests { |
| 156 | use super::*; |
| 157 | |
| 158 | fn claims_in(days: i64) -> Claims { |
| 159 | Claims { |
| 160 | sub: Uuid::now_v7(), |
| 161 | exp: (Utc::now() + chrono::Duration::days(days)).timestamp(), |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | /// JWT 校验的护栏:默认配置必须认自家签发的 HS256,且拒绝换密钥与过期。 |
| 166 | /// 加于 jsonwebtoken 9 → 10 升级时(CVE-2026-25537:<10.3.0 的类型混淆可绕过授权)—— |
| 167 | /// 库的默认校验语义是编译器看不见的那部分,回归靠这里兜。 |
| 168 | #[test] |
| 169 | fn default_validation_accepts_own_token_and_rejects_the_rest() { |
| 170 | let secret = b"test-secret-not-a-real-key"; |
| 171 | let claims = claims_in(7); |
| 172 | let token = encode( |
| 173 | &Header::default(), |
| 174 | &claims, |
| 175 | &EncodingKey::from_secret(secret), |
| 176 | ) |
| 177 | .expect("issuing must succeed"); |
| 178 | |
| 179 | let decoded = decode::<Claims>( |
| 180 | &token, |
| 181 | &DecodingKey::from_secret(secret), |
| 182 | &Validation::default(), |
| 183 | ) |
| 184 | .expect("own token must verify under default validation"); |
| 185 | assert_eq!(decoded.claims.sub, claims.sub, "sub must survive the trip"); |
| 186 | |
| 187 | assert!( |
| 188 | decode::<Claims>( |
| 189 | &token, |
| 190 | &DecodingKey::from_secret(b"a-different-secret"), |
| 191 | &Validation::default(), |
| 192 | ) |
| 193 | .is_err(), |
| 194 | "a token signed with another key must not verify" |
| 195 | ); |
| 196 | |
| 197 | let expired = encode( |
| 198 | &Header::default(), |
| 199 | &claims_in(-1), |
| 200 | &EncodingKey::from_secret(secret), |
| 201 | ) |
| 202 | .expect("issuing must succeed"); |
| 203 | assert!( |
| 204 | decode::<Claims>( |
| 205 | &expired, |
| 206 | &DecodingKey::from_secret(secret), |
| 207 | &Validation::default(), |
| 208 | ) |
| 209 | .is_err(), |
| 210 | "exp must be enforced by default" |
| 211 | ); |
| 212 | } |
| 213 | |
| 214 | fn headers_with(proto: Option<&str>) -> axum::http::HeaderMap { |
| 215 | let mut h = axum::http::HeaderMap::new(); |
| 216 | if let Some(p) = proto { |
| 217 | h.insert("x-forwarded-proto", p.parse().unwrap()); |
| 218 | } |
| 219 | h |
| 220 | } |
| 221 | |
| 222 | /// Secure 的判定必须只在确认走了 TLS 时为真:判错成 true,明文部署的用户 |
| 223 | /// 登录后浏览器直接丢掉 cookie,症状是「点了登录又回到登录页」,且不报错。 |
| 224 | #[test] |
| 225 | fn secure_only_when_tls_is_actually_in_front() { |
| 226 | // 没有代理:本地直连、cargo run —— 不能打 Secure,否则 HTTP 下登不上 |
| 227 | assert!(!behind_tls(&headers_with(None), false)); |
| 228 | assert!(!behind_tls(&headers_with(Some("http")), false)); |
| 229 | |
| 230 | assert!(behind_tls(&headers_with(Some("https")), false)); |
| 231 | // 头的大小写由代理决定,不能假设 |
| 232 | assert!(behind_tls(&headers_with(Some("HTTPS")), false)); |
| 233 | |
| 234 | // 多层代理时这个头是逗号分隔的链,最左边是最初那一跳—— |
| 235 | // 取错一端会把「用户走 HTTPS 到边缘、边缘走 HTTP 回源」判成明文 |
| 236 | assert!(behind_tls(&headers_with(Some("https, http")), false)); |
| 237 | assert!(!behind_tls(&headers_with(Some("http, https")), false)); |
| 238 | |
| 239 | // 配置强制打开:给不发这个头的代理兜底 |
| 240 | assert!(behind_tls(&headers_with(None), true)); |
| 241 | } |
| 242 | } |