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

@@ -8,6 +8,32 @@ use aes_gcm::aead::rand_core::RngCore;
use aes_gcm::{Aes256Gcm, Nonce};
use crate::error::{SaasError, SaasResult};
/// 启动时迁移所有旧格式 TOTP secret明文或固定 nonce → 随机 nonce `enc:` 格式)
///
/// 查找 `totp_secret IS NOT NULL AND totp_secret != '' AND totp_secret NOT LIKE 'enc:%'` 的行,
/// 用当前 AES-256-GCM 密钥加密后写回。
pub async fn migrate_legacy_totp_secrets(pool: &sqlx::PgPool, enc_key: &[u8; 32]) -> anyhow::Result<u32> {
let rows: Vec<(String, String)> = sqlx::query_as(
"SELECT id, totp_secret FROM accounts WHERE totp_secret IS NOT NULL AND totp_secret != '' AND totp_secret NOT LIKE 'enc:%'"
)
.fetch_all(pool)
.await?;
let count = rows.len() as u32;
for (account_id, plaintext_secret) in &rows {
let encrypted = encrypt_value(plaintext_secret, enc_key)?;
sqlx::query("UPDATE accounts SET totp_secret = $1 WHERE id = $2")
.bind(&encrypted)
.bind(account_id)
.execute(pool)
.await?;
}
if count > 0 {
tracing::info!("Migrated {} legacy TOTP secrets to encrypted format", count);
}
Ok(count)
}
/// 加密值的前缀标识
pub const ENCRYPTED_PREFIX: &str = "enc:";