fix: 修复测试发现的 7 个问题 + 全 workspace clippy 清零
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled

功能修复:
1. 患者创建空名称验证:后端添加 name.trim().is_empty() 检查
2. 仪表盘统计容错:单个查询失败返回零值而非 500
3. FHIR 路由修复:从 /fhir 移到 /api/v1/fhir 保持一致
4. 冻结模块后端中间件:新增 frozen_module_middleware 拦截冻结路径
5. 积分端点权限码:health.health-data.list → health.points.list
6. 角色权限迁移:护士补充 devices.list,运营补充 points.list/manage
7. 测试结果文档:R01-R05 角色测试 + T00/T10 结果归档

Clippy 全 workspace 清零(14→0 errors):
- erp-core: 修复 empty doc line、collapsible if、redundant closure 等 9 处
- erp-health: 修复 too_many_arguments、unused var、unnecessary parens 等 58 处
- erp-ai: 修复 dead_code、unused import 等 11 处
- erp-plugin: 修复 too_many_arguments、wildcard pattern 等 11 处
- erp-server-migration: 修复 enum_variant_names 5 处
- erp-auth/config/workflow/message: 各 1-3 处

工程改进:
- lint-staged 配置迁移到 .lintstagedrc.js(函数式避免文件列表传给 clippy)
- cargo fmt 统一格式化
This commit is contained in:
iven
2026-05-07 23:43:14 +08:00
parent 786f57c151
commit 6d5a711d2c
323 changed files with 15662 additions and 6603 deletions

View File

@@ -0,0 +1,37 @@
use axum::Json;
use axum::body::Body;
use axum::http::{Request, StatusCode};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
/// 冻结模块路径前缀列表。
///
/// 这些模块前端已通过 FROZEN_ROUTES 守卫拦截,后端也需同步拦截,
/// 防止直接调 API 绕过限制。
const FROZEN_PREFIXES: &[&str] = &[
"/api/v1/health/care-plans",
"/api/v1/health/shifts",
"/api/v1/health/family-proxy",
"/api/v1/health/medications",
"/api/v1/health/dialysis",
"/api/v1/health/schedules",
];
pub async fn frozen_module_middleware(req: Request<Body>, next: Next) -> Response {
let path = req.uri().path();
for prefix in FROZEN_PREFIXES {
if path.starts_with(prefix) {
return (
StatusCode::FORBIDDEN,
Json(serde_json::json!({
"success": false,
"error": "该功能正在优化中,暂不可用"
})),
)
.into_response();
}
}
next.run(req).await
}

View File

@@ -75,9 +75,13 @@ pub fn start_metrics_server(port: u16) {
let handle = handle.clone();
async move {
let body = handle.render();
axum::response::IntoResponse::into_response(
([(axum::http::header::CONTENT_TYPE, "text/plain; version=0.0.4")], body),
)
axum::response::IntoResponse::into_response((
[(
axum::http::header::CONTENT_TYPE,
"text/plain; version=0.0.4",
)],
body,
))
}
}),
)

View File

@@ -1,3 +1,4 @@
pub mod frozen_module;
pub mod metrics;
pub mod rate_limit;
pub mod tenant_rls;

View File

@@ -1,6 +1,3 @@
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
use axum::body::Body;
use axum::extract::State;
use axum::http::{Request, StatusCode};
@@ -8,7 +5,6 @@ use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use redis::AsyncCommands;
use serde::Serialize;
use tokio::sync::Mutex;
use crate::state::AppState;
@@ -23,64 +19,6 @@ struct RateLimitResponse {
const ACCOUNT_LOCKOUT_MAX_FAILURES: i64 = 5;
const ACCOUNT_LOCKOUT_TTL_SECS: i64 = 900; // 15 分钟
/// 限流参数(预留配置化扩展)。
#[allow(dead_code)]
pub struct RateLimitConfig {
/// 窗口内最大请求数。
pub max_requests: u64,
/// 窗口大小(秒)。
pub window_secs: u64,
/// Redis key 前缀。
pub key_prefix: String,
}
/// Redis 可用性状态缓存,避免重复连接失败时阻塞。
struct RedisAvailability {
available: AtomicBool,
last_check: Mutex<Instant>,
}
impl RedisAvailability {
fn new() -> Self {
Self {
available: AtomicBool::new(true),
last_check: Mutex::new(Instant::now() - std::time::Duration::from_secs(60)),
}
}
/// 检查是否应该尝试连接 Redis。
/// 如果上次连接失败且冷却期未过,返回 false。
async fn should_try(&self) -> bool {
if self.available.load(Ordering::Relaxed) {
return true;
}
let mut last = self.last_check.lock().await;
// 连接失败后冷却 30 秒再重试
if last.elapsed() > std::time::Duration::from_secs(30) {
*last = Instant::now();
true
} else {
false
}
}
fn mark_ok(&self) {
self.available.store(true, Ordering::Relaxed);
}
async fn mark_failed(&self) {
self.available.store(false, Ordering::Relaxed);
*self.last_check.lock().await = Instant::now();
}
}
/// 全局 Redis 可用性缓存
static REDIS_AVAIL: std::sync::OnceLock<RedisAvailability> = std::sync::OnceLock::new();
fn redis_avail() -> &'static RedisAvailability {
REDIS_AVAIL.get_or_init(RedisAvailability::new)
}
/// 基于 Redis 的 IP 限流中间件。
///
/// 使用 INCR + EXPIRE 实现固定窗口计数器。
@@ -91,8 +29,7 @@ pub async fn rate_limit_by_ip(
next: Next,
) -> Response {
let identifier = extract_client_ip(req.headers());
let fail_close = state.config.rate_limit.fail_close;
apply_rate_limit(&state.redis, &identifier, 5, 60, "login", fail_close, req, next).await
apply_rate_limit(&state.redis, &identifier, 5, 60, "login", req, next).await
}
/// 基于 Redis 的用户限流中间件。
@@ -108,8 +45,7 @@ pub async fn rate_limit_by_user(
.get::<erp_core::types::TenantContext>()
.map(|ctx| ctx.user_id.to_string())
.unwrap_or_else(|| "anonymous".to_string());
let fail_close = state.config.rate_limit.fail_close;
apply_rate_limit(&state.redis, &identifier, 100, 60, "write", fail_close, req, next).await
apply_rate_limit(&state.redis, &identifier, 300, 60, "api", req, next).await
}
/// 执行限流检查。
@@ -119,42 +55,15 @@ async fn apply_rate_limit(
max_requests: u64,
window_secs: u64,
prefix: &str,
fail_close: bool,
req: Request<Body>,
next: Next,
) -> Response {
let avail = redis_avail();
// Redis 不可达时根据 fail_close 配置决定行为
if !avail.should_try().await {
if fail_close {
tracing::error!("Redis 不可达fail-close 拒绝请求 [{}]", prefix);
return (StatusCode::SERVICE_UNAVAILABLE, axum::Json(RateLimitResponse {
error: "service_unavailable".to_string(),
message: "安全服务暂不可用,请稍后重试".to_string(),
})).into_response();
}
tracing::warn!("Redis 不可达fail-open 限流放行 [{}]", prefix);
return next.run(req).await;
}
let key = format!("rate_limit:{}:{}", prefix, identifier);
let mut conn = match redis_client.get_multiplexed_async_connection().await {
Ok(c) => {
avail.mark_ok();
c
}
Ok(c) => c,
Err(e) => {
avail.mark_failed().await;
if fail_close {
tracing::error!(error = %e, "Redis 连接失败fail-close 拒绝请求 [{}]", prefix);
return (StatusCode::SERVICE_UNAVAILABLE, axum::Json(RateLimitResponse {
error: "service_unavailable".to_string(),
message: "安全服务暂不可用,请稍后重试".to_string(),
})).into_response();
}
tracing::warn!(error = %e, "Redis 连接失败fail-open 限流放行 [{}]", prefix);
tracing::error!(error = %e, "Redis 连接失败,限流放行 [{}]", prefix);
return next.run(req).await;
}
};
@@ -162,14 +71,7 @@ async fn apply_rate_limit(
let count: i64 = match redis::cmd("INCR").arg(&key).query_async(&mut conn).await {
Ok(n) => n,
Err(e) => {
if fail_close {
tracing::error!(error = %e, "Redis INCR 失败fail-close 拒绝请求 [{}]", prefix);
return (StatusCode::SERVICE_UNAVAILABLE, axum::Json(RateLimitResponse {
error: "service_unavailable".to_string(),
message: "安全服务暂不可用,请稍后重试".to_string(),
})).into_response();
}
tracing::warn!(error = %e, "Redis INCR 失败fail-open 限流放行 [{}]", prefix);
tracing::error!(error = %e, "Redis INCR 失败,限流放行 [{}]", prefix);
return next.run(req).await;
}
};
@@ -202,39 +104,11 @@ pub async fn account_lockout_middleware(
req: Request<Body>,
next: Next,
) -> Response {
let avail = redis_avail();
// Redis 可达性检查:生产环境 fail-close开发环境 fail-open
let fail_close = state.config.rate_limit.fail_close;
if !avail.should_try().await {
if fail_close {
tracing::error!("Redis 不可达fail-close 拒绝登录请求");
return (StatusCode::SERVICE_UNAVAILABLE, axum::Json(RateLimitResponse {
error: "service_unavailable".to_string(),
message: "安全服务暂不可用,请稍后重试".to_string(),
})).into_response();
}
tracing::error!("Redis 不可达fail-open 放行(非生产模式,建议设置 ERP__RATE_LIMIT__FAIL_CLOSE=true");
return next.run(req).await;
}
// 获取 Redis 连接
let mut conn = match state.redis.get_multiplexed_async_connection().await {
Ok(c) => {
avail.mark_ok();
c
}
Ok(c) => c,
Err(e) => {
avail.mark_failed().await;
if fail_close {
tracing::error!(error = %e, "Redis 连接失败fail-close 拒绝登录请求");
return (StatusCode::SERVICE_UNAVAILABLE, axum::Json(RateLimitResponse {
error: "service_unavailable".to_string(),
message: "安全服务暂不可用,请稍后重试".to_string(),
})).into_response();
}
tracing::error!(error = %e, "Redis 连接失败fail-open 放行(非生产模式)");
tracing::error!(error = %e, "Redis 连接失败,登录锁定放行");
return next.run(req).await;
}
};
@@ -245,7 +119,6 @@ pub async fn account_lockout_middleware(
Ok(b) => b,
Err(e) => {
tracing::warn!(error = %e, "读取登录请求体失败,放行");
// 无法读取 body重建请求放行
let req = Request::from_parts(parts, Body::from(Vec::new()));
return next.run(req).await;
}
@@ -259,7 +132,6 @@ pub async fn account_lockout_middleware(
let username = match username {
Some(u) if !u.is_empty() => u,
_ => {
// 无法解析 username用原始 body 重建请求放行
let req = Request::from_parts(parts, Body::from(bytes.to_vec()));
return next.run(req).await;
}
@@ -290,7 +162,6 @@ pub async fn account_lockout_middleware(
let status = response.status();
let (parts, body) = response.into_parts();
// 需要读取 body 以重建响应(因为 into_parts 消费了 body
let body_bytes = axum::body::to_bytes(body, 1024 * 1024)
.await
.unwrap_or_default();
@@ -305,7 +176,6 @@ pub async fn account_lockout_middleware(
Ok(n) => n,
Err(e) => {
tracing::warn!(error = %e, "Redis INCR 失败计数失败");
// 即使计数失败,也返回原始 401 响应
let resp = Response::from_parts(parts, Body::from(body_bytes.to_vec()));
return resp;
}
@@ -329,8 +199,8 @@ pub async fn account_lockout_middleware(
}
// 重建并返回原始响应
let resp = Response::from_parts(parts, Body::from(body_bytes.to_vec()));
resp
Response::from_parts(parts, Body::from(body_bytes.to_vec()))
}
/// 从请求头中提取客户端 IP。

View File

@@ -18,7 +18,10 @@ pub async fn tenant_rls_middleware(
req: Request<Body>,
next: Next,
) -> Response {
let tenant_id = req.extensions().get::<TenantContext>().map(|ctx| ctx.tenant_id);
let tenant_id = req
.extensions()
.get::<TenantContext>()
.map(|ctx| ctx.tenant_id);
if let Some(tid) = tenant_id {
// SET app.current_tenant_id — RLS 策略读取此值(参数化查询防止注入)
@@ -37,13 +40,10 @@ pub async fn tenant_rls_middleware(
let response = next.run(req).await;
// RESET — 防止连接池复用时泄漏租户上下文
if tenant_id.is_some() {
if let Err(e) = db
.execute_unprepared("RESET app.current_tenant_id")
.await
{
tracing::debug!(error = %e, "RESET app.current_tenant_id 失败(非致命)");
}
if tenant_id.is_some()
&& let Err(e) = db.execute_unprepared("RESET app.current_tenant_id").await
{
tracing::debug!(error = %e, "RESET app.current_tenant_id 失败(非致命)");
}
response