wordval-web 1.0.13

Wordval web layer: router, middleware, extractors, responses, session-based authentication
Documentation
//! Wordval 请求中间件模块
//!
//! 按职责拆分为多个子模块:
//! | 模块               | 功能                 |
//! |-------------------|---------------------|
//! | [client_identity] | 可信客户端 IP 解析(ClientIp)与请求入口打点(RequestStart) |
//! | [request_id]      | 请求 ID 生成/注入     |
//! | [auth]            | Bearer Token 会话认证 |
//! | [role]            | 角色校验              |
//! | [permission_check]| 路径权限规则校验       |
//! | [audit]           | 白名单路由的操作审计记录(含被拒绝访问) |
//! | [request_log]     | 请求访问日志(tracing 输出) |
//! | [rate_limit]      | IP 滑动窗口限流       |
//! | [security_headers]| 安全响应头注入         |
//! | `nonce`           | Nonce 防重放(按需)    |
//!
//! 幂等执行(`#[idempotent]` 宏)是宏展开支撑而非 tower 层,位于顶层 `crate::idempotency`(需启用 `cache` feature)。

pub mod audit;
pub mod auth;
pub mod client_identity;
#[cfg(feature = "cache")]
pub mod nonce;
pub mod permission_check;
pub mod rate_limit;
pub mod request_id;
pub mod request_log;
pub mod role;
pub mod security_headers;

#[cfg(feature = "cache")]
pub use auth::{session_resolver, SessionResolverState};
pub use audit::{AuditLayer, AuditRule, AuditService};
pub use auth::{AuthLayer, AuthService};
pub use client_identity::{ClientIdentityLayer, ClientIdentityService, ClientIp, RequestStart};
// 向后兼容:幂等支撑已移至顶层 crate::idempotency
#[cfg(feature = "cache")]
pub use crate::idempotency::idempotent_run;
#[cfg(feature = "cache")]
pub use nonce::{nonce, NonceState};
pub use permission_check::{PermissionCheckLayer, PermissionCheckService, PermissionRule};
pub use rate_limit::{IpWindow, RateLimitLayer, RateLimitService};
pub use request_id::{RequestIdLayer, RequestIdService};
pub use request_log::{RequestLogLayer, RequestLogService};
pub use role::{RequireRoleLayer, RequireRoleService};
pub use security_headers::{SecurityHeadersLayer, SecurityHeadersService};

use axum::response::{IntoResponse, Response};
use serde::{Deserialize, Serialize};
use wordval_core::api::ApiError;

use crate::middleware::auth::PathPattern;

/// 规则匹配的最小接口:路径模式 + 方法集合 + 来源标记 + 具体程度。
///
/// 权限规则与审计规则共用同一套"守卫优先 + 最具体规则优先"的选择策略
/// ([`best_rule`]/[`rule_specificity`]),避免两处各写一遍而产生语义漂移。
pub(crate) trait RuleKey {
    fn pattern(&self) -> &PathPattern;
    fn methods(&self) -> &[String];
    fn is_guard(&self) -> bool;
    fn specificity(&self) -> (usize, usize);
}

/// 路径具体程度(段数, 静态段数);静态段越多越具体
pub(crate) fn rule_specificity(path: &str) -> (usize, usize) {
    let mut segments = 0usize;
    let mut statics = 0usize;
    for s in path.split('/').filter(|s| !s.is_empty()) {
        segments += 1;
        if !(s.starts_with('{') && s.ends_with('}')) && s != "*" {
            statics += 1;
        }
    }
    (segments, statics)
}

/// 单次遍历选出最优规则:守卫规则优先;同源内取最具体;同具体程度取先注册者。
///
/// `path` 必须为已 normalize 的路径。
pub(crate) fn best_rule<'a, T: RuleKey>(rules: &'a [T], path: &str, method: &str) -> Option<&'a T> {
    let best = best_rule_for_method(rules, path, method);
    if !method.eq_ignore_ascii_case("HEAD") {
        return best;
    }
    if best.is_some_and(|r| r.is_guard()) {
        return best;
    }
    let get = best_rule_for_method(rules, path, "GET");
    match (best, get) {
        (_, Some(get)) if get.is_guard() => Some(get),
        (Some(best), _) => Some(best),
        (None, get) => get,
    }
}

fn best_rule_for_method<'a, T: RuleKey>(
    rules: &'a [T],
    path: &str,
    method: &str,
) -> Option<&'a T> {
    let mut best: Option<&T> = None;
    for r in rules {
        if !r.pattern().matches_normalized(path) {
            continue;
        }
        if !r.methods().is_empty() && !r.methods().iter().any(|m| m.eq_ignore_ascii_case(method)) {
            continue;
        }
        best = Some(match best {
            None => r,
            Some(b) => match (r.is_guard(), b.is_guard()) {
                // 守卫规则存在时配置规则不得遮蔽路由自身声明的策略
                (true, false) => r,
                (false, true) => b,
                // 同来源取更具体者;同具体程度保持先注册者(不替换)
                _ => {
                    if r.specificity() > b.specificity() {
                        r
                    } else {
                        b
                    }
                }
            },
        });
    }
    best
}

/// 中间件短路时统一生成错误响应:复用 [`ApiError`] 的 `IntoResponse`
///(`Res` schema + 注册表错误码),保证与业务错误响应完全同构。
pub(crate) fn error_response(err: ApiError) -> Response {
    err.into_response()
}

/// 会话数据 —— 登录时写入缓存,认证中间件从缓存读取注入 extensions
///
/// 同时也是请求处理器的 `CurrentUser` 提取器类型,使用时只需 `user: CurrentUser`。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CurrentUser {
    pub id: i64,
    pub username: String,
    pub roles: Vec<String>,
    pub permissions: Vec<String>,
    /// 是否为平台管理员(user_type == '00')
    #[serde(default)]
    pub is_admin: bool,
    /// 已绑定的租户 ID(管理员为 None)
    #[serde(default)]
    pub tenant_id: Option<i64>,
    /// 当前店铺 ID(按需设置)
    #[serde(default)]
    pub store_id: Option<i64>,
}

impl CurrentUser {
    pub fn has_role(&self, role: &str) -> bool {
        self.roles.iter().any(|r| r == role)
    }

    pub fn has_perm(&self, perm: &str) -> bool {
        self.permissions.iter().any(|p| p == perm)
    }

    pub fn is_admin_user(&self) -> bool {
        self.is_admin || self.permissions.iter().any(|p| p == "*" || p == "*:*:*")
    }

    /// 统一授权入口:管理员 / 通配权限 / 精确权限任一满足即授权。
    ///
    /// 权限中间件、路径权限规则与提取器都必须调用同一判断入口,
    /// 避免管理员或通配权限用户因 exact-match 被误拒。
    pub fn is_authorized(&self, permission: &str) -> bool {
        self.is_admin_user() || self.has_perm(permission)
    }
}

/// 创建会话:生成 UUID token,CurrentUser 写入缓存,返回 token
#[cfg(feature = "cache")]
#[allow(clippy::too_many_arguments)]
pub async fn create_session(
    cache: &wordval_cache::SharedCache,
    user_id: i64,
    username: &str,
    roles: &[String],
    permissions: &[String],
    is_admin: bool,
    tenant_id: Option<i64>,
    store_id: Option<i64>,
    ttl_secs: u64,
) -> Result<String, wordval_core::api::ApiError> {
    use wordval_cache::Cache;
    use wordval_core::api::ApiError;
    let token = wordval_utils::Sid::uuid();
    let session = CurrentUser {
        id: user_id,
        username: username.to_string(),
        roles: roles.to_vec(),
        permissions: permissions.to_vec(),
        is_admin,
        tenant_id,
        store_id,
    };
    cache
        .set_ex(&format!("session:{}", token), &session, ttl_secs)
        .await
        .map_err(|e| ApiError::internal(format!("创建会话失败: {}", e)))?;
    Ok(token)
}

/// 销毁会话(登出)
///
/// 返回 `Result`:缓存删除失败时调用方不得提示"退出成功",
/// 因为 token 在 TTL 内仍然有效。
#[cfg(feature = "cache")]
pub async fn destroy_session(
    cache: &wordval_cache::SharedCache,
    token: &str,
) -> Result<(), wordval_core::api::ApiError> {
    use wordval_cache::Cache;
    use wordval_core::api::ApiError;
    cache
        .del(&format!("session:{}", token))
        .await
        .map_err(|e| ApiError::internal(format!("销毁会话失败: {}", e)))
}

/// 续期会话 TTL(用 CurrentUser 重新 set_ex)
///
/// 会话不存在或缓存读取失败时返回明确错误,不静默吞掉缓存故障。
#[cfg(feature = "cache")]
pub async fn refresh_session(
    cache: &wordval_cache::SharedCache,
    token: &str,
    ttl_secs: u64,
) -> Result<(), wordval_core::api::ApiError> {
    use wordval_cache::Cache;
    use wordval_core::api::ApiError;
    let key = format!("session:{}", token);
    let session = cache
        .get::<CurrentUser>(&key)
        .await
        .map_err(|e| ApiError::internal(format!("续期会话失败: {}", e)))?
        .ok_or_else(|| {
            ApiError::unauthorized(wordval_core::error_registry::error_message_of(
                wordval_core::error_registry::ErrorCode::Unauthorized,
            ))
        })?;
    cache
        .set_ex(&key, &session, ttl_secs)
        .await
        .map_err(|e| ApiError::internal(format!("续期会话失败: {}", e)))
}