fix(security): implement all 15 security fixes from penetration test V1

Security audit (2026-03-31): 5 HIGH + 10 MEDIUM issues, all fixed.

HIGH:
- H1: JWT password_version mechanism (pwv in Claims, middleware verification,
  auto-increment on password change)
- H2: Docker saas port bound to 127.0.0.1
- H3: TOTP encryption key decoupled from JWT secret (production bailout)
- H4+H5: Tauri CSP hardened (removed unsafe-inline, restricted connect-src)

MEDIUM:
- M1: Persistent rate limiting (PostgreSQL rate_limit_events table)
- M2: Account lockout (5 failures -> 15min lock)
- M3: RFC 5322 email validation with regex
- M4: Device registration typed struct with length limits
- M5: Provider URL validation on create/update (SSRF prevention)
- M6: Legacy TOTP secret migration (fixed nonce -> random nonce)
- M7: Legacy frontend crypto migration (static salt -> random salt)
- M8+M9: Admin frontend: removed JS token storage, HttpOnly cookie only
- M10: Pipeline debug log sanitization (keys only, 100-char truncation)

Also: fixed CLAUDE.md Section 12 (was corrupted), added title.rs middleware
skeleton, fixed RegisterDeviceRequest visibility.
This commit is contained in:
iven
2026-04-01 08:38:37 +08:00
parent 3b1a017761
commit e3b93ff96d
26 changed files with 597 additions and 220 deletions

View File

@@ -40,6 +40,44 @@ async fn main() -> anyhow::Result<()> {
let shutdown_token = CancellationToken::new();
let state = AppState::new(db.clone(), config.clone(), dispatcher, shutdown_token.clone())?;
// Restore rate limit counts from DB so limits survive server restarts
{
let rows: Vec<(String, i64)> = sqlx::query_as(
"SELECT key, SUM(count) FROM rate_limit_events WHERE window_start > NOW() - interval '1 hour' GROUP BY key"
)
.fetch_all(&db)
.await
.unwrap_or_default();
let mut restored_count = 0usize;
for (key, count) in rows {
let mut entries = Vec::new();
// Approximate: insert count timestamps at "now" — the DashMap will
// expire them naturally via the retain() call in the middleware.
// This is intentionally approximate; exact window alignment is not
// required for rate limiting correctness.
for _ in 0..count as usize {
entries.push(std::time::Instant::now());
}
state.rate_limit_entries.insert(key, entries);
restored_count += 1;
}
info!("Restored rate limit state from DB: {} keys", restored_count);
}
// 迁移旧格式 TOTP secret明文 → 加密 enc: 格式)
{
let config_for_migration = state.config.read().await;
if let Ok(enc_key) = config_for_migration.totp_encryption_key() {
drop(config_for_migration);
if let Err(e) = zclaw_saas::crypto::migrate_legacy_totp_secrets(&db, &enc_key).await {
tracing::warn!("TOTP legacy migration check failed: {}", e);
}
} else {
drop(config_for_migration);
}
}
// 启动声明式 Scheduler从 TOML 配置读取定时任务)
let scheduler_config = &config.scheduler;
zclaw_saas::scheduler::start_scheduler(scheduler_config, db.clone(), state.worker_dispatcher.clone_ref());