Skip to main content

yang_base/router/
middleware.rs

1//! Router 中间件 / 拦截器机制(H-5)
2//!
3//! `Registry::dispatch` 使用本模块的洋葱模型组合日志、限流、请求追踪与认证。
4//! 每个中间件拿到 [`ActionContext`] 与代表"调用链剩余部分"的
5//! [`Next`],可在调用 `next.run(ctx)` 前后插入逻辑,也可短路直接返回。
6//!
7//! # 注意:ActionContext 不是 Clone
8//!
9//! [`ActionContext`] 持有数据库句柄等不可克隆资源,因此中间件链以**移动**方式
10//! 传递 ctx——`handle` 接收 `ctx` 的所有权,并在调用 `next.run(ctx)` 时把它交给
11//! 链路的下一环。这保证全链路只有一份上下文。
12//!
13//! # 示例
14//!
15//! ```rust,ignore
16//! use yang_base::router::{Middleware, Next};
17//! use yang_base::action::{ActionContext, ApiResponse};
18//! use yang_base::error::BaseError;
19//! use async_trait::async_trait;
20//!
21//! struct LoggingMiddleware;
22//!
23//! #[async_trait]
24//! impl Middleware for LoggingMiddleware {
25//!     async fn handle(&self, ctx: ActionContext, next: Next<'_>)
26//!         -> Result<ApiResponse, BaseError>
27//!     {
28//!         log::info!("进入 Action");
29//!         let result = next.run(ctx).await;
30//!         log::info!("离开 Action");
31//!         result
32//!     }
33//! }
34//!
35//! // 通过 ModuleSpec::middleware 按顺序注册 LoggingMiddleware。
36//! ```
37
38use crate::action::{ActionContext, ApiResponse, DynAction, PermissionMode};
39use crate::definition::ActionRef;
40use crate::error::BaseError;
41use async_trait::async_trait;
42use std::sync::Arc;
43
44/// 构建期冻结的 Action 授权策略。
45#[derive(Debug, Clone)]
46pub(crate) struct AuthorizationPolicy {
47    pub(crate) is_public: bool,
48    groups: Arc<[PermissionGroup]>,
49}
50
51impl AuthorizationPolicy {
52    pub(crate) fn new(is_public: bool, groups: impl Into<Arc<[PermissionGroup]>>) -> Self {
53        Self {
54            is_public,
55            groups: groups.into(),
56        }
57    }
58
59    pub(crate) fn authorize(&self, context: &ActionContext) -> Result<(), BaseError> {
60        if self.is_public {
61            return Ok(());
62        }
63        let user = context
64            .authenticated_user()
65            .ok_or_else(|| BaseError::Unauthorized("需要登录".to_string()))?;
66        for group in self.groups.iter() {
67            if !permissions_match(user, &group.permissions, group.mode) {
68                return Err(BaseError::PermissionDenied(format!(
69                    "缺少 {} 权限: {:?}",
70                    group.label, group.permissions
71                )));
72            }
73        }
74        Ok(())
75    }
76
77    pub(crate) fn allows(&self, context: &ActionContext) -> bool {
78        self.authorize(context).is_ok()
79    }
80}
81
82#[derive(Debug, Clone)]
83pub(crate) struct PermissionGroup {
84    label: &'static str,
85    permissions: Arc<[String]>,
86    mode: PermissionMode,
87}
88
89impl PermissionGroup {
90    pub(crate) fn new(
91        label: &'static str,
92        permissions: impl Into<Arc<[String]>>,
93        mode: PermissionMode,
94    ) -> Self {
95        Self {
96            label,
97            permissions: permissions.into(),
98            mode,
99        }
100    }
101}
102
103/// 中间件适用的 Action 范围。
104///
105/// 通用中间件使用默认的 [`AllActions`](Self::AllActions),因此日志、限流、
106/// 请求追踪等横切逻辑会覆盖公开与受保护 Action。强制认证中间件应返回
107/// [`ProtectedActions`](Self::ProtectedActions),公开 Action 会跳过它,而受保护
108/// Action 仍按原有洋葱链顺序执行。
109#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
110pub enum MiddlewareScope {
111    /// 对公开与受保护 Action 都生效。
112    #[default]
113    AllActions,
114    /// 只对需要认证的受保护 Action 生效。
115    ProtectedActions,
116}
117
118/// 框架内置中间件的依赖角色。
119///
120/// 该角色只用于构建期检查已知的安全依赖,不会重排洋葱链,也不会对自定义
121/// 中间件臆测顺序。未声明角色的中间件保持原有注册语义。
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub enum MiddlewareRole {
124    /// 没有框架可推断的安全顺序依赖。
125    Unspecified,
126    /// 向 [`ActionContext`](crate::action::ActionContext) 注入可信身份。
127    Authentication,
128    /// 依赖可信身份解析租户上下文。
129    TenantResolution,
130    /// 依赖可信身份执行敏感操作重认证。
131    StepUpProtection,
132}
133
134/// 中间件 trait。
135///
136/// 实现者在 `handle` 中拦截一次 Action 派发:可在调用 `next.run(ctx)` 前后
137/// 注入逻辑,或不调用 `next` 直接短路返回。
138#[async_trait]
139pub trait Middleware: Send + Sync + 'static {
140    /// 返回构建期可验证的安全依赖角色。
141    fn role(&self) -> MiddlewareRole {
142        MiddlewareRole::Unspecified
143    }
144
145    /// 返回只应执行此中间件的确定 Action。
146    ///
147    /// 默认 `None` 表示不限定 Action。返回目标时,App 构建期会验证引用存在且属于
148    /// 当前注册模块,派发期再以 Registry 注入的可信目标进行匹配。
149    fn target_action(&self) -> Option<&ActionRef> {
150        None
151    }
152
153    /// 返回此中间件适用的 Action 范围。
154    ///
155    /// 默认覆盖全部 Action,以保持日志、限流、追踪和其他通用中间件的直观语义。
156    /// 强制认证中间件应显式返回 [`MiddlewareScope::ProtectedActions`]。
157    fn scope(&self) -> MiddlewareScope {
158        MiddlewareScope::AllActions
159    }
160
161    /// 处理一次派发。
162    ///
163    /// # 参数
164    ///
165    /// - `ctx`: 动作上下文(所有权转移,需在调用 `next.run` 时传递下去)
166    /// - `next`: 调用链的剩余部分
167    async fn handle(&self, ctx: ActionContext, next: Next<'_>) -> Result<ApiResponse, BaseError>;
168}
169
170/// 调用链中"剩余部分"的句柄。
171///
172/// 持有尚未执行的中间件切片、构建期授权策略以及链尾的目标 [`DynAction`]。
173/// 中间件链是**最外层**:当中间件耗尽时,链尾执行「授权 + Action 派发」。
174/// [`MiddlewareScope::AllActions`] 中间件可以观察并干预所有请求;
175/// [`MiddlewareScope::ProtectedActions`] 中间件则会在公开 Action 上被跳过。
176pub struct Next<'a> {
177    /// 尚未执行的中间件
178    pub(crate) remaining: &'a [Arc<dyn Middleware>],
179    /// 链尾要执行的目标 Action
180    pub(crate) action: Arc<dyn DynAction>,
181    /// 构建期冻结的授权策略。
182    pub(crate) policy: &'a AuthorizationPolicy,
183}
184
185impl<'a> Next<'a> {
186    /// 推进调用链。
187    ///
188    /// 依次跳过不适用于目标 Action 的中间件;遇到第一个适用中间件时执行它,
189    /// 并把其余部分包装成新的 `Next` 传入。全部耗尽后执行链尾的
190    /// 「内置鉴权 + Action 派发」。
191    ///
192    /// # 参数
193    ///
194    /// - `ctx`: 动作上下文(所有权转移)
195    pub async fn run(self, ctx: ActionContext) -> Result<ApiResponse, BaseError> {
196        let mut remaining = self.remaining;
197
198        while let Some((current, rest)) = remaining.split_first() {
199            remaining = rest;
200            let action_applies = match current.target_action() {
201                None => true,
202                Some(target) => ctx.dispatch_target().is_some_and(|(module, action)| {
203                    module == target.module().as_str() && action == target.action().as_str()
204                }),
205            };
206            let scope_applies = match current.scope() {
207                MiddlewareScope::AllActions => true,
208                MiddlewareScope::ProtectedActions => !self.policy.is_public,
209            };
210            if action_applies && scope_applies {
211                let next = Next {
212                    remaining: rest,
213                    action: self.action,
214                    policy: self.policy,
215                };
216                return current.handle(ctx, next).await;
217            }
218        }
219
220        authorize_and_dispatch(self.action, self.policy, ctx).await
221    }
222}
223
224async fn authorize_and_dispatch(
225    action: Arc<dyn DynAction>,
226    policy: &AuthorizationPolicy,
227    context: ActionContext,
228) -> Result<ApiResponse, BaseError> {
229    let span = tracing::info_span!(
230        "authorize",
231        is_public = policy.is_public,
232        granted = tracing::field::Empty,
233    );
234    let _enter = span.enter();
235
236    authorize(policy, &context).inspect_err(|_| {
237        span.record("granted", false);
238    })?;
239
240    span.record("granted", true);
241    drop(_enter);
242    action.dispatch(context).await
243}
244
245pub(crate) fn authorize(
246    policy: &AuthorizationPolicy,
247    context: &ActionContext,
248) -> Result<(), BaseError> {
249    policy.authorize(context)
250}
251
252fn permissions_match(
253    user: &crate::action::User,
254    permissions: &[String],
255    mode: PermissionMode,
256) -> bool {
257    if permissions.is_empty() {
258        return true;
259    }
260    match mode {
261        PermissionMode::All => permissions
262            .iter()
263            .all(|permission| user.has_permission(permission)),
264        PermissionMode::Any => permissions
265            .iter()
266            .any(|permission| user.has_permission(permission)),
267    }
268}
269
270/// request_id 透传中间件(可观测性 C4)。
271///
272/// 作洋葱链**最外层**:若请求头含 `X-Request-Id` 则解析透传(解析失败回退为
273/// `ActionContext` 已生成的标识),否则沿用默认生成值;随后写入根 span 的
274/// `request_id` 字段以串联日志/metrics/审计。
275///
276/// 注:`ActionContext::new` 默认已生成一个 request_id,本中间件只负责「上游透传」
277/// 这一增量语义,不破坏无中间件时的可观测性。
278///
279/// # 示例
280///
281/// ```rust,ignore
282/// use yang_base::definition::{ModuleName, ModuleSpec};
283/// use yang_base::router::RequestIdMiddleware;
284///
285/// let module = ModuleSpec::new(ModuleName::new("account.user")?)
286///     .middleware(RequestIdMiddleware);
287/// ```
288pub struct RequestIdMiddleware;
289
290#[async_trait]
291impl Middleware for RequestIdMiddleware {
292    async fn handle(
293        &self,
294        mut ctx: ActionContext,
295        next: Next<'_>,
296    ) -> Result<ApiResponse, BaseError> {
297        // 上游 X-Request-Id 优先:存在且可解析则透传,否则保留默认生成值
298        if let Some(raw) = ctx
299            .request
300            .headers
301            .get("X-Request-Id")
302            .or_else(|| ctx.request.headers.get("x-request-id"))
303        {
304            if let Some(rid) = crate::action::RequestId::parse_hex(raw) {
305                ctx = ctx.with_request_id(rid);
306            }
307        }
308        // 写入当前 span(dispatch 根 span 已声明 request_id 字段)
309        tracing::Span::current().record("request_id", tracing::field::display(ctx.request_id));
310        next.run(ctx).await
311    }
312}