feat(saas): Phase 1 后端能力补强 — API Token 认证、真实 SSE 流式、速率限制

Phase 1.1: API Token 认证中间件
- auth_middleware 新增 zclaw_ 前缀 token 分支 (SHA-256 验证)
- 合并 token 自身权限与角色权限,异步更新 last_used_at
- 添加 GET /api/v1/auth/me 端点返回当前用户信息
- get_role_permissions 改为 pub(crate) 供中间件调用

Phase 1.2: 真实 SSE 流式中转
- RelayResponse::Sse 改为 axum::body::Body (bytes_stream)
- 流式请求超时提升至 300s,转发 SSE headers (Cache-Control, Connection)
- 添加 futures 依赖用于 StreamExt

Phase 1.3: 滑动窗口速率限制中间件
- 按 account_id 做 per-minute 限流 (默认 60 rpm + 10 burst)
- 超限返回 429 + Retry-After header
- RateLimitConfig 支持配置化,DashMap 存储时间戳

21 tests passed, zero warnings.
This commit is contained in:
iven
2026-03-27 13:49:45 +08:00
parent a0d59b1947
commit d760b9ca10
11 changed files with 237 additions and 13 deletions

View File

@@ -2,6 +2,7 @@
use sqlx::SqlitePool;
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::RwLock;
use crate::config::SaaSConfig;
@@ -14,6 +15,8 @@ pub struct AppState {
pub config: Arc<RwLock<SaaSConfig>>,
/// JWT 密钥
pub jwt_secret: secrecy::SecretString,
/// 速率限制: account_id → 请求时间戳列表
pub rate_limit_entries: Arc<dashmap::DashMap<String, Vec<Instant>>>,
}
impl AppState {
@@ -23,6 +26,7 @@ impl AppState {
db,
config: Arc::new(RwLock::new(config)),
jwt_secret,
rate_limit_entries: Arc::new(dashmap::DashMap::new()),
})
}
}