feat: add password entry auth flow

This commit is contained in:
2026-04-21 14:50:42 +08:00
parent 5675c40119
commit c23088539e
18 changed files with 1146 additions and 25 deletions

60
server-rs/Cargo.lock generated
View File

@@ -24,6 +24,7 @@ dependencies = [
"axum",
"dotenvy",
"http-body-util",
"module-auth",
"platform-auth",
"platform-oss",
"serde",
@@ -37,6 +38,18 @@ dependencies = [
"uuid",
]
[[package]]
name = "argon2"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"
dependencies = [
"base64ct",
"blake2",
"cpufeatures",
"password-hash",
]
[[package]]
name = "atomic-waker"
version = "1.1.2"
@@ -107,12 +120,27 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64ct"
version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "bitflags"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"
[[package]]
name = "blake2"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
dependencies = [
"digest",
]
[[package]]
name = "block-buffer"
version = "0.10.4"
@@ -512,6 +540,14 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "module-auth"
version = "0.1.0"
dependencies = [
"platform-auth",
"tokio",
]
[[package]]
name = "nu-ansi-term"
version = "0.50.3"
@@ -561,6 +597,17 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "password-hash"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"
dependencies = [
"base64ct",
"rand_core",
"subtle",
]
[[package]]
name = "pem"
version = "3.0.6"
@@ -587,10 +634,14 @@ checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
name = "platform-auth"
version = "0.1.0"
dependencies = [
"argon2",
"jsonwebtoken",
"rand_core",
"serde",
"time",
"tokio",
"urlencoding",
"uuid",
]
[[package]]
@@ -645,6 +696,15 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom 0.2.17",
]
[[package]]
name = "regex-automata"
version = "0.4.14"

View File

@@ -5,6 +5,7 @@
resolver = "2"
members = [
"crates/api-server",
"crates/module-auth",
"crates/platform-oss",
"crates/platform-auth",
"crates/shared-logging",

View File

@@ -7,6 +7,7 @@ license.workspace = true
[dependencies]
axum = "0.8"
dotenvy = "0.15"
module-auth = { path = "../module-auth" }
platform-auth = { path = "../platform-auth" }
platform-oss = { path = "../platform-oss" }
serde = { version = "1", features = ["derive"] }

View File

@@ -28,6 +28,8 @@
6. `src/config.rs`
7. 基础 `TraceLayer` 挂载
8. 接入 `shared-logging` 完成 `tracing subscriber` 初始化
9. 接入 `POST /api/auth/entry` 首版密码登录链路
10. 接入 `POST /api/assets/direct-upload-tickets` 直传票据接口
后续与本 crate 直接相关的任务包括:
@@ -36,6 +38,8 @@
3. [x] 接入统一错误处理中间件
4. [x] 接入 response envelope
5. [x] 接入 `/healthz`
6. [x] 接入 `/api/auth/entry`
7. [x] 接入 `/api/assets/direct-upload-tickets`
当前 tracing 约定:
@@ -94,3 +98,4 @@
2. 业务逻辑优先通过独立模块 crate 暴露能力,再由主工程组合。
3. 外部副作用通过 `platform-auth``platform-oss``platform-llm` 与各模块 crate 的应用层完成。
4. 不把领域规则直接堆在 handler 中。
5. 当前密码登录由 `module-auth` 负责用例编排,`api-server` 只负责请求解析、JWT 签发与 refresh cookie 写回。

View File

@@ -123,7 +123,7 @@ mod tests {
let request_context = build_request_context(false);
let error = ApiErrorPayload {
code: "NOT_FOUND",
message: "资源不存在",
message: "资源不存在".to_string(),
details: None,
};
let body = json_error_body(Some(&request_context), &error).0;

View File

@@ -17,6 +17,7 @@ use crate::{
},
error_middleware::normalize_error_response,
health::health_check,
password_entry::password_entry,
request_context::{attach_request_context, resolve_request_id},
response_headers::propagate_request_id_header,
state::AppState,
@@ -49,6 +50,7 @@ pub fn build_router(state: AppState) -> Router {
"/api/assets/direct-upload-tickets",
post(create_direct_upload_ticket),
)
.route("/api/auth/entry", post(password_entry))
// 错误归一化层放在 tracing 里侧,让 tracing 记录到最终对外返回的状态与错误体形态。
.layer(middleware::from_fn(normalize_error_response))
// 响应头回写放在错误归一化外侧,确保最终写回的是归一化后的最终响应。
@@ -329,4 +331,179 @@ mod tests {
Value::Number(serde_json::Number::from(10))
);
}
#[tokio::test]
async fn password_entry_creates_user_and_sets_refresh_cookie() {
let app = build_router(AppState::new(AppConfig::default()).expect("state should build"));
let response = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/auth/entry")
.header("content-type", "application/json")
.body(Body::from(
serde_json::json!({
"username": "guest_001",
"password": "secret123"
})
.to_string(),
))
.expect("request should build"),
)
.await
.expect("request should succeed");
assert_eq!(response.status(), StatusCode::OK);
assert!(
response
.headers()
.get("set-cookie")
.and_then(|value| value.to_str().ok())
.is_some_and(|value| value.contains("genarrative_refresh_session="))
);
let body = response
.into_body()
.collect()
.await
.expect("response body should collect")
.to_bytes();
let payload: Value =
serde_json::from_slice(&body).expect("response body should be valid json");
assert_eq!(
payload["user"]["username"],
Value::String("guest_001".to_string())
);
assert!(payload["token"].as_str().is_some());
}
#[tokio::test]
async fn password_entry_reuses_same_user_for_same_credentials() {
let app = build_router(AppState::new(AppConfig::default()).expect("state should build"));
let first_response = app
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/auth/entry")
.header("content-type", "application/json")
.body(Body::from(
serde_json::json!({
"username": "guest_001",
"password": "secret123"
})
.to_string(),
))
.expect("request should build"),
)
.await
.expect("first request should succeed");
let first_body = first_response
.into_body()
.collect()
.await
.expect("first body should collect")
.to_bytes();
let first_payload: Value =
serde_json::from_slice(&first_body).expect("first payload should be json");
let second_response = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/auth/entry")
.header("content-type", "application/json")
.body(Body::from(
serde_json::json!({
"username": "guest_001",
"password": "secret123"
})
.to_string(),
))
.expect("request should build"),
)
.await
.expect("second request should succeed");
let second_body = second_response
.into_body()
.collect()
.await
.expect("second body should collect")
.to_bytes();
let second_payload: Value =
serde_json::from_slice(&second_body).expect("second payload should be json");
assert_eq!(first_payload["user"]["id"], second_payload["user"]["id"]);
}
#[tokio::test]
async fn password_entry_rejects_wrong_password() {
let app = build_router(AppState::new(AppConfig::default()).expect("state should build"));
app.clone()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/auth/entry")
.header("content-type", "application/json")
.body(Body::from(
serde_json::json!({
"username": "guest_001",
"password": "secret123"
})
.to_string(),
))
.expect("request should build"),
)
.await
.expect("seed request should succeed");
let response = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/auth/entry")
.header("content-type", "application/json")
.body(Body::from(
serde_json::json!({
"username": "guest_001",
"password": "secret999"
})
.to_string(),
))
.expect("request should build"),
)
.await
.expect("request should succeed");
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn password_entry_rejects_invalid_username() {
let app = build_router(AppState::new(AppConfig::default()).expect("state should build"));
let response = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/auth/entry")
.header("content-type", "application/json")
.body(Body::from(
serde_json::json!({
"username": "无效用户",
"password": "secret123"
})
.to_string(),
))
.expect("request should build"),
)
.await
.expect("request should succeed");
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}
}

View File

@@ -11,14 +11,14 @@ use crate::{api_response::json_error_body, request_context::RequestContext};
pub struct AppError {
status_code: StatusCode,
code: &'static str,
message: &'static str,
message: String,
details: Option<Value>,
}
#[derive(Clone, Debug, Serialize)]
pub struct ApiErrorPayload {
pub code: &'static str,
pub message: &'static str,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub details: Option<Value>,
}
@@ -30,7 +30,7 @@ impl AppError {
Self {
status_code,
code,
message,
message: message.to_string(),
details: None,
}
}
@@ -39,6 +39,11 @@ impl AppError {
self.code
}
pub fn with_message(mut self, message: impl Into<String>) -> Self {
self.message = message.into();
self
}
pub fn with_details(mut self, details: Value) -> Self {
self.details = Some(details);
self
@@ -54,7 +59,7 @@ impl AppError {
fn to_payload(&self) -> ApiErrorPayload {
ApiErrorPayload {
code: self.code,
message: self.message,
message: self.message.clone(),
details: self.details.clone(),
}
}

View File

@@ -6,6 +6,7 @@ mod config;
mod error_middleware;
mod health;
mod http_error;
mod password_entry;
mod request_context;
mod response_headers;
mod state;

View File

@@ -0,0 +1,132 @@
use axum::{
Json,
extract::{Extension, State},
http::{HeaderMap, HeaderValue, StatusCode, header::SET_COOKIE},
response::IntoResponse,
};
use module_auth::{PasswordEntryError, PasswordEntryInput};
use platform_auth::{
AccessTokenClaims, AccessTokenClaimsInput, AuthProvider, BindingStatus,
build_refresh_session_set_cookie, create_refresh_session_token, sign_access_token,
};
use serde::{Deserialize, Serialize};
use serde_json::json;
use time::OffsetDateTime;
use crate::{
api_response::json_success_body, http_error::AppError, request_context::RequestContext,
state::AppState,
};
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PasswordEntryRequest {
pub username: String,
pub password: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PasswordEntryResponse {
pub token: String,
pub user: PasswordEntryUserPayload,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PasswordEntryUserPayload {
pub id: String,
pub username: String,
pub display_name: String,
pub phone_number_masked: Option<String>,
pub login_method: &'static str,
pub binding_status: &'static str,
pub wechat_bound: bool,
}
pub async fn password_entry(
State(state): State<AppState>,
Extension(request_context): Extension<RequestContext>,
Json(payload): Json<PasswordEntryRequest>,
) -> Result<impl IntoResponse, AppError> {
let result = state
.password_entry_service()
.execute(PasswordEntryInput {
username: payload.username,
password: payload.password,
})
.await
.map_err(map_password_entry_error)?;
let refresh_session_token = create_refresh_session_token();
let access_claims = AccessTokenClaims::from_input(
AccessTokenClaimsInput {
user_id: result.user.id.clone(),
session_id: refresh_session_token.clone(),
provider: AuthProvider::Password,
roles: vec!["user".to_string()],
token_version: result.user.token_version,
phone_verified: false,
binding_status: BindingStatus::Active,
display_name: Some(result.user.display_name.clone()),
},
state.auth_jwt_config(),
OffsetDateTime::now_utc(),
)
.map_err(|error| {
AppError::from_status(StatusCode::INTERNAL_SERVER_ERROR).with_message(error.to_string())
})?;
let access_token =
sign_access_token(&access_claims, state.auth_jwt_config()).map_err(|error| {
AppError::from_status(StatusCode::INTERNAL_SERVER_ERROR).with_message(error.to_string())
})?;
let refresh_cookie =
build_refresh_session_set_cookie(&refresh_session_token, state.refresh_cookie_config());
let mut headers = HeaderMap::new();
let set_cookie = HeaderValue::from_str(&refresh_cookie).map_err(|error| {
AppError::from_status(StatusCode::INTERNAL_SERVER_ERROR)
.with_message(format!("refresh cookie 头构造失败:{error}"))
})?;
headers.insert(SET_COOKIE, set_cookie);
Ok((
headers,
json_success_body(
Some(&request_context),
PasswordEntryResponse {
token: access_token,
user: PasswordEntryUserPayload {
id: result.user.id,
username: result.user.username,
display_name: result.user.display_name,
phone_number_masked: result.user.phone_number_masked,
login_method: result.user.login_method.as_str(),
binding_status: result.user.binding_status.as_str(),
wechat_bound: result.user.wechat_bound,
},
},
),
))
}
fn map_password_entry_error(error: PasswordEntryError) -> AppError {
match error {
PasswordEntryError::InvalidUsername => AppError::from_status(StatusCode::BAD_REQUEST)
.with_message("用户名只允许 3 到 24 位字母、数字、下划线")
.with_details(json!({
"field": "username",
})),
PasswordEntryError::InvalidPasswordLength => AppError::from_status(StatusCode::BAD_REQUEST)
.with_message("密码长度需要在 6 到 128 位之间")
.with_details(json!({
"field": "password",
})),
PasswordEntryError::InvalidCredentials => {
AppError::from_status(StatusCode::UNAUTHORIZED).with_message("用户名或密码错误")
}
PasswordEntryError::Store(_) | PasswordEntryError::PasswordHash(_) => {
AppError::from_status(StatusCode::INTERNAL_SERVER_ERROR).with_message(error.to_string())
}
}
}

View File

@@ -1,5 +1,6 @@
use std::{error::Error, fmt};
use module_auth::{InMemoryPasswordUserStore, PasswordEntryService};
use platform_auth::{
JwtConfig, JwtError, RefreshCookieConfig, RefreshCookieError, RefreshCookieSameSite,
};
@@ -16,6 +17,7 @@ pub struct AppState {
auth_jwt_config: JwtConfig,
refresh_cookie_config: RefreshCookieConfig,
oss_client: Option<OssClient>,
password_entry_service: PasswordEntryService,
}
#[derive(Debug)]
@@ -44,12 +46,15 @@ impl AppState {
config.refresh_session_ttl_days,
)?;
let oss_client = build_oss_client(&config)?;
let password_entry_service =
PasswordEntryService::new(InMemoryPasswordUserStore::default());
Ok(Self {
config,
auth_jwt_config,
refresh_cookie_config,
oss_client,
password_entry_service,
})
}
@@ -64,6 +69,10 @@ impl AppState {
pub fn oss_client(&self) -> Option<&OssClient> {
self.oss_client.as_ref()
}
pub fn password_entry_service(&self) -> &PasswordEntryService {
&self.password_entry_service
}
}
impl fmt::Display for AppStateInitError {

View File

@@ -0,0 +1,11 @@
[package]
name = "module-auth"
edition.workspace = true
version.workspace = true
license.workspace = true
[dependencies]
platform-auth = { path = "../platform-auth" }
[dev-dependencies]
tokio = { version = "1", features = ["macros", "rt"] }

View File

@@ -1,28 +1,34 @@
# module-auth 独立模块 crate 占位说明
# module-auth 鉴权模块 crate 说明
日期:`2026-04-20`
日期:`2026-04-21`
## 1. crate 职责
`module-auth` 是鉴权与会话模块 crate后续负责
`module-auth` 是鉴权与会话模块 crate当前与后续负责:
1. 用户身份、会话、风控、审计相关领域模型
2. 手机验证码、微信登录、密码登录的模块内用例编排
3.`crates/api-server` 的鉴权接口装配对接
4.`crates/spacetime-module` 的身份表、会话表聚合对接
1. 用户身份、会话、风控、审计相关领域模型
2. 手机验证码、微信登录、密码登录的模块内用例编排
3.`crates/api-server` 的鉴权接口装配对接
4.`crates/spacetime-module` 的身份表、会话表聚合对接
## 2. 当前阶段说明
当前阶段已冻结前七张鉴权基础表设计,剩余重点收口在 JWT claims、refresh cookie 与旧接口兼容细节。
当前阶段已冻结前七张鉴权基础表设计,并已完成:
后续与本 crate 直接相关的任务包括:
1. JWT claims 设计与 `platform-auth` 落地。
2. refresh cookie 读取适配。
3. `module-auth` 真实 crate 与首版密码登录用例落地。
4. 微信登录链路暂缓执行,不进入当前连续实现顺序。
1. 设计 `user_account``auth_identity``refresh_session`
2. 设计 `auth_audit_log``auth_risk_block`
3. 设计 `sms_auth_event``wechat_auth_state`
4. 落地 JWT claims、refresh cookie 与旧接口兼容
当前连续实现优先顺序固定为:
当前已冻结文档:
1. 密码登录
2. `me` 查询
3. refresh token 轮换
4. 会话吊销
5. 手机验证码登录
## 3. 当前已冻结文档
1. [../../../docs/technical/SPACETIMEDB_AUTH_USER_ACCOUNT_TABLE_DESIGN_2026-04-21.md](../../../docs/technical/SPACETIMEDB_AUTH_USER_ACCOUNT_TABLE_DESIGN_2026-04-21.md)
2. [../../../docs/technical/SPACETIMEDB_AUTH_IDENTITY_TABLE_DESIGN_2026-04-21.md](../../../docs/technical/SPACETIMEDB_AUTH_IDENTITY_TABLE_DESIGN_2026-04-21.md)
@@ -32,9 +38,14 @@
6. [../../../docs/technical/SPACETIMEDB_SMS_AUTH_EVENT_TABLE_DESIGN_2026-04-21.md](../../../docs/technical/SPACETIMEDB_SMS_AUTH_EVENT_TABLE_DESIGN_2026-04-21.md)
7. [../../../docs/technical/SPACETIMEDB_WECHAT_AUTH_STATE_TABLE_DESIGN_2026-04-21.md](../../../docs/technical/SPACETIMEDB_WECHAT_AUTH_STATE_TABLE_DESIGN_2026-04-21.md)
8. [../../../docs/technical/OIDC_JWT_CLAIMS_DESIGN_2026-04-21.md](../../../docs/technical/OIDC_JWT_CLAIMS_DESIGN_2026-04-21.md)
9. [../../../docs/technical/PLATFORM_AUTH_JWT_ADAPTER_DESIGN_2026-04-21.md](../../../docs/technical/PLATFORM_AUTH_JWT_ADAPTER_DESIGN_2026-04-21.md)
10. [../../../docs/technical/PLATFORM_AUTH_REFRESH_COOKIE_ADAPTER_DESIGN_2026-04-21.md](../../../docs/technical/PLATFORM_AUTH_REFRESH_COOKIE_ADAPTER_DESIGN_2026-04-21.md)
11. [../../../docs/technical/PASSWORD_ENTRY_FLOW_DESIGN_2026-04-21.md](../../../docs/technical/PASSWORD_ENTRY_FLOW_DESIGN_2026-04-21.md)
## 3. 边界约束
## 4. 边界约束
1. `module-auth` 负责鉴权领域规则与模块级编排,不直接把供应商 SDK 逻辑写进主工程。
2. 短信、微信、JWT、Cookie 等平台适配优先通过 `crates/platform-auth` 承接。
2. 短信、微信、JWT、Cookie、密码哈希等平台适配优先通过 `crates/platform-auth` 承接。
3. 身份与会话状态最终由 `crates/spacetime-module` 聚合,前端接口由 `crates/api-server` 暴露。
4. 当前阶段允许先使用进程内适配器把用例跑通,但后续切到 `SpacetimeDB` 时应保持用例接口稳定。
5. 当前 `PasswordEntryService` 已承接用户名校验、密码哈希校验、自动建号与重复登录复用逻辑。

View File

@@ -0,0 +1,353 @@
use std::{
collections::HashMap,
error::Error,
fmt,
sync::{Arc, Mutex},
};
use platform_auth::{hash_password, verify_password};
const USERNAME_MIN_LENGTH: usize = 3;
const USERNAME_MAX_LENGTH: usize = 24;
const PASSWORD_MIN_LENGTH: usize = 6;
const PASSWORD_MAX_LENGTH: usize = 128;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AuthLoginMethod {
Password,
Phone,
Wechat,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AuthBindingStatus {
Active,
PendingBindPhone,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AuthUser {
pub id: String,
pub username: String,
pub display_name: String,
pub phone_number_masked: Option<String>,
pub login_method: AuthLoginMethod,
pub binding_status: AuthBindingStatus,
pub wechat_bound: bool,
pub token_version: u64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PasswordEntryInput {
pub username: String,
pub password: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PasswordEntryResult {
pub user: AuthUser,
pub created: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PasswordEntryError {
InvalidUsername,
InvalidPasswordLength,
InvalidCredentials,
Store(String),
PasswordHash(String),
}
#[derive(Clone, Debug)]
pub struct InMemoryPasswordUserStore {
inner: Arc<Mutex<InMemoryPasswordUserStoreState>>,
}
#[derive(Debug)]
struct InMemoryPasswordUserStoreState {
next_id: u64,
users_by_username: HashMap<String, StoredPasswordUser>,
}
#[derive(Clone, Debug)]
struct StoredPasswordUser {
user: AuthUser,
password_hash: String,
}
#[derive(Clone, Debug)]
pub struct PasswordEntryService {
store: InMemoryPasswordUserStore,
}
impl PasswordEntryService {
pub fn new(store: InMemoryPasswordUserStore) -> Self {
Self { store }
}
pub async fn execute(
&self,
input: PasswordEntryInput,
) -> Result<PasswordEntryResult, PasswordEntryError> {
let username = normalize_username(&input.username)?;
validate_password(&input.password)?;
if let Some(existing_user) = self.store.find_by_username(&username)? {
let is_valid = verify_password(&existing_user.password_hash, &input.password)
.await
.map_err(|error| PasswordEntryError::PasswordHash(error.to_string()))?;
if !is_valid {
return Err(PasswordEntryError::InvalidCredentials);
}
return Ok(PasswordEntryResult {
user: existing_user.user,
created: false,
});
}
let password_hash = hash_password(&input.password)
.await
.map_err(|error| PasswordEntryError::PasswordHash(error.to_string()))?;
match self
.store
.create_user(username.clone(), password_hash.clone())
{
Ok(user) => Ok(PasswordEntryResult {
user,
created: true,
}),
Err(CreateUserError::AlreadyExists) => {
let existing_user = self.store.find_by_username(&username)?.ok_or_else(|| {
PasswordEntryError::Store("唯一键冲突后未能重新读取账号".to_string())
})?;
let is_valid = verify_password(&existing_user.password_hash, &input.password)
.await
.map_err(|error| PasswordEntryError::PasswordHash(error.to_string()))?;
if !is_valid {
return Err(PasswordEntryError::InvalidCredentials);
}
Ok(PasswordEntryResult {
user: existing_user.user,
created: false,
})
}
Err(CreateUserError::Store(message)) => Err(PasswordEntryError::Store(message)),
}
}
}
impl Default for InMemoryPasswordUserStore {
fn default() -> Self {
Self {
inner: Arc::new(Mutex::new(InMemoryPasswordUserStoreState {
next_id: 1,
users_by_username: HashMap::new(),
})),
}
}
}
impl InMemoryPasswordUserStore {
fn find_by_username(
&self,
username: &str,
) -> Result<Option<StoredPasswordUser>, PasswordEntryError> {
let state = self
.inner
.lock()
.map_err(|_| PasswordEntryError::Store("用户仓储锁已中毒".to_string()))?;
Ok(state.users_by_username.get(username).cloned())
}
fn create_user(
&self,
username: String,
password_hash: String,
) -> Result<AuthUser, CreateUserError> {
let mut state = self
.inner
.lock()
.map_err(|_| CreateUserError::Store("用户仓储锁已中毒".to_string()))?;
if state.users_by_username.contains_key(&username) {
return Err(CreateUserError::AlreadyExists);
}
let user_id = format!("user_{:08}", state.next_id);
state.next_id += 1;
let user = AuthUser {
id: user_id,
username: username.clone(),
display_name: username.clone(),
phone_number_masked: None,
login_method: AuthLoginMethod::Password,
binding_status: AuthBindingStatus::Active,
wechat_bound: false,
token_version: 1,
};
state.users_by_username.insert(
username,
StoredPasswordUser {
user: user.clone(),
password_hash,
},
);
Ok(user)
}
}
#[derive(Debug, PartialEq, Eq)]
enum CreateUserError {
AlreadyExists,
Store(String),
}
impl AuthLoginMethod {
pub fn as_str(&self) -> &'static str {
match self {
Self::Password => "password",
Self::Phone => "phone",
Self::Wechat => "wechat",
}
}
}
impl AuthBindingStatus {
pub fn as_str(&self) -> &'static str {
match self {
Self::Active => "active",
Self::PendingBindPhone => "pending_bind_phone",
}
}
}
impl fmt::Display for PasswordEntryError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidUsername => f.write_str("用户名只允许 3 到 24 位字母、数字、下划线"),
Self::InvalidPasswordLength => f.write_str("密码长度需要在 6 到 128 位之间"),
Self::InvalidCredentials => f.write_str("用户名或密码错误"),
Self::Store(message) | Self::PasswordHash(message) => f.write_str(message),
}
}
}
impl Error for PasswordEntryError {}
fn normalize_username(raw_username: &str) -> Result<String, PasswordEntryError> {
let username = raw_username.trim().to_string();
let valid_length =
(USERNAME_MIN_LENGTH..=USERNAME_MAX_LENGTH).contains(&username.chars().count());
let valid_chars = username
.chars()
.all(|character| character.is_ascii_alphanumeric() || character == '_');
if !valid_length || !valid_chars {
return Err(PasswordEntryError::InvalidUsername);
}
Ok(username)
}
fn validate_password(password: &str) -> Result<(), PasswordEntryError> {
let length = password.chars().count();
if !(PASSWORD_MIN_LENGTH..=PASSWORD_MAX_LENGTH).contains(&length) {
return Err(PasswordEntryError::InvalidPasswordLength);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn build_service() -> PasswordEntryService {
PasswordEntryService::new(InMemoryPasswordUserStore::default())
}
#[tokio::test]
async fn first_password_entry_creates_user() {
let service = build_service();
let result = service
.execute(PasswordEntryInput {
username: "guest_001".to_string(),
password: "secret123".to_string(),
})
.await
.expect("first login should succeed");
assert!(result.created);
assert_eq!(result.user.id, "user_00000001");
assert_eq!(result.user.username, "guest_001");
assert_eq!(result.user.display_name, "guest_001");
assert_eq!(result.user.login_method, AuthLoginMethod::Password);
assert_eq!(result.user.binding_status, AuthBindingStatus::Active);
}
#[tokio::test]
async fn repeated_password_entry_reuses_same_user() {
let service = build_service();
let first = service
.execute(PasswordEntryInput {
username: "guest_001".to_string(),
password: "secret123".to_string(),
})
.await
.expect("first login should succeed");
let second = service
.execute(PasswordEntryInput {
username: "guest_001".to_string(),
password: "secret123".to_string(),
})
.await
.expect("second login should succeed");
assert!(first.created);
assert!(!second.created);
assert_eq!(second.user.id, first.user.id);
}
#[tokio::test]
async fn repeated_password_entry_rejects_wrong_password() {
let service = build_service();
service
.execute(PasswordEntryInput {
username: "guest_001".to_string(),
password: "secret123".to_string(),
})
.await
.expect("first login should succeed");
let error = service
.execute(PasswordEntryInput {
username: "guest_001".to_string(),
password: "secret999".to_string(),
})
.await
.expect_err("wrong password should fail");
assert_eq!(error, PasswordEntryError::InvalidCredentials);
}
#[tokio::test]
async fn invalid_username_returns_bad_request_error() {
let service = build_service();
let error = service
.execute(PasswordEntryInput {
username: "坏用户名".to_string(),
password: "secret123".to_string(),
})
.await
.expect_err("invalid username should fail");
assert_eq!(error, PasswordEntryError::InvalidUsername);
}
}

View File

@@ -5,7 +5,13 @@ version.workspace = true
license.workspace = true
[dependencies]
argon2 = "0.5"
jsonwebtoken = "9"
rand_core = { version = "0.6", features = ["getrandom"] }
serde = { version = "1", features = ["derive"] }
time = { version = "0.3", features = ["std"] }
urlencoding = "2"
uuid = { version = "1", features = ["v4"] }
[dev-dependencies]
tokio = { version = "1", features = ["macros", "rt"] }

View File

@@ -1,10 +1,13 @@
use std::{collections::HashSet, error::Error, fmt};
use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier, password_hash::SaltString};
use jsonwebtoken::{
Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode, errors::ErrorKind,
};
use rand_core::OsRng;
use serde::{Deserialize, Serialize};
use time::{Duration, OffsetDateTime};
use uuid::Uuid;
pub const ACCESS_TOKEN_ALGORITHM: Algorithm = Algorithm::HS256;
pub const DEFAULT_ACCESS_TOKEN_TTL_SECONDS: u64 = 2 * 60 * 60;
@@ -98,6 +101,12 @@ pub enum RefreshCookieError {
InvalidConfig(&'static str),
}
#[derive(Debug, PartialEq, Eq)]
pub enum PasswordHashError {
HashFailed(String),
VerifyFailed(String),
}
impl JwtConfig {
pub fn new(
issuer: String,
@@ -370,6 +379,53 @@ pub fn read_refresh_session_token(
None
}
pub async fn hash_password(password: &str) -> Result<String, PasswordHashError> {
let salt = SaltString::generate(&mut OsRng);
Argon2::default()
.hash_password(password.as_bytes(), &salt)
.map(|hash| hash.to_string())
.map_err(|error| PasswordHashError::HashFailed(format!("密码哈希失败:{error}")))
}
pub async fn verify_password(
password_hash: &str,
password: &str,
) -> Result<bool, PasswordHashError> {
let parsed_hash = PasswordHash::new(password_hash)
.map_err(|error| PasswordHashError::VerifyFailed(format!("密码哈希格式非法:{error}")))?;
Ok(Argon2::default()
.verify_password(password.as_bytes(), &parsed_hash)
.is_ok())
}
pub fn create_refresh_session_token() -> String {
Uuid::new_v4().simple().to_string()
}
pub fn build_refresh_session_set_cookie(token: &str, config: &RefreshCookieConfig) -> String {
let mut parts = vec![
format!(
"{}={}",
config.cookie_name(),
urlencoding::encode(token).into_owned()
),
format!("Path={}", config.cookie_path()),
"HttpOnly".to_string(),
format!("SameSite={}", config.cookie_same_site().as_str()),
format!(
"Max-Age={}",
u64::from(config.refresh_session_ttl_days()) * 24 * 60 * 60
),
];
if config.cookie_secure() {
parts.push("Secure".to_string());
}
parts.join("; ")
}
impl fmt::Display for JwtError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
@@ -391,6 +447,16 @@ impl fmt::Display for RefreshCookieError {
impl Error for RefreshCookieError {}
impl fmt::Display for PasswordHashError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::HashFailed(message) | Self::VerifyFailed(message) => f.write_str(message),
}
}
}
impl Error for PasswordHashError {}
fn normalize_required_field(
value: String,
error_message: &'static str,
@@ -560,4 +626,29 @@ mod tests {
assert!(token.is_none());
}
#[tokio::test]
async fn hash_and_verify_password_round_trip() {
let password_hash = hash_password("secret123")
.await
.expect("password hash should build");
let is_valid = verify_password(&password_hash, "secret123")
.await
.expect("password hash should verify");
assert!(is_valid);
}
#[test]
fn build_refresh_session_cookie_respects_config() {
let cookie =
build_refresh_session_set_cookie("refresh/token=01", &build_refresh_cookie_config());
assert!(cookie.contains("genarrative_refresh_session=refresh%2Ftoken%3D01"));
assert!(cookie.contains("Path=/api/auth"));
assert!(cookie.contains("HttpOnly"));
assert!(cookie.contains("SameSite=Lax"));
assert!(cookie.contains("Max-Age=2592000"));
}
}