wordval-web 1.0.13

Wordval web layer: router, middleware, extractors, responses, session-based authentication
Documentation
//! 请求提取器:ValidatedJson、CurrentUser、OptionalUser、ClientContext、TenantId、RequestedTenantId、FileSender

use axum::{
    extract::{FromRequest, Json},
    response::{IntoResponse, Response},
};
use serde::de::DeserializeOwned;
use wordval_core::api::ApiError;
use wordval_core::error_registry::{error_message_of, ErrorCode};

/// 带自动校验的 JSON 提取器
#[derive(Debug, Clone, Copy, Default)]
pub struct ValidatedJson<T>(pub T);

impl<T, S> FromRequest<S> for ValidatedJson<T>
where
    T: DeserializeOwned,
    S: Send + Sync,
{
    type Rejection = ValidatedJsonRejection;

    async fn from_request(req: axum::extract::Request, state: &S) -> Result<Self, Self::Rejection> {
        match Json::<T>::from_request(req, state).await {
            Ok(Json(value)) => Ok(ValidatedJson(value)),
            Err(rejection) => {
                let msg = format!("请求体格式错误: {}", rejection.body_text());
                Err(ValidatedJsonRejection(ApiError::bad_request(msg)))
            }
        }
    }
}

impl<T: validator::Validate> ValidatedJson<T> {
    pub fn validate(self) -> Result<Self, ApiError> {
        self.0.validate().map_err(|e| {
            ApiError::unprocessable_entity(wordval_utils::valid::Valid::format_validation_errors(
                &e,
            ))
        })?;
        Ok(self)
    }
}

impl<T> std::ops::Deref for ValidatedJson<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> std::ops::DerefMut for ValidatedJson<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[derive(Debug)]
pub struct ValidatedJsonRejection(pub ApiError);

impl IntoResponse for ValidatedJsonRejection {
    fn into_response(self) -> Response {
        self.0.into_response()
    }
}

impl From<ValidatedJsonRejection> for ApiError {
    fn from(rejection: ValidatedJsonRejection) -> Self {
        rejection.0
    }
}

// ──── CurrentUser extractor ────────────────────────────

pub use crate::middleware::CurrentUser;

use axum::extract::FromRequestParts;
use axum::http::request::Parts;

impl<S: Send + Sync> FromRequestParts<S> for CurrentUser {
    type Rejection = ApiError;
    async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
        parts
            .extensions
            .get::<CurrentUser>()
            .cloned()
            .ok_or_else(|| ApiError::unauthorized(error_message_of(ErrorCode::Unauthorized)))
    }
}

// ──── OptionalUser ────────────────────────────────────

/// 可选用户提取器:有 token 时为 Some(user),游客时为 None
/// 用于支持游客结账等公开接口
#[derive(Debug, Clone)]
pub struct OptionalUser(pub Option<CurrentUser>);

impl OptionalUser {
    /// 获取用户 ID,游客返回 0
    pub fn user_id(&self) -> i64 {
        self.0.as_ref().map(|u| u.id).unwrap_or(0)
    }

    /// 是否为游客(未登录)
    pub fn is_guest(&self) -> bool {
        self.0.is_none()
    }
}

impl<S: Send + Sync> FromRequestParts<S> for OptionalUser {
    type Rejection = ApiError;
    async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
        Ok(OptionalUser(parts.extensions.get::<CurrentUser>().cloned()))
    }
}

// ──── ClientContext ────────────────────────────

/// 客户端上下文提取器:一处声明同时拿到可信 IP、User-Agent、请求入口时刻与请求 ID
///
/// - `ip`:ClientIdentity 中间件解析的可信客户端 IP(与访问日志/限流
///   同一结论;未经该层的手工 Router 上为 `"unknown"`);
/// - `user_agent`:请求头 `User-Agent`(缺失为 `None`);
/// - `started`:请求进入中间件链的时刻(ClientIdentity 层注入的
///   `RequestStart` 打点;层未安装时退化为提取时刻);
/// - `request_id`:请求 ID(RequestId 层注入,复用合法入站 `x-request-id`、
///   否则服务端生成;与访问日志/`x-request-id` 响应头同值,可直接对账;
///   层未启用时为 `None`)。
///
/// 审计场景直接配合 [`crate::audit::AuditRecord::from_ctx`]:User-Agent、
/// 请求入口耗时与请求 ID 自动填进审计记录,业务侧既不用写 `AuditCtx`
/// 也不用自己记 `Instant`:
///
/// ```ignore
/// #[get("/orders")]
/// async fn delete_order(ctx: ClientContext) -> Json<Res<()>> {
///     audit.write(AuditRecord::from_ctx(&ctx, "order.delete", "/api/orders/1", AuditResult::Success));
///     // ...
/// }
/// ```
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ClientContext {
    /// 客户端 IP
    pub ip: String,
    /// User-Agent(缺失为 None)
    pub user_agent: Option<String>,
    /// 请求入口时刻
    pub started: std::time::Instant,
    /// 请求 ID(与访问日志 / `x-request-id` 响应头同值)
    pub request_id: Option<String>,
}

impl ClientContext {
    /// 距请求入口的耗时
    pub fn elapsed(&self) -> std::time::Duration {
        self.started.elapsed()
    }

    /// 距请求入口的耗时(毫秒)
    pub fn elapsed_ms(&self) -> u64 {
        self.elapsed().as_millis() as u64
    }
}

impl<S: Send + Sync> FromRequestParts<S> for ClientContext {
    type Rejection = std::convert::Infallible;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let ip = parts
            .extensions
            .get::<crate::middleware::ClientIp>()
            .map(|c| c.0.clone())
            .unwrap_or_else(|| "unknown".to_string());
        let user_agent = parts
            .headers
            .get(axum::http::header::USER_AGENT)
            .and_then(|v| v.to_str().ok())
            .map(|s| s.to_string());
        let started = parts
            .extensions
            .get::<crate::middleware::RequestStart>()
            .map(|r| r.0)
            .unwrap_or_else(std::time::Instant::now);
        // RequestId(0) 在 ClientIdentity(10) 外侧,正常链路必有该扩展;
        // 手工 Router 未装该层时为 None
        let request_id = parts
            .extensions
            .get::<crate::middleware::request_id::RequestId>()
            .map(|r| r.0.clone());
        Ok(Self { ip, user_agent, started, request_id })
    }
}

// ──── TenantId ────────────────────────────────────────

/// 从**已解析的租户上下文**(`tenant_context_layer` 注入)读取租户 ID
///
/// 租户解析的唯一权威来源是租户层:已登录用户的租户以会话绑定值为准,
/// 客户端租户头(默认 `X-Tenant-Id`,可配)无法覆盖,防止登录用户带头
/// 越权访问其他租户数据。本提取器不再回退读请求头,避免绕过租户层
/// 的安全策略。
///
/// 登录接口等 bootstrap 路由请使用 [`RequestedTenantId`](读取原始头值)。
#[derive(Debug, Clone)]
pub struct TenantId(pub i64);

impl std::ops::Deref for TenantId {
    type Target = i64;
    fn deref(&self) -> &i64 {
        &self.0
    }
}

impl<S: Send + Sync> FromRequestParts<S> for TenantId {
    type Rejection = ApiError;
    async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
        // 只读租户层已解析的上下文(业务不能绕过解析策略)
        parts
            .extensions
            .get::<crate::tenant::TenantContext>()
            .and_then(|ctx| ctx.tenant_id)
            .map(TenantId)
            .ok_or_else(|| ApiError::bad_request(error_message_of(ErrorCode::BadRequest)))
    }
}

// ──── RequestedTenantId ────────────────────────────────

/// 从租户头(默认 `X-Tenant-Id`,可配)读取**客户端声明的目标租户**(原始值)
///
/// 仅限登录接口等 public / auth bootstrap 路由使用;受保护路由请使用
/// [`TenantId`](读取已解析的安全租户上下文)。
#[derive(Debug, Clone)]
pub struct RequestedTenantId(pub String);

impl std::ops::Deref for RequestedTenantId {
    type Target = str;
    fn deref(&self) -> &str {
        &self.0
    }
}

impl<S: Send + Sync> FromRequestParts<S> for RequestedTenantId {
    type Rejection = ApiError;
    async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
        parts
            .headers
            .get(crate::tenant::tenant_header())
            .and_then(|v| v.to_str().ok())
            .filter(|s| !s.is_empty())
            .map(|s| RequestedTenantId(s.to_string()))
            .ok_or_else(|| ApiError::bad_request(error_message_of(ErrorCode::BadRequest)))
    }
}

// ──── FileSender ──────────────────────────────────────

use axum::body::Body;
use std::path::PathBuf;

#[derive(Debug, Clone)]
pub struct FileSender {
    root: PathBuf,
}

impl FileSender {
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self { root: root.into() }
    }

    pub async fn send(
        &self,
        path: &str,
        content_type: &str,
    ) -> Result<axum::response::Response, ApiError> {
        // 词法规范化后再做逐段包含校验:单纯的 join + starts_with 无法拦截 `..`,
        // 因为 `..` 组件会保留在路径中,starts_with 仍会命中 root 前缀而放行越界路径。
        let root = lexically_canonicalize(&self.root);
        let full = lexically_canonicalize(&root.join(path.trim_start_matches('/')));
        if !is_within(&full, &root) {
            return Err(ApiError::forbidden(error_message_of(ErrorCode::Forbidden)));
        }
        // 流式发送:不把整个文件读入内存(大文件下载不会 OOM)
        let file = tokio::fs::File::open(&full)
            .await
            .map_err(|_| ApiError::not_found(error_message_of(ErrorCode::NotFound)))?;
        let len = file
            .metadata()
            .await
            .map_err(|_| ApiError::not_found(error_message_of(ErrorCode::NotFound)))?
            .len();
        let stream = tokio_util::io::ReaderStream::new(file);
        let filename = full
            .file_name()
            .and_then(|n| n.to_str())
            .map(sanitize_header_filename)
            .unwrap_or_else(|| "download".to_string());
        axum::response::Response::builder()
            .header("Content-Type", content_type)
            .header("Content-Length", len)
            .header(
                "Content-Disposition",
                format!("attachment; filename=\"{}\"", filename),
            )
            .body(Body::from_stream(stream))
            .map_err(|e| ApiError::internal(format!("构建文件响应失败: {}", e)))
    }
}

impl<S: Send + Sync> FromRequestParts<S> for FileSender {
    type Rejection = ApiError;
    async fn from_request_parts(_parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
        let path: PathBuf = { crate::resources::download_path().into() };
        Ok(FileSender::new(path))
    }
}

/// 净化文件名以安全放入 `Content-Disposition` quoted-string:
/// 仅保留可见 ASCII 且剔除 `"` `\`(防 header 注入);
/// 非 ASCII 文件名(如中文名)回退为 "download"(RFC 5987 编码暂不支持)。
fn sanitize_header_filename(name: &str) -> String {
    let sanitized: String = name
        .chars()
        .map(|c| match c {
            '"' | '\\' | '\r' | '\n' => '_',
            c => c,
        })
        .collect();
    if sanitized.is_empty() || !sanitized.is_ascii() || sanitized.bytes().any(|b| !(0x20..=0x7e).contains(&b)) {
        "download".to_string()
    } else {
        sanitized
    }
}

/// 词法规范化路径:解析 `.` 与 `..`,**不访问文件系统**、不解析符号链接。
/// 当 `..` 超出根时超出部分被截断到根,配合 `is_within` 即可判定越界。
fn lexically_canonicalize(path: &std::path::Path) -> PathBuf {
    use std::path::Component;
    let mut out: Vec<Component<'_>> = Vec::new();
    for comp in path.components() {
        match comp {
            Component::CurDir => {}
            Component::ParentDir => {
                if let Some(Component::Normal(_)) = out.last() {
                    out.pop();
                }
            }
            other => out.push(other),
        }
    }
    out.iter().collect()
}

/// 判断 `path` 是否等于或在 `base` 目录之内(逐段比较,避免 `/data` 误匹配 `/data-evil`)。
fn is_within(path: &std::path::Path, base: &std::path::Path) -> bool {
    let base_segments: Vec<_> = base.components().collect();
    let path_segments: Vec<_> = path.components().collect();
    if path_segments.len() < base_segments.len() {
        return path == base;
    }
    path_segments[..base_segments.len()] == base_segments[..]
}