feat(health): patient_service 集成 PiiCrypto — 电话/过敏史/病史加密
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled

- HealthState.crypto: HealthCrypto → PiiCrypto (erp-core)
- create_patient: 加密 phone/allergy/medical_history + HMAC 索引
- update_patient: 同上,同步加密
- model_to_resp_decrypted: 解密所有 Tier 1 字段
- model_to_resp (列表): Tier 1 字段返回 None
- list_patients 搜索: 新增 phone hash 精确搜索
- article handler: 适配新 list_articles 签名
- article 迁移: 添加 category_id 列
- error.rs: From<String> for HealthError
- 集成测试: HealthCrypto → PiiCrypto::dev_default()
This commit is contained in:
iven
2026-04-26 10:37:52 +08:00
parent e0b299ccd4
commit e6f036eaf4
11 changed files with 367 additions and 51 deletions

View File

@@ -16,9 +16,31 @@ pub struct Model {
#[sea_orm(skip_serializing_if = "Option::is_none")]
pub category: Option<String>,
#[sea_orm(skip_serializing_if = "Option::is_none")]
pub category_id: Option<Uuid>,
#[sea_orm(skip_serializing_if = "Option::is_none")]
pub author: Option<String>,
#[sea_orm(skip_serializing_if = "Option::is_none")]
pub published_at: Option<DateTimeUtc>,
/// 状态: draft / pending_review / approved / rejected / published
pub status: String,
/// URL 友好标识
#[sea_orm(skip_serializing_if = "Option::is_none")]
pub slug: Option<String>,
/// 内容类型: rich_text / markdown
pub content_type: String,
/// 审核人
#[sea_orm(skip_serializing_if = "Option::is_none")]
pub reviewed_by: Option<Uuid>,
/// 审核时间
#[sea_orm(skip_serializing_if = "Option::is_none")]
pub reviewed_at: Option<DateTimeUtc>,
/// 审核备注
#[sea_orm(skip_serializing_if = "Option::is_none")]
pub review_note: Option<String>,
/// 浏览次数
pub view_count: i32,
/// 排序权重
pub sort_order: i32,
pub created_at: DateTimeUtc,
pub updated_at: DateTimeUtc,
#[sea_orm(skip_serializing_if = "Option::is_none")]

View File

@@ -118,4 +118,10 @@ impl From<AppError> for HealthError {
}
}
impl From<String> for HealthError {
fn from(err: String) -> Self {
HealthError::Validation(err)
}
}
pub type HealthResult<T> = Result<T, HealthError>;

View File

@@ -23,6 +23,7 @@ where
let page_size = params.page_size.unwrap_or(20);
let result = article_service::list_articles(
&state, ctx.tenant_id, page, page_size, params.category,
params.status, params.category_id, params.tag_id, params.keyword,
)
.await?;
Ok(Json(ApiResponse::ok(result)))

View File

@@ -462,20 +462,19 @@ impl ErpModule for HealthModule {
}
async fn on_startup(&self, ctx: &erp_core::module::ModuleContext) -> erp_core::error::AppResult<()> {
let crypto = match crate::crypto::HealthCrypto::from_keys(
&std::env::var("HEALTH_AES_KEY").unwrap_or_default(),
&std::env::var("HEALTH_HMAC_KEY").unwrap_or_default(),
let crypto = match erp_core::crypto::PiiCrypto::from_kek_hex(
&std::env::var("ERP__CRYPTO__KEK").unwrap_or_default(),
) {
Ok(c) => c,
Err(_) => {
#[cfg(debug_assertions)]
{
tracing::warn!("HEALTH_AES_KEY / HEALTH_HMAC_KEY 未设置或无效,使用开发默认密钥");
crate::crypto::HealthCrypto::dev_default()
tracing::warn!("ERP__CRYPTO__KEK 未设置或无效,使用开发默认密钥");
erp_core::crypto::PiiCrypto::dev_default()
}
#[cfg(not(debug_assertions))]
{
panic!("HEALTH_AES_KEY 和 HEALTH_HMAC_KEY 必须设置为有效的 64 字符 hex 字符串(生产环境不允许回退到开发密钥)");
panic!("ERP__CRYPTO__KEK 必须设置为有效的 64 字符 hex 字符串(生产环境不允许回退到开发密钥)");
}
}
};

View File

@@ -22,6 +22,7 @@ use crate::error::{HealthError, HealthResult};
use crate::service::validation::{validate_gender, validate_blood_type, validate_patient_status, validate_verification_status};
use crate::service::masking::{mask_id_number, mask_phone, validate_status_transition};
use crate::state::HealthState;
use erp_core::crypto::{self as pii, PiiCrypto};
// ---------------------------------------------------------------------------
// 患者 CRUD
@@ -57,11 +58,13 @@ pub async fn list_patients(
.filter(patient::Column::DeletedAt.is_null());
if let Some(ref search) = search {
let search_hash = state.crypto.hmac_hash(search);
let search_hash = pii::hmac_hash(state.crypto.kek(), search);
let phone_hash = pii::hmac_hash(state.crypto.kek(), search);
query = query.filter(
Condition::any()
.add(patient::Column::Name.contains(search))
.add(patient::Column::IdNumberHash.eq(search_hash)),
.add(patient::Column::IdNumberHash.eq(search_hash))
.add(patient::Column::EmergencyContactPhoneHash.eq(phone_hash)),
);
}
@@ -109,13 +112,35 @@ pub async fn create_patient(
// 加密身份证号 + HMAC 索引
let (encrypted_id_number, id_number_hash) = match req.id_number {
Some(ref plain) if !plain.is_empty() => {
let encrypted = state.crypto.encrypt(plain)?;
let hash = state.crypto.hmac_hash(plain);
let encrypted = pii::encrypt(state.crypto.kek(), plain)?;
let hash = pii::hmac_hash(state.crypto.kek(), plain);
(Some(encrypted), Some(hash))
}
_ => (None, None),
};
// 加密紧急联系人电话 + HMAC 索引
let (encrypted_phone, phone_hash) = match req.emergency_contact_phone {
Some(ref p) if !p.is_empty() => {
let encrypted = pii::encrypt(state.crypto.kek(), p)?;
let hash = pii::hmac_hash(state.crypto.kek(), p);
(Some(encrypted), Some(hash))
}
_ => (None, None),
};
// 加密过敏史
let encrypted_allergy = req.allergy_history.as_ref()
.filter(|a| !a.is_empty())
.map(|a| pii::encrypt(state.crypto.kek(), a))
.transpose()?;
// 加密病史摘要
let encrypted_medical = req.medical_history_summary.as_ref()
.filter(|m| !m.is_empty())
.map(|m| pii::encrypt(state.crypto.kek(), m))
.transpose()?;
let active = patient::ActiveModel {
id: Set(id),
tenant_id: Set(tenant_id),
@@ -126,12 +151,12 @@ pub async fn create_patient(
blood_type: Set(req.blood_type),
id_number: Set(encrypted_id_number),
id_number_hash: Set(id_number_hash),
allergy_history: Set(req.allergy_history),
medical_history_summary: Set(req.medical_history_summary),
allergy_history: Set(encrypted_allergy),
medical_history_summary: Set(encrypted_medical),
emergency_contact_name: Set(req.emergency_contact_name),
emergency_contact_phone: Set(req.emergency_contact_phone),
emergency_contact_phone_hash: Set(None),
key_version: Set(None),
emergency_contact_phone: Set(encrypted_phone),
emergency_contact_phone_hash: Set(phone_hash),
key_version: Set(Some(1)),
status: Set("active".to_string()),
verification_status: Set("pending".to_string()),
source: Set(req.source),
@@ -222,15 +247,26 @@ pub async fn update_patient(
if req.birth_date.is_some() { active.birth_date = Set(req.birth_date); }
if let Some(v) = req.blood_type { active.blood_type = Set(Some(v)); }
if let Some(ref plain) = req.id_number {
let encrypted = state.crypto.encrypt(plain)?;
let hash = state.crypto.hmac_hash(plain);
let encrypted = pii::encrypt(state.crypto.kek(), plain)?;
let hash = pii::hmac_hash(state.crypto.kek(), plain);
active.id_number = Set(Some(encrypted));
active.id_number_hash = Set(Some(hash));
}
if let Some(v) = req.allergy_history { active.allergy_history = Set(Some(v)); }
if let Some(v) = req.medical_history_summary { active.medical_history_summary = Set(Some(v)); }
if let Some(ref v) = req.allergy_history {
let encrypted = pii::encrypt(state.crypto.kek(), v)?;
active.allergy_history = Set(Some(encrypted));
}
if let Some(ref v) = req.medical_history_summary {
let encrypted = pii::encrypt(state.crypto.kek(), v)?;
active.medical_history_summary = Set(Some(encrypted));
}
if let Some(v) = req.emergency_contact_name { active.emergency_contact_name = Set(Some(v)); }
if let Some(v) = req.emergency_contact_phone { active.emergency_contact_phone = Set(Some(v)); }
if let Some(ref v) = req.emergency_contact_phone {
let encrypted = pii::encrypt(state.crypto.kek(), v)?;
let hash = pii::hmac_hash(state.crypto.kek(), v);
active.emergency_contact_phone = Set(Some(encrypted));
active.emergency_contact_phone_hash = Set(Some(hash));
}
if let Some(v) = req.source { active.source = Set(Some(v)); }
if let Some(v) = req.notes { active.notes = Set(Some(v)); }
if let Some(ref v) = req.status { active.status = Set(v.clone()); }
@@ -738,10 +774,10 @@ fn model_to_resp(m: patient::Model) -> PatientResp {
birth_date: m.birth_date,
blood_type: m.blood_type,
id_number: None,
allergy_history: m.allergy_history,
medical_history_summary: m.medical_history_summary,
allergy_history: None,
medical_history_summary: None,
emergency_contact_name: m.emergency_contact_name,
emergency_contact_phone: mask_phone(m.emergency_contact_phone.as_deref()),
emergency_contact_phone: None,
status: m.status,
verification_status: m.verification_status,
source: m.source,
@@ -752,11 +788,21 @@ fn model_to_resp(m: patient::Model) -> PatientResp {
}
}
/// 详情用 — 解密身份证号
fn model_to_resp_decrypted(crypto: &crate::crypto::HealthCrypto, m: patient::Model) -> PatientResp {
let decrypted_id_number = m.id_number.as_ref().and_then(|enc| {
crypto.decrypt(enc).ok()
});
/// 详情用 — 解密 Tier 1 字段
fn model_to_resp_decrypted(crypto: &PiiCrypto, m: patient::Model) -> PatientResp {
let kek = crypto.kek();
let decrypted_id_number = m.id_number.as_ref()
.map(|enc| pii::decrypt(kek, enc))
.transpose().ok().flatten();
let decrypted_allergy = m.allergy_history.as_ref()
.map(|enc| pii::decrypt(kek, enc))
.transpose().ok().flatten();
let decrypted_medical = m.medical_history_summary.as_ref()
.map(|enc| pii::decrypt(kek, enc))
.transpose().ok().flatten();
let decrypted_phone = m.emergency_contact_phone.as_ref()
.map(|enc| pii::decrypt(kek, enc))
.transpose().ok().flatten();
PatientResp {
id: m.id,
user_id: m.user_id,
@@ -765,10 +811,10 @@ fn model_to_resp_decrypted(crypto: &crate::crypto::HealthCrypto, m: patient::Mod
birth_date: m.birth_date,
blood_type: m.blood_type,
id_number: decrypted_id_number.map(|id| mask_id_number(&id)),
allergy_history: m.allergy_history,
medical_history_summary: m.medical_history_summary,
allergy_history: decrypted_allergy,
medical_history_summary: decrypted_medical,
emergency_contact_name: m.emergency_contact_name,
emergency_contact_phone: mask_phone(m.emergency_contact_phone.as_deref()),
emergency_contact_phone: mask_phone(decrypted_phone.as_deref()),
status: m.status,
verification_status: m.verification_status,
source: m.source,

View File

@@ -1,4 +1,4 @@
use crate::crypto::HealthCrypto;
use erp_core::crypto::PiiCrypto;
use erp_core::events::EventBus;
use sea_orm::DatabaseConnection;
@@ -6,5 +6,5 @@ use sea_orm::DatabaseConnection;
pub struct HealthState {
pub db: DatabaseConnection,
pub event_bus: EventBus,
pub crypto: HealthCrypto,
pub crypto: PiiCrypto,
}