Skip to main content

yang_base/action/auth/
middleware.rs

1//! Token 鉴权中间件与应用级声明校验钩子。
2
3use crate::action::{ActionContext, ApiResponse, User};
4use crate::error::BaseError;
5use crate::router::middleware::{Middleware, MiddlewareRole, MiddlewareScope, Next};
6use crate::token::TokenClaims;
7use async_trait::async_trait;
8
9// ──────────────────────────────────────────────────────────────────────────────
10// TokenAuthMiddleware
11// ──────────────────────────────────────────────────────────────────────────────
12
13/// Token 鉴权中间件:在 Action 派发前完成 JWT 三重校验并注入当前用户。
14///
15/// 挂到 [`ModuleSpec`](crate::definition::ModuleSpec) 后,只对非公开 Action 执行;
16/// 标记为 `public` 的 Action 会绕过本认证中间件,但仍会经过日志、限流、追踪等
17/// 通用中间件。对受保护 Action:
18///
19/// 1. 从 [`Request::token`](crate::action::Request::token) 取 `Authorization: Bearer <token>`;
20///    缺失则短路返回 [`BaseError::Unauthorized`]。
21/// 2. 调用 [`TokenManager::verify_token_checked`](crate::token::TokenManager::verify_token_checked)
22///    完成 **签名 + 过期 + 黑名单** 三重校验;失败短路(`TokenVerifyFailed` /
23///    `TokenExpired` / `TokenRevoked` 等原样上抛)。
24/// 3. 用注入的 `claims -> User` 闭包,从已验证的 [`TokenClaims`] 构造
25///    [`User`] 并填入 `ActionContext.user`,随后 `next.run(ctx)`。
26///
27/// 用户如何从声明映射(角色/权限放在哪个自定义字段)因项目而异,故由闭包 `F` 注入。
28///
29/// # 示例
30///
31/// ```rust,ignore
32/// use yang_base::action::{TokenAuthMiddleware, User};
33/// use yang_base::definition::{ModuleName, ModuleSpec};
34///
35/// // 从 JWT sub 取用户 ID;业务标识解析失败时必须拒绝认证
36/// let auth = TokenAuthMiddleware::new(|claims| {
37///     let id = claims.sub.parse::<i64>()
38///         .map_err(|_| yang_base::BaseError::Unauthorized("Token subject 无效".into()))?;
39///     Ok(User::new(id, claims.sub.clone()))
40/// });
41///
42/// let module = ModuleSpec::new(ModuleName::new("account.user")?).middleware(auth);
43/// ```
44pub struct TokenAuthMiddleware<F, V = NoopTokenClaimsValidator> {
45    /// 从已验证声明构造业务 [`User`](crate::action::User) 的闭包
46    build_user: F,
47    /// 签名与 Token 类型通过后的应用级异步声明校验器。
48    claims_validator: V,
49    /// 是否在公开 Action 上执行可选认证。
50    authenticate_public_actions: bool,
51}
52
53/// 已验签 Access Token 的应用级校验钩子。
54///
55/// 基础库保持 JWT、黑名单和类型校验的唯一认证链;业务系统可在用户投影前校验
56/// 授权版本、会话世代等应用事实,而无需重复解析或验签 Token。
57#[async_trait]
58pub trait TokenClaimsValidator: Send + Sync + 'static {
59    /// 校验已通过核心 Token 验证的声明;返回错误会在用户投影前短路认证。
60    async fn validate(
61        &self,
62        context: &ActionContext,
63        claims: &TokenClaims,
64    ) -> Result<(), BaseError>;
65}
66
67/// 不增加额外 I/O 的默认声明校验器。
68#[derive(Debug, Clone, Copy, Default)]
69pub struct NoopTokenClaimsValidator;
70
71#[async_trait]
72impl TokenClaimsValidator for NoopTokenClaimsValidator {
73    async fn validate(
74        &self,
75        _context: &ActionContext,
76        _claims: &TokenClaims,
77    ) -> Result<(), BaseError> {
78        Ok(())
79    }
80}
81
82/// 将不可失败的旧式用户投影和可失败的安全投影统一成认证结果。
83///
84/// 该适配 trait 公开仅用于满足 [`TokenAuthMiddleware`] 的泛型边界;业务代码通常
85/// 只需让闭包返回 [`User`] 或 `Result<User, BaseError>`。
86#[doc(hidden)]
87pub trait IntoUserProjection {
88    fn into_user_projection(self) -> Result<User, BaseError>;
89}
90
91impl IntoUserProjection for User {
92    fn into_user_projection(self) -> Result<User, BaseError> {
93        Ok(self)
94    }
95}
96
97impl IntoUserProjection for Result<User, BaseError> {
98    fn into_user_projection(self) -> Result<User, BaseError> {
99        self
100    }
101}
102
103impl<F, R> TokenAuthMiddleware<F, NoopTokenClaimsValidator>
104where
105    F: Fn(&TokenClaims) -> R + Send + Sync + 'static,
106    R: IntoUserProjection,
107{
108    /// 用「声明 -> 用户」闭包创建 Token 鉴权中间件。
109    ///
110    /// 闭包可返回 `User` 保持简单场景兼容,也可返回 `Result<User, BaseError>`,在
111    /// subject、角色或权限声明格式非法时 fail-closed。
112    pub fn new(build_user: F) -> Self {
113        Self {
114            build_user,
115            claims_validator: NoopTokenClaimsValidator,
116            authenticate_public_actions: false,
117        }
118    }
119}
120
121impl<F, V> TokenAuthMiddleware<F, V> {
122    /// 注入应用级异步声明校验器,并保留同一条 Token 认证链。
123    pub fn with_claims_validator<N>(self, claims_validator: N) -> TokenAuthMiddleware<F, N>
124    where
125        N: TokenClaimsValidator,
126    {
127        TokenAuthMiddleware {
128            build_user: self.build_user,
129            claims_validator,
130            authenticate_public_actions: self.authenticate_public_actions,
131        }
132    }
133
134    /// 在公开 Action 上启用可选认证。
135    ///
136    /// 默认情况下,本中间件只处理受保护 Action,以确保登录、刷新等公开端点不会
137    /// 因缺少 Token 被拦截。启用本选项后,公开 Action 在没有 Authorization header
138    /// 时仍按匿名请求继续;携带 Bearer Token 时则完成完整校验并注入用户。该模式
139    /// 适用于请求级 UI 目录等“匿名可用、登录后按身份投影”的公开端点。
140    ///
141    /// 非 Bearer Authorization header、无效 Token 和错误 Token 类型不会降级为匿名。
142    pub fn authenticate_public_actions(mut self) -> Self {
143        self.authenticate_public_actions = true;
144        self
145    }
146}
147
148#[async_trait]
149impl<F, R, V> Middleware for TokenAuthMiddleware<F, V>
150where
151    F: Fn(&TokenClaims) -> R + Send + Sync + 'static,
152    R: IntoUserProjection + Send + Sync + 'static,
153    V: TokenClaimsValidator,
154{
155    fn role(&self) -> MiddlewareRole {
156        MiddlewareRole::Authentication
157    }
158
159    fn scope(&self) -> MiddlewareScope {
160        if self.authenticate_public_actions {
161            MiddlewareScope::AllActions
162        } else {
163            MiddlewareScope::ProtectedActions
164        }
165    }
166
167    async fn handle(
168        &self,
169        mut ctx: ActionContext,
170        next: Next<'_>,
171    ) -> Result<ApiResponse, BaseError> {
172        // 1. 取 Bearer Token(owned,及早结束对 ctx 的借用)
173        let token = match ctx.request.token() {
174            Some(t) => t.to_string(),
175            None if self.authenticate_public_actions
176                && next.policy.is_public
177                && ctx.request.get_header("authorization").is_none() =>
178            {
179                return next.run(ctx).await;
180            }
181            None => {
182                return Err(BaseError::Unauthorized(
183                    "缺少 Authorization Bearer Token".to_string(),
184                ))
185            }
186        };
187
188        // 2. 签名 + 过期 + 黑名单三重校验(失败原样短路)
189        let claims = ctx.tools().token()?.verify_token_checked(&token).await?;
190
191        // 3. 校验 token_type 必须为 Access
192        if claims.token_type != crate::token::TokenType::Access {
193            return Err(BaseError::TokenTypeInvalid("期望 access token".into()));
194        }
195
196        // 4. 应用级事实校验仍位于唯一认证链内,不重复解析或验签 Token
197        self.claims_validator.validate(&ctx, &claims).await?;
198
199        // 5. 注入当前用户后继续调用链
200        ctx.user = Some((self.build_user)(&claims).into_user_projection()?);
201        if let Some(user) = &ctx.user {
202            tracing::Span::current().record("actor_id", user.id);
203        }
204        next.run(ctx).await
205    }
206}