yang_base/router/
middleware.rs1use 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#[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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
110pub enum MiddlewareScope {
111 #[default]
113 AllActions,
114 ProtectedActions,
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub enum MiddlewareRole {
124 Unspecified,
126 Authentication,
128 TenantResolution,
130 StepUpProtection,
132}
133
134#[async_trait]
139pub trait Middleware: Send + Sync + 'static {
140 fn role(&self) -> MiddlewareRole {
142 MiddlewareRole::Unspecified
143 }
144
145 fn target_action(&self) -> Option<&ActionRef> {
150 None
151 }
152
153 fn scope(&self) -> MiddlewareScope {
158 MiddlewareScope::AllActions
159 }
160
161 async fn handle(&self, ctx: ActionContext, next: Next<'_>) -> Result<ApiResponse, BaseError>;
168}
169
170pub struct Next<'a> {
177 pub(crate) remaining: &'a [Arc<dyn Middleware>],
179 pub(crate) action: Arc<dyn DynAction>,
181 pub(crate) policy: &'a AuthorizationPolicy,
183}
184
185impl<'a> Next<'a> {
186 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
270pub 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 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 tracing::Span::current().record("request_id", tracing::field::display(ctx.request_id));
310 next.run(ctx).await
311 }
312}