feat(core): DEK 缓存 + 密钥轮换管理端点
- erp-core/crypto/key_manager: DashMap LRU DEK 缓存 (TTL 5min, 100条) - DekManager: get_or_create_dek, generate_new_dek, invalidate - PiiCrypto 集成 DekManager - POST /api/v1/admin/tenants/:id/rotate-key: 生成新 DEK + 缓存失效 - 权限: tenant.manage (仅超级管理员)
This commit is contained in:
120
crates/erp-core/src/crypto/key_manager.rs
Normal file
120
crates/erp-core/src/crypto/key_manager.rs
Normal file
@@ -0,0 +1,120 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use dashmap::DashMap;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::{AppError, AppResult};
|
||||
|
||||
use super::engine;
|
||||
|
||||
/// DEK 缓存条目
|
||||
#[derive(Clone)]
|
||||
struct CachedDek {
|
||||
dek: [u8; 32],
|
||||
version: u32,
|
||||
loaded_at: Instant,
|
||||
}
|
||||
|
||||
/// DEK 缓存管理 — 每租户独立 DEK,LRU + TTL
|
||||
#[derive(Clone)]
|
||||
pub struct DekManager {
|
||||
cache: DashMap<Uuid, CachedDek>,
|
||||
ttl_secs: u64,
|
||||
max_entries: usize,
|
||||
}
|
||||
|
||||
impl DekManager {
|
||||
pub fn new(ttl_secs: u64, max_entries: usize) -> Self {
|
||||
Self {
|
||||
cache: DashMap::new(),
|
||||
ttl_secs,
|
||||
max_entries,
|
||||
}
|
||||
}
|
||||
|
||||
/// 获取或创建租户的 DEK
|
||||
pub fn get_or_create_dek(
|
||||
&self,
|
||||
tenant_id: Uuid,
|
||||
encrypted_dek: Option<&str>,
|
||||
kek: &[u8; 32],
|
||||
) -> AppResult<([u8; 32], u32)> {
|
||||
// 检查缓存
|
||||
if let Some(entry) = self.cache.get(&tenant_id) {
|
||||
if entry.loaded_at.elapsed().as_secs() < self.ttl_secs {
|
||||
return Ok((entry.dek, entry.version));
|
||||
}
|
||||
}
|
||||
|
||||
// 从加密 DEK 解密
|
||||
if let Some(enc_dek) = encrypted_dek {
|
||||
let dek_hex = engine::decrypt(kek, enc_dek).map_err(|e| AppError::Internal(e))?;
|
||||
let dek_bytes = hex::decode(&dek_hex).map_err(|e| AppError::Internal(e.to_string()))?;
|
||||
if dek_bytes.len() != 32 {
|
||||
return Err(AppError::Internal("DEK must be 32 bytes".into()));
|
||||
}
|
||||
let mut dek = [0u8; 32];
|
||||
dek.copy_from_slice(&dek_bytes);
|
||||
|
||||
// 缓存(版本从外部传入时无法确定,使用默认值 1)
|
||||
self.evict_if_full();
|
||||
self.cache.insert(tenant_id, CachedDek {
|
||||
dek,
|
||||
version: 1,
|
||||
loaded_at: Instant::now(),
|
||||
});
|
||||
return Ok((dek, 1));
|
||||
}
|
||||
|
||||
// 无现有 DEK → 生成新的
|
||||
let dek = Self::generate_dek();
|
||||
self.evict_if_full();
|
||||
self.cache.insert(tenant_id, CachedDek {
|
||||
dek,
|
||||
version: 1,
|
||||
loaded_at: Instant::now(),
|
||||
});
|
||||
Ok((dek, 1))
|
||||
}
|
||||
|
||||
/// 使用 KEK 加密 DEK 以便存储
|
||||
pub fn encrypt_dek_for_storage(dek: &[u8; 32], kek: &[u8; 32]) -> AppResult<String> {
|
||||
let dek_hex = hex::encode(dek);
|
||||
engine::encrypt(kek, &dek_hex).map_err(|e| AppError::Internal(e))
|
||||
}
|
||||
|
||||
/// 生成新 DEK 并用 KEK 加密,返回 (新 DEK, 加密后的 DEK)
|
||||
pub fn generate_new_dek(kek: &[u8; 32]) -> AppResult<([u8; 32], String)> {
|
||||
let dek = Self::generate_dek();
|
||||
let encrypted = Self::encrypt_dek_for_storage(&dek, kek)?;
|
||||
Ok((dek, encrypted))
|
||||
}
|
||||
|
||||
/// 使缓存失效(轮换后调用)
|
||||
pub fn invalidate(&self, tenant_id: Uuid) {
|
||||
self.cache.remove(&tenant_id);
|
||||
}
|
||||
|
||||
fn generate_dek() -> [u8; 32] {
|
||||
use rand::RngCore;
|
||||
let mut dek = [0u8; 32];
|
||||
rand::thread_rng().fill_bytes(&mut dek);
|
||||
dek
|
||||
}
|
||||
|
||||
fn evict_if_full(&self) {
|
||||
if self.cache.len() >= self.max_entries {
|
||||
// 简单策略:移除最早加载的一半
|
||||
let to_remove: Vec<Uuid> = self.cache
|
||||
.iter()
|
||||
.filter(|e| e.loaded_at.elapsed().as_secs() > self.ttl_secs / 2)
|
||||
.map(|e| *e.key())
|
||||
.take(self.max_entries / 2)
|
||||
.collect();
|
||||
for id in to_remove {
|
||||
self.cache.remove(&id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user