use crate::action::{ActionContext, ApiResponse, TypedHandler, User};
use crate::error::BaseError;
use crate::router::middleware::{Middleware, MiddlewareRole, MiddlewareScope, Next};
use crate::token::TokenClaims;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use yang_base_derive::Action;
#[derive(Clone, Deserialize, schemars::JsonSchema)]
pub struct LoginInput {
pub username: String,
pub password: String,
#[serde(default)]
pub extra: serde_json::Value,
}
impl core::fmt::Debug for LoginInput {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("LoginInput")
.field("username", &self.username)
.field("password", &"***")
.field("extra", &self.extra)
.finish()
}
}
#[derive(Clone, Serialize, schemars::JsonSchema)]
pub struct TokenPairResponse {
pub access_token: String,
pub refresh_token: String,
}
impl core::fmt::Debug for TokenPairResponse {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("TokenPairResponse")
.field(
"access_token",
&format!("***({} chars)", self.access_token.len()),
)
.field(
"refresh_token",
&format!("***({} chars)", self.refresh_token.len()),
)
.finish()
}
}
#[derive(Clone, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RefreshInput {
pub refresh_token: String,
}
impl core::fmt::Debug for RefreshInput {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("RefreshInput")
.field(
"refresh_token",
&format!("***({} chars)", self.refresh_token.len()),
)
.finish()
}
}
#[derive(Clone, Serialize, schemars::JsonSchema)]
pub struct AccessTokenResponse {
pub access_token: String,
}
impl core::fmt::Debug for AccessTokenResponse {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("AccessTokenResponse")
.field(
"access_token",
&format!("***({} chars)", self.access_token.len()),
)
.finish()
}
}
#[derive(Clone, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct LogoutInput {
pub token: String,
#[serde(default)]
pub refresh_token: Option<String>,
}
impl core::fmt::Debug for LogoutInput {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("LogoutInput")
.field("token", &format!("***({} chars)", self.token.len()))
.field(
"refresh_token",
&self
.refresh_token
.as_ref()
.map(|s| format!("***({} chars)", s.len())),
)
.finish()
}
}
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
pub struct MessageResponse {
pub message: String,
}
#[derive(Debug, Clone)]
pub struct VerifiedSubject {
pub subject: String,
pub custom_claims: serde_json::Value,
}
impl VerifiedSubject {
pub fn new(subject: impl Into<String>) -> Self {
Self {
subject: subject.into(),
custom_claims: serde_json::Value::Null,
}
}
pub fn with_claims(mut self, claims: serde_json::Value) -> Self {
self.custom_claims = claims;
self
}
}
#[async_trait]
pub trait CredentialVerifier: Send + Sync + 'static {
async fn verify(
&self,
ctx: &ActionContext,
input: &LoginInput,
) -> Result<VerifiedSubject, BaseError>;
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct AuthAuditEvent {
pub request_id: String,
pub action: &'static str,
pub subject: Option<String>,
pub error_code: Option<&'static str>,
}
pub fn token_fingerprint(token: &str) -> String {
let mut hash: u64 = 0xcbf29ce484222325;
for b in token.as_bytes() {
hash ^= *b as u64;
hash = hash.wrapping_mul(0x100000001b3);
}
format!("{:016x}", hash)
}
#[async_trait]
pub trait AuthAuditHook: Send + Sync + 'static {
async fn on_success(&self, event: AuthAuditEvent);
async fn on_failure(&self, event: AuthAuditEvent);
}
#[derive(Debug, Clone, Default)]
pub struct TracingAuditHook;
#[async_trait]
impl AuthAuditHook for TracingAuditHook {
async fn on_success(&self, event: AuthAuditEvent) {
tracing::info!(
request_id = %event.request_id,
action = event.action,
subject = event.subject.as_deref().unwrap_or("-"),
"认证成功",
);
}
async fn on_failure(&self, event: AuthAuditEvent) {
tracing::warn!(
request_id = %event.request_id,
action = event.action,
subject = event.subject.as_deref().unwrap_or("-"),
error_code = event.error_code.unwrap_or("-"),
"认证失败",
);
}
}
#[derive(Action)]
#[action(
name = "login",
display_name = "登录",
description = "校验凭证并签发 Token 对",
public
)]
pub struct LoginAction<V: CredentialVerifier, A: AuthAuditHook = TracingAuditHook> {
verifier: V,
audit: A,
}
impl<V: CredentialVerifier> LoginAction<V, TracingAuditHook> {
pub fn new(verifier: V) -> Self {
Self {
verifier,
audit: TracingAuditHook,
}
}
}
impl<V: CredentialVerifier, A: AuthAuditHook> LoginAction<V, A> {
pub fn with_audit(verifier: V, audit: A) -> Self {
Self { verifier, audit }
}
}
#[async_trait]
impl<V: CredentialVerifier, A: AuthAuditHook> TypedHandler for LoginAction<V, A> {
type Input = LoginInput;
type Output = TokenPairResponse;
async fn handle(
&self,
ctx: ActionContext,
input: LoginInput,
) -> Result<TokenPairResponse, BaseError> {
let request_id = ctx.request_id.to_string();
let subject = match self.verifier.verify(&ctx, &input).await {
Ok(s) => s,
Err(e) => {
self.audit
.on_failure(AuthAuditEvent {
request_id,
action: "login",
subject: Some(input.username.clone()),
error_code: Some(e.code_str()),
})
.await;
return Err(e);
}
};
let result = ctx
.tools()
.token()?
.generate_token_pair(&subject.subject, subject.custom_claims);
match result {
Ok((access_token, refresh_token)) => {
self.audit
.on_success(AuthAuditEvent {
request_id,
action: "login",
subject: Some(subject.subject.clone()),
error_code: None,
})
.await;
Ok(TokenPairResponse {
access_token,
refresh_token,
})
}
Err(e) => {
self.audit
.on_failure(AuthAuditEvent {
request_id,
action: "login",
subject: Some(subject.subject.clone()),
error_code: Some(e.code_str()),
})
.await;
Err(e)
}
}
}
}
#[async_trait]
pub trait RefreshClaimsResolver: Send + Sync + 'static {
async fn resolve(&self, ctx: &ActionContext, sub: &str)
-> Result<serde_json::Value, BaseError>;
}
#[derive(Debug, Clone, Default)]
pub struct DefaultRefreshClaims;
#[async_trait]
impl RefreshClaimsResolver for DefaultRefreshClaims {
async fn resolve(
&self,
_ctx: &ActionContext,
_sub: &str,
) -> Result<serde_json::Value, BaseError> {
Ok(serde_json::Value::Null)
}
}
#[derive(Action, Default)]
#[action(
name = "refresh",
display_name = "刷新 Token",
description = "用 Refresh Token 换取新的 Access Token",
public
)]
pub struct RefreshAction<
R: RefreshClaimsResolver = DefaultRefreshClaims,
A: AuthAuditHook = TracingAuditHook,
> {
resolver: R,
audit: A,
}
impl<R: RefreshClaimsResolver> RefreshAction<R, TracingAuditHook> {
pub fn new(resolver: R) -> Self {
Self {
resolver,
audit: TracingAuditHook,
}
}
}
impl<R: RefreshClaimsResolver, A: AuthAuditHook> RefreshAction<R, A> {
pub fn with_audit(resolver: R, audit: A) -> Self {
Self { resolver, audit }
}
}
#[async_trait]
impl<R: RefreshClaimsResolver, A: AuthAuditHook> TypedHandler for RefreshAction<R, A> {
type Input = RefreshInput;
type Output = TokenPairResponse;
async fn handle(
&self,
ctx: ActionContext,
input: RefreshInput,
) -> Result<TokenPairResponse, BaseError> {
let request_id = ctx.request_id.to_string();
let manager = ctx.tools().token()?;
let run = async {
let claims = manager.verify_token_checked(&input.refresh_token).await?;
if claims.token_type != crate::token::TokenType::Refresh {
return Err(BaseError::TokenTypeInvalid(
"期望 refresh token".to_string(),
));
}
let custom_claims = self.resolver.resolve(&ctx, &claims.sub).await?;
let (access_token, refresh_token) = manager
.rotate_refresh_token_from_claims(&claims, custom_claims)
.await?;
Ok::<_, BaseError>((access_token, refresh_token, claims.sub))
};
match run.await {
Ok((access_token, refresh_token, sub)) => {
self.audit
.on_success(AuthAuditEvent {
request_id,
action: "refresh",
subject: Some(sub),
error_code: None,
})
.await;
Ok(TokenPairResponse {
access_token,
refresh_token,
})
}
Err(e) => {
self.audit
.on_failure(AuthAuditEvent {
request_id,
action: "refresh",
subject: None,
error_code: Some(e.code_str()),
})
.await;
Err(e)
}
}
}
}
#[derive(Action, Default)]
#[action(
name = "logout",
display_name = "登出",
description = "撤销 Token,使其在过期前失效",
public
)]
pub struct LogoutAction<A: AuthAuditHook = TracingAuditHook> {
audit: A,
}
impl LogoutAction<TracingAuditHook> {
pub fn new() -> Self {
Self {
audit: TracingAuditHook,
}
}
}
impl<A: AuthAuditHook> LogoutAction<A> {
pub fn with_audit(audit: A) -> Self {
Self { audit }
}
}
#[async_trait]
impl<A: AuthAuditHook> TypedHandler for LogoutAction<A> {
type Input = LogoutInput;
type Output = MessageResponse;
async fn handle(
&self,
ctx: ActionContext,
input: LogoutInput,
) -> Result<MessageResponse, BaseError> {
let request_id = ctx.request_id.to_string();
let manager = ctx.tools().token()?;
let run = async {
let target_claims = manager.verify_token(&input.token)?;
if let Some(bearer_token) = ctx.request.token() {
let caller_claims = manager.verify_token_checked(bearer_token).await?;
if caller_claims.sub != target_claims.sub {
return Err(BaseError::PermissionDenied(
"只能撤销自己的 Token".to_string(),
));
}
}
manager.revoke_by_subject(&target_claims.sub).await?;
Ok::<(), BaseError>(())
};
match run.await {
Ok(()) => {
self.audit
.on_success(AuthAuditEvent {
request_id,
action: "logout",
subject: Some(token_fingerprint(&input.token)),
error_code: None,
})
.await;
Ok(MessageResponse {
message: "已登出".to_string(),
})
}
Err(e) => {
self.audit
.on_failure(AuthAuditEvent {
request_id,
action: "logout",
subject: Some(token_fingerprint(&input.token)),
error_code: Some(e.code_str()),
})
.await;
Err(e)
}
}
}
}
pub struct TokenAuthMiddleware<F> {
build_user: F,
authenticate_public_actions: bool,
}
#[doc(hidden)]
pub trait IntoUserProjection {
fn into_user_projection(self) -> Result<User, BaseError>;
}
impl IntoUserProjection for User {
fn into_user_projection(self) -> Result<User, BaseError> {
Ok(self)
}
}
impl IntoUserProjection for Result<User, BaseError> {
fn into_user_projection(self) -> Result<User, BaseError> {
self
}
}
impl<F, R> TokenAuthMiddleware<F>
where
F: Fn(&TokenClaims) -> R + Send + Sync + 'static,
R: IntoUserProjection,
{
pub fn new(build_user: F) -> Self {
Self {
build_user,
authenticate_public_actions: false,
}
}
pub fn authenticate_public_actions(mut self) -> Self {
self.authenticate_public_actions = true;
self
}
}
#[async_trait]
impl<F, R> Middleware for TokenAuthMiddleware<F>
where
F: Fn(&TokenClaims) -> R + Send + Sync + 'static,
R: IntoUserProjection + Send + Sync + 'static,
{
fn role(&self) -> MiddlewareRole {
MiddlewareRole::Authentication
}
fn scope(&self) -> MiddlewareScope {
if self.authenticate_public_actions {
MiddlewareScope::AllActions
} else {
MiddlewareScope::ProtectedActions
}
}
async fn handle(
&self,
mut ctx: ActionContext,
next: Next<'_>,
) -> Result<ApiResponse, BaseError> {
let token = match ctx.request.token() {
Some(t) => t.to_string(),
None if self.authenticate_public_actions
&& next.policy.is_public
&& ctx.request.get_header("authorization").is_none() =>
{
return next.run(ctx).await;
}
None => {
return Err(BaseError::Unauthorized(
"缺少 Authorization Bearer Token".to_string(),
))
}
};
let claims = ctx.tools().token()?.verify_token_checked(&token).await?;
if claims.token_type != crate::token::TokenType::Access {
return Err(BaseError::TokenTypeInvalid("期望 access token".into()));
}
ctx.user = Some((self.build_user)(&claims).into_user_projection()?);
next.run(ctx).await
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::action::{DynAction, TypedAction, UiCatalogAction};
use crate::definition::{
ActionName, ActionRef, ActionSpec, AddonName, AddonSpec, AppBuilder, BuiltApp, HttpMethod,
ModuleName, ModuleSpec, RouteSpec,
};
use crate::router::{Middleware, Next};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use testcontainers::{runners::AsyncRunner, GenericImage};
use yang_db::{RedisClient, RedisConfig};
struct DummyVerifier;
#[async_trait]
impl CredentialVerifier for DummyVerifier {
async fn verify(
&self,
_ctx: &ActionContext,
input: &LoginInput,
) -> Result<VerifiedSubject, BaseError> {
Ok(VerifiedSubject::new(format!("user:{}", input.username)))
}
}
#[derive(Debug, Default, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct EmptyInput {}
#[derive(Debug, Serialize, JsonSchema)]
struct ProbeOutput {
authenticated: bool,
}
#[derive(Action)]
#[action(name = "protected_probe", display_name = "受保护探针")]
struct ProtectedProbe;
#[async_trait]
impl TypedHandler for ProtectedProbe {
type Input = EmptyInput;
type Output = ProbeOutput;
async fn handle(
&self,
ctx: ActionContext,
_input: Self::Input,
) -> Result<Self::Output, BaseError> {
Ok(ProbeOutput {
authenticated: ctx.authenticated_user().is_some(),
})
}
}
#[derive(Action)]
#[action(name = "public_probe", display_name = "公开探针", public)]
struct PublicProbe;
#[async_trait]
impl TypedHandler for PublicProbe {
type Input = EmptyInput;
type Output = ProbeOutput;
async fn handle(
&self,
ctx: ActionContext,
_input: Self::Input,
) -> Result<Self::Output, BaseError> {
Ok(ProbeOutput {
authenticated: ctx.authenticated_user().is_some(),
})
}
}
struct CountingMiddleware(Arc<AtomicUsize>);
#[async_trait]
impl Middleware for CountingMiddleware {
async fn handle(
&self,
ctx: ActionContext,
next: Next<'_>,
) -> Result<ApiResponse, BaseError> {
self.0.fetch_add(1, Ordering::SeqCst);
next.run(ctx).await
}
}
fn test_token_manager() -> crate::token::TokenManager {
crate::token::TokenManager::new_symmetric(
"mixed-public-protected-actions-test-secret",
jsonwebtoken::Algorithm::HS256,
"test-issuer".to_string(),
"test-audience".to_string(),
3600,
7200,
)
}
fn test_tools() -> Arc<crate::tools::Tools> {
Arc::new(
crate::tools::ToolsBuilder::new()
.token(test_token_manager())
.build()
.expect("测试 Tools 应构建成功"),
)
}
fn optional_auth_app(tools: Arc<crate::tools::Tools>) -> BuiltApp {
let module = ModuleSpec::new(
ModuleName::new("account.optional_auth").expect("测试 Module 名称应有效"),
)
.middleware(
TokenAuthMiddleware::new(|claims| User::new(7, claims.sub.clone()))
.authenticate_public_actions(),
)
.action(
ActionSpec::new(
ActionName::new("public_probe").expect("测试 Action 名称应有效"),
RouteSpec::new(
HttpMethod::Get,
"/api/v1/optional-auth/public",
"account.optional_auth.public_probe",
),
)
.public(true),
PublicProbe,
)
.action(
ActionSpec::new(
ActionName::new("protected_probe").expect("测试 Action 名称应有效"),
RouteSpec::new(
HttpMethod::Get,
"/api/v1/optional-auth/protected",
"account.optional_auth.protected_probe",
),
),
ProtectedProbe,
)
.native_action(UiCatalogAction);
AppBuilder::new()
.addon(
AddonSpec::new(AddonName::new("account").expect("测试 Addon 名称应有效"))
.module(module),
)
.build(tools)
.expect("可选认证测试应用应构建成功")
}
fn optional_auth_ref(name: &str) -> ActionRef {
ActionRef::new(
ModuleName::new("account.optional_auth").expect("测试 Module 名称应有效"),
ActionName::new(name).expect("测试 Action 名称应有效"),
)
}
fn test_access_token(app: &BuiltApp) -> String {
app.tools()
.token()
.expect("测试应用应配置 TokenManager")
.generate_access_token("user-7", serde_json::json!({}))
.expect("测试 Access Token 应生成成功")
}
fn response_authenticated(response: ApiResponse) -> bool {
response
.data
.and_then(|data| {
data.get("authenticated")
.and_then(serde_json::Value::as_bool)
})
.expect("探针响应应包含 authenticated 布尔值")
}
fn catalog_operation_ids(response: ApiResponse) -> Vec<String> {
response
.data
.and_then(|data| data.get("actions").cloned())
.and_then(|actions| actions.as_array().cloned())
.expect("UI 目录响应应包含 actions 数组")
.into_iter()
.map(|action| {
action
.get("operation_id")
.and_then(serde_json::Value::as_str)
.expect("UI 目录 Action 应包含 operation_id")
.to_string()
})
.collect()
}
#[test]
fn test_auth_actions_meta() {
let login = LoginAction::new(DummyVerifier);
assert_eq!(login.name(), "login");
assert!(DynAction::meta(&login).is_public);
let refresh = RefreshAction::<DefaultRefreshClaims>::default();
assert_eq!(refresh.name(), "refresh");
assert!(refresh.is_public());
let logout = LogoutAction::new();
assert_eq!(logout.name(), "logout");
assert!(logout.is_public());
}
#[test]
fn token_auth_middleware_accepts_fallible_user_projection() {
fn assert_middleware(_: &impl Middleware) {}
let middleware = TokenAuthMiddleware::new(|_claims: &TokenClaims| {
Err::<User, BaseError>(BaseError::Unauthorized("Token subject 无效".to_string()))
});
assert_middleware(&middleware);
assert_eq!(middleware.scope(), MiddlewareScope::ProtectedActions);
}
#[tokio::test]
async fn public_and_protected_actions_share_auth_enabled_module() {
let calls = Arc::new(AtomicUsize::new(0));
let module_name = ModuleName::new("account.user").expect("测试 Module 名称应有效");
let login_ref = ActionRef::new(
module_name.clone(),
ActionName::new("login").expect("测试 Action 名称应有效"),
);
let probe_ref = ActionRef::new(
module_name.clone(),
ActionName::new("protected_probe").expect("测试 Action 名称应有效"),
);
let module = ModuleSpec::new(module_name)
.middleware(CountingMiddleware(Arc::clone(&calls)))
.middleware(TokenAuthMiddleware::new(|claims| {
User::new(1, claims.sub.clone())
}))
.action(
ActionSpec::new(
ActionName::new("login").expect("测试 Action 名称应有效"),
RouteSpec::new(
HttpMethod::Post,
"/api/v1/users/login",
"account.user.login",
),
)
.public(true),
LoginAction::new(DummyVerifier),
)
.action(
ActionSpec::new(
ActionName::new("protected_probe").expect("测试 Action 名称应有效"),
RouteSpec::new(
HttpMethod::Get,
"/api/v1/users/me",
"account.user.protected_probe",
),
),
ProtectedProbe,
);
let app = AppBuilder::new()
.addon(
AddonSpec::new(AddonName::new("account").expect("测试 Addon 名称应有效"))
.module(module),
)
.build(test_tools())
.expect("同一模块应能注册公开与受保护 Action");
let login_handle = app.registry().resolve(&login_ref).expect("login 应已注册");
let probe_handle = app
.registry()
.resolve(&probe_ref)
.expect("protected_probe 应已注册");
let public_request = crate::action::Request::new(serde_json::json!({
"username": "alice",
"password": "correct-password"
}));
let public_response = app.dispatch(login_handle, public_request).await;
assert!(
public_response.is_ok(),
"公开 Action 不应被 TokenAuthMiddleware 拦截: {public_response:?}"
);
let protected_response = app
.dispatch(
probe_handle,
crate::action::Request::new(serde_json::json!({})),
)
.await;
assert!(matches!(
protected_response,
Err(BaseError::Unauthorized(message))
if message.contains("Authorization Bearer Token")
));
assert_eq!(
calls.load(Ordering::SeqCst),
2,
"通用中间件应覆盖公开与受保护 Action"
);
}
#[tokio::test]
async fn optional_public_auth_distinguishes_absent_valid_and_invalid_credentials() {
let app = optional_auth_app(test_tools());
let public_handle = app
.registry()
.resolve(&optional_auth_ref("public_probe"))
.expect("公开探针应已注册");
let anonymous = app
.dispatch(
public_handle,
crate::action::Request::new(serde_json::json!({})),
)
.await
.expect("缺少 Authorization header 时公开 Action 应按匿名继续");
assert!(!response_authenticated(anonymous));
let invalid = app
.dispatch(
public_handle,
crate::action::Request::new(serde_json::json!({}))
.header("Authorization", "Bearer invalid-token"),
)
.await;
assert!(matches!(invalid, Err(BaseError::TokenVerifyFailed(_))));
let wrong_scheme = app
.dispatch(
public_handle,
crate::action::Request::new(serde_json::json!({}))
.header("Authorization", "Basic credentials"),
)
.await;
assert!(matches!(
wrong_scheme,
Err(BaseError::Unauthorized(message))
if message.contains("Authorization Bearer Token")
));
}
#[tokio::test]
async fn optional_public_auth_projects_catalog_without_weakening_protected_actions() {
let app = optional_auth_app(test_tools());
let catalog_handle = app
.registry()
.resolve(&optional_auth_ref("ui_catalog"))
.expect("UI 目录应已注册");
let protected_handle = app
.registry()
.resolve(&optional_auth_ref("protected_probe"))
.expect("受保护探针应已注册");
let anonymous_catalog = app
.dispatch(
catalog_handle,
crate::action::Request::new(serde_json::json!({})),
)
.await
.expect("匿名用户应能读取公开目录");
let anonymous_ids = catalog_operation_ids(anonymous_catalog);
assert!(anonymous_ids.contains(&"account.optional_auth.public_probe".to_string()));
assert!(!anonymous_ids.contains(&"account.optional_auth.protected_probe".to_string()));
let protected_without_token = app
.dispatch(
protected_handle,
crate::action::Request::new(serde_json::json!({})),
)
.await;
assert!(matches!(
protected_without_token,
Err(BaseError::Unauthorized(message))
if message.contains("Authorization Bearer Token")
));
}
#[tokio::test]
async fn optional_public_auth_without_revocation_store_fails_closed() {
let app = optional_auth_app(test_tools());
let token = test_access_token(&app);
let public_handle = app
.registry()
.resolve(&optional_auth_ref("public_probe"))
.expect("公开探针应已注册");
let result = app
.dispatch(
public_handle,
crate::action::Request::new(serde_json::json!({}))
.header("Authorization", format!("Bearer {token}")),
)
.await;
assert!(
matches!(result, Err(BaseError::RedisNotInitialized)),
"无撤销存储时不得降级放行: {result:?}"
);
}
#[tokio::test]
#[ignore = "需要 Docker 启动 Redis 撤销存储(无存储时 fail-closed,见 optional_public_auth_without_revocation_store_fails_closed)"]
async fn optional_public_auth_injects_valid_identity_into_catalog_projection() {
let redis_image = GenericImage::new("redis", "7-alpine").with_wait_for(
testcontainers::core::WaitFor::message_on_stdout("Ready to accept connections"),
);
let redis_container = redis_image.start().await.expect("Redis 测试容器应启动成功");
let redis_port = redis_container
.get_host_port_ipv4(6379)
.await
.expect("Redis 测试端口应可获取");
let redis_url = format!("redis://127.0.0.1:{redis_port}");
let cache = RedisClient::connect_with_config(&redis_url, RedisConfig::default())
.await
.expect("Redis 测试客户端应连接成功");
let tools = Arc::new(
crate::tools::ToolsBuilder::new()
.cache(cache)
.token(test_token_manager())
.build()
.expect("带撤销存储的测试 Tools 应构建成功"),
);
let app = optional_auth_app(tools);
let token = test_access_token(&app);
let public_handle = app
.registry()
.resolve(&optional_auth_ref("public_probe"))
.expect("公开探针应已注册");
let authenticated = app
.dispatch(
public_handle,
crate::action::Request::new(serde_json::json!({}))
.header("Authorization", format!("Bearer {token}")),
)
.await
.expect("合法 Access Token 应在公开 Action 注入用户");
assert!(response_authenticated(authenticated));
let catalog_handle = app
.registry()
.resolve(&optional_auth_ref("ui_catalog"))
.expect("UI 目录应已注册");
let authenticated_catalog = app
.dispatch(
catalog_handle,
crate::action::Request::new(serde_json::json!({}))
.header("Authorization", format!("Bearer {token}")),
)
.await
.expect("认证用户应能读取按身份投影的目录");
let authenticated_ids = catalog_operation_ids(authenticated_catalog);
assert!(authenticated_ids.contains(&"account.optional_auth.protected_probe".to_string()));
}
#[test]
fn test_token_fingerprint_stable_and_opaque() {
let a = token_fingerprint("super-secret-access-token");
let b = token_fingerprint("super-secret-access-token");
let c = token_fingerprint("another-token");
assert_eq!(a, b, "同一 token 指纹应稳定");
assert_ne!(a, c, "不同 token 指纹应不同");
assert_eq!(a.len(), 16, "指纹为 16 位十六进制");
assert!(!a.contains("secret"), "指纹不得含原文");
}
#[tokio::test]
async fn test_audit_hook_records_without_leaking() {
use std::sync::{Arc, Mutex};
#[derive(Clone, Default)]
struct RecordingHook {
events: Arc<Mutex<Vec<AuthAuditEvent>>>,
}
#[async_trait]
impl AuthAuditHook for RecordingHook {
async fn on_success(&self, event: AuthAuditEvent) {
self.events.lock().unwrap().push(event);
}
async fn on_failure(&self, event: AuthAuditEvent) {
self.events.lock().unwrap().push(event);
}
}
let hook = RecordingHook::default();
let login = LoginAction::with_audit(DummyVerifier, hook.clone());
assert_eq!(login.name(), "login");
hook.on_success(AuthAuditEvent {
request_id: "abc".into(),
action: "login",
subject: Some("user:alice".into()),
error_code: None,
})
.await;
let events = hook.events.lock().unwrap();
assert_eq!(events.len(), 1);
assert_eq!(events[0].action, "login");
assert_eq!(events[0].subject.as_deref(), Some("user:alice"));
}
}