feat: systematic functional audit — fix 18 issues across Phase A/B
Phase A (P1 production blockers): - A1: Apply IP rate limiting to public routes (login/refresh) - A2: Publish domain events for workflow instance state transitions (completed/suspended/resumed/terminated) via outbox pattern - A3: Replace hardcoded nil UUID default tenant with dynamic DB lookup - A4: Add GET /api/v1/audit-logs query endpoint with pagination - A5: Enhance CORS wildcard warning for production environments Phase B (P2 functional gaps): - B1: Remove dead erp-common crate (zero references in codebase) - B2: Refactor 5 settings pages to use typed API modules instead of direct client calls; create api/themes.ts; delete dead errors.ts - B3: Add resume/suspend buttons to InstanceMonitor page - B4: Remove unused EventHandler trait from erp-core - B5: Handle task.completed events in message module (send notifications) - B6: Wire TimeoutChecker as 60s background task - B7: Auto-skip ServiceTask nodes instead of crashing the process - B8: Remove empty register_routes() from ErpModule trait and modules
This commit is contained in:
@@ -9,7 +9,6 @@ path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
erp-core.workspace = true
|
||||
erp-common.workspace = true
|
||||
tokio.workspace = true
|
||||
axum.workspace = true
|
||||
tower.workspace = true
|
||||
|
||||
75
crates/erp-server/src/handlers/audit_log.rs
Normal file
75
crates/erp-server/src/handlers/audit_log.rs
Normal file
@@ -0,0 +1,75 @@
|
||||
use axum::extract::{Query, State};
|
||||
use axum::response::Json;
|
||||
use axum::routing::get;
|
||||
use axum::Router;
|
||||
use sea_orm::{ColumnTrait, EntityTrait, PaginatorTrait, QueryFilter, QueryOrder};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::state::AppState;
|
||||
use erp_core::entity::audit_log;
|
||||
use erp_core::error::AppError;
|
||||
|
||||
/// 审计日志查询参数。
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct AuditLogQuery {
|
||||
pub resource_type: Option<String>,
|
||||
pub user_id: Option<uuid::Uuid>,
|
||||
pub page: Option<u64>,
|
||||
pub page_size: Option<u64>,
|
||||
}
|
||||
|
||||
/// 审计日志分页响应。
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct AuditLogResponse {
|
||||
pub items: Vec<audit_log::Model>,
|
||||
pub total: u64,
|
||||
pub page: u64,
|
||||
pub page_size: u64,
|
||||
}
|
||||
|
||||
/// GET /audit-logs
|
||||
///
|
||||
/// 分页查询审计日志,支持按 resource_type 和 user_id 过滤。
|
||||
pub async fn list_audit_logs(
|
||||
State(state): State<AppState>,
|
||||
Query(params): Query<AuditLogQuery>,
|
||||
) -> Result<Json<AuditLogResponse>, AppError> {
|
||||
let page = params.page.unwrap_or(1).max(1);
|
||||
let page_size = params.page_size.unwrap_or(20).min(100);
|
||||
let tenant_id = state.default_tenant_id;
|
||||
|
||||
let mut q = audit_log::Entity::find()
|
||||
.filter(audit_log::Column::TenantId.eq(tenant_id));
|
||||
|
||||
if let Some(rt) = ¶ms.resource_type {
|
||||
q = q.filter(audit_log::Column::ResourceType.eq(rt.clone()));
|
||||
}
|
||||
if let Some(uid) = ¶ms.user_id {
|
||||
q = q.filter(audit_log::Column::UserId.eq(*uid));
|
||||
}
|
||||
|
||||
let paginator = q
|
||||
.order_by_desc(audit_log::Column::CreatedAt)
|
||||
.paginate(&state.db, page_size);
|
||||
|
||||
let total = paginator
|
||||
.num_items()
|
||||
.await
|
||||
.map_err(|e| AppError::Internal(format!("查询审计日志失败: {e}")))?;
|
||||
|
||||
let items = paginator
|
||||
.fetch_page(page - 1)
|
||||
.await
|
||||
.map_err(|e| AppError::Internal(format!("查询审计日志失败: {e}")))?;
|
||||
|
||||
Ok(Json(AuditLogResponse {
|
||||
items,
|
||||
total,
|
||||
page,
|
||||
page_size,
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn audit_log_router() -> Router<AppState> {
|
||||
Router::new().route("/audit-logs", get(list_audit_logs))
|
||||
}
|
||||
@@ -1,2 +1,3 @@
|
||||
pub mod audit_log;
|
||||
pub mod health;
|
||||
pub mod openapi;
|
||||
|
||||
@@ -53,8 +53,8 @@ async fn main() -> anyhow::Result<()> {
|
||||
erp_server_migration::Migrator::up(&db, None).await?;
|
||||
tracing::info!("Database migrations applied");
|
||||
|
||||
// Seed default tenant and auth data if not present
|
||||
{
|
||||
// Seed default tenant and auth data if not present, and resolve the actual tenant ID
|
||||
let default_tenant_id = {
|
||||
#[derive(sea_orm::FromQueryResult)]
|
||||
struct TenantId {
|
||||
id: uuid::Uuid,
|
||||
@@ -71,6 +71,7 @@ async fn main() -> anyhow::Result<()> {
|
||||
match existing {
|
||||
Some(row) => {
|
||||
tracing::info!(tenant_id = %row.id, "Default tenant already exists, skipping seed");
|
||||
row.id
|
||||
}
|
||||
None => {
|
||||
let new_tenant_id = uuid::Uuid::now_v7();
|
||||
@@ -101,9 +102,10 @@ async fn main() -> anyhow::Result<()> {
|
||||
.map_err(|e| anyhow::anyhow!("Failed to seed auth data: {}", e))?;
|
||||
|
||||
tracing::info!(tenant_id = %new_tenant_id, "Default tenant ready with auth seed data");
|
||||
new_tenant_id
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Connect to Redis
|
||||
let redis_client = redis::Client::open(&config.redis.url[..])?;
|
||||
@@ -147,6 +149,10 @@ async fn main() -> anyhow::Result<()> {
|
||||
outbox::start_outbox_relay(db.clone(), event_bus.clone());
|
||||
tracing::info!("Outbox relay started");
|
||||
|
||||
// Start timeout checker (scan overdue tasks every 60s)
|
||||
erp_workflow::WorkflowModule::start_timeout_checker(db.clone());
|
||||
tracing::info!("Timeout checker started");
|
||||
|
||||
let host = config.server.host.clone();
|
||||
let port = config.server.port;
|
||||
|
||||
@@ -160,6 +166,7 @@ async fn main() -> anyhow::Result<()> {
|
||||
event_bus,
|
||||
module_registry: registry,
|
||||
redis: redis_client.clone(),
|
||||
default_tenant_id,
|
||||
};
|
||||
|
||||
// --- Build the router ---
|
||||
@@ -171,11 +178,15 @@ async fn main() -> anyhow::Result<()> {
|
||||
// Both layers share the same AppState. The protected layer wraps routes
|
||||
// with the jwt_auth_middleware_fn.
|
||||
|
||||
// Public routes (no authentication)
|
||||
// Public routes (no authentication, but IP-based rate limiting)
|
||||
let public_routes = Router::new()
|
||||
.merge(handlers::health::health_check_router())
|
||||
.merge(erp_auth::AuthModule::public_routes())
|
||||
.route("/docs/openapi.json", axum::routing::get(handlers::openapi::openapi_spec))
|
||||
.layer(axum::middleware::from_fn_with_state(
|
||||
state.clone(),
|
||||
middleware::rate_limit::rate_limit_by_ip,
|
||||
))
|
||||
.with_state(state.clone());
|
||||
|
||||
// Protected routes (JWT authentication required)
|
||||
@@ -184,6 +195,7 @@ async fn main() -> anyhow::Result<()> {
|
||||
.merge(erp_config::ConfigModule::protected_routes())
|
||||
.merge(erp_workflow::WorkflowModule::protected_routes())
|
||||
.merge(erp_message::MessageModule::protected_routes())
|
||||
.merge(handlers::audit_log::audit_log_router())
|
||||
.layer(axum::middleware::from_fn_with_state(
|
||||
state.clone(),
|
||||
middleware::rate_limit::rate_limit_by_user,
|
||||
@@ -229,31 +241,34 @@ fn build_cors_layer(allowed_origins: &str) -> tower_http::cors::CorsLayer {
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
if origins.len() == 1 && origins[0] == "*" {
|
||||
tracing::warn!("CORS: allowing all origins — only use in development!");
|
||||
tower_http::cors::CorsLayer::permissive()
|
||||
} else {
|
||||
let allowed: Vec<HeaderValue> = origins
|
||||
.iter()
|
||||
.filter_map(|o| o.parse::<HeaderValue>().ok())
|
||||
.collect();
|
||||
|
||||
tracing::info!(origins = ?origins, "CORS: restricting to allowed origins");
|
||||
|
||||
tower_http::cors::CorsLayer::new()
|
||||
.allow_origin(AllowOrigin::list(allowed))
|
||||
.allow_methods([
|
||||
axum::http::Method::GET,
|
||||
axum::http::Method::POST,
|
||||
axum::http::Method::PUT,
|
||||
axum::http::Method::DELETE,
|
||||
axum::http::Method::PATCH,
|
||||
])
|
||||
.allow_headers([
|
||||
axum::http::header::AUTHORIZATION,
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
])
|
||||
.allow_credentials(true)
|
||||
tracing::warn!(
|
||||
"⚠️ CORS 允许所有来源 — 仅限开发环境使用!\
|
||||
生产环境请通过 ERP__CORS__ALLOWED_ORIGINS 设置具体的来源域名"
|
||||
);
|
||||
return tower_http::cors::CorsLayer::permissive();
|
||||
}
|
||||
|
||||
let allowed: Vec<HeaderValue> = origins
|
||||
.iter()
|
||||
.filter_map(|o| o.parse::<HeaderValue>().ok())
|
||||
.collect();
|
||||
|
||||
tracing::info!(origins = ?origins, "CORS: restricting to allowed origins");
|
||||
|
||||
tower_http::cors::CorsLayer::new()
|
||||
.allow_origin(AllowOrigin::list(allowed))
|
||||
.allow_methods([
|
||||
axum::http::Method::GET,
|
||||
axum::http::Method::POST,
|
||||
axum::http::Method::PUT,
|
||||
axum::http::Method::DELETE,
|
||||
axum::http::Method::PATCH,
|
||||
])
|
||||
.allow_headers([
|
||||
axum::http::header::AUTHORIZATION,
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
])
|
||||
.allow_credentials(true)
|
||||
}
|
||||
|
||||
async fn shutdown_signal() {
|
||||
|
||||
@@ -14,6 +14,8 @@ pub struct AppState {
|
||||
pub event_bus: EventBus,
|
||||
pub module_registry: ModuleRegistry,
|
||||
pub redis: redis::Client,
|
||||
/// 实际的默认租户 ID,从数据库种子数据中获取。
|
||||
pub default_tenant_id: uuid::Uuid,
|
||||
}
|
||||
|
||||
/// Allow handlers to extract `DatabaseConnection` directly from `State<AppState>`.
|
||||
@@ -44,10 +46,7 @@ impl FromRef<AppState> for erp_auth::AuthState {
|
||||
jwt_secret: state.config.jwt.secret.clone(),
|
||||
access_ttl_secs: parse_ttl(&state.config.jwt.access_token_ttl),
|
||||
refresh_ttl_secs: parse_ttl(&state.config.jwt.refresh_token_ttl),
|
||||
// Default tenant ID: during bootstrap, use a well-known UUID.
|
||||
// In production, tenant resolution middleware will override this.
|
||||
default_tenant_id: uuid::Uuid::parse_str("00000000-0000-0000-0000-000000000000")
|
||||
.unwrap(),
|
||||
default_tenant_id: state.default_tenant_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user