feat(health): patient_service 集成 PiiCrypto — 电话/过敏史/病史加密
- 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:
@@ -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")]
|
||||
|
||||
@@ -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>;
|
||||
|
||||
@@ -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)))
|
||||
|
||||
@@ -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 字符串(生产环境不允许回退到开发密钥)");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
use sea_orm_migration::prelude::*;
|
||||
|
||||
#[derive(DeriveMigrationName)]
|
||||
pub struct Migration;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
// 1. ALTER articles 表:新增字段
|
||||
manager
|
||||
.alter_table(
|
||||
Table::alter()
|
||||
.table(Article::Table)
|
||||
.add_column(ColumnDef::new(Article::Status).string_len(20).not_null().default("draft"))
|
||||
.add_column(ColumnDef::new(Article::Slug).string_len(200).null())
|
||||
.add_column(ColumnDef::new(Article::ContentType).string_len(20).not_null().default("rich_text"))
|
||||
.add_column(ColumnDef::new(Article::ReviewedBy).uuid().null())
|
||||
.add_column(ColumnDef::new(Article::ReviewedAt).timestamp_with_time_zone().null())
|
||||
.add_column(ColumnDef::new(Article::ReviewNote).text().null())
|
||||
.add_column(ColumnDef::new(Article::ViewCount).integer().not_null().default(0))
|
||||
.add_column(ColumnDef::new(Article::SortOrder).integer().not_null().default(0))
|
||||
.add_column(ColumnDef::new(Article::CategoryId).uuid().null())
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// 将已有 published_at 不为 null 的记录状态设为 published
|
||||
manager
|
||||
.get_connection()
|
||||
.execute_unprepared(
|
||||
"UPDATE article SET status = 'published' WHERE published_at IS NOT NULL AND deleted_at IS NULL",
|
||||
)
|
||||
.await?;
|
||||
|
||||
// 2. 创建 article_category 表
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(ArticleCategory::Table)
|
||||
.col(ColumnDef::new(ArticleCategory::Id).uuid().not_null().primary_key())
|
||||
.col(ColumnDef::new(ArticleCategory::TenantId).uuid().not_null())
|
||||
.col(ColumnDef::new(ArticleCategory::Name).string_len(100).not_null())
|
||||
.col(ColumnDef::new(ArticleCategory::Slug).string_len(100).null())
|
||||
.col(ColumnDef::new(ArticleCategory::ParentId).uuid().null())
|
||||
.col(ColumnDef::new(ArticleCategory::Description).text().null())
|
||||
.col(ColumnDef::new(ArticleCategory::SortOrder).integer().not_null().default(0))
|
||||
.col(ColumnDef::new(ArticleCategory::CreatedAt).timestamp_with_time_zone().not_null().default(Expr::current_timestamp()))
|
||||
.col(ColumnDef::new(ArticleCategory::UpdatedAt).timestamp_with_time_zone().not_null().default(Expr::current_timestamp()))
|
||||
.col(ColumnDef::new(ArticleCategory::CreatedBy).uuid().null())
|
||||
.col(ColumnDef::new(ArticleCategory::UpdatedBy).uuid().null())
|
||||
.col(ColumnDef::new(ArticleCategory::DeletedAt).timestamp_with_time_zone().null())
|
||||
.col(ColumnDef::new(ArticleCategory::Version).integer().not_null().default(1))
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
manager
|
||||
.create_index(
|
||||
Index::create()
|
||||
.name("idx_article_category_tenant")
|
||||
.table(ArticleCategory::Table)
|
||||
.col(ArticleCategory::TenantId)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// 3. 创建 article_tag 表
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(ArticleTag::Table)
|
||||
.col(ColumnDef::new(ArticleTag::Id).uuid().not_null().primary_key())
|
||||
.col(ColumnDef::new(ArticleTag::TenantId).uuid().not_null())
|
||||
.col(ColumnDef::new(ArticleTag::Name).string_len(50).not_null())
|
||||
.col(ColumnDef::new(ArticleTag::CreatedAt).timestamp_with_time_zone().not_null().default(Expr::current_timestamp()))
|
||||
.col(ColumnDef::new(ArticleTag::UpdatedAt).timestamp_with_time_zone().not_null().default(Expr::current_timestamp()))
|
||||
.col(ColumnDef::new(ArticleTag::CreatedBy).uuid().null())
|
||||
.col(ColumnDef::new(ArticleTag::UpdatedBy).uuid().null())
|
||||
.col(ColumnDef::new(ArticleTag::DeletedAt).timestamp_with_time_zone().null())
|
||||
.col(ColumnDef::new(ArticleTag::Version).integer().not_null().default(1))
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
manager
|
||||
.create_index(
|
||||
Index::create()
|
||||
.name("idx_article_tag_tenant")
|
||||
.table(ArticleTag::Table)
|
||||
.col(ArticleTag::TenantId)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// 4. 创建 article_article_tag 关联表(复合主键)
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(ArticleArticleTag::Table)
|
||||
.col(ColumnDef::new(ArticleArticleTag::ArticleId).uuid().not_null())
|
||||
.col(ColumnDef::new(ArticleArticleTag::TagId).uuid().not_null())
|
||||
.primary_key(
|
||||
Index::create()
|
||||
.col(ArticleArticleTag::ArticleId)
|
||||
.col(ArticleArticleTag::TagId),
|
||||
)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// 5. 创建 article_revision 版本历史表
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(ArticleRevision::Table)
|
||||
.col(ColumnDef::new(ArticleRevision::Id).uuid().not_null().primary_key())
|
||||
.col(ColumnDef::new(ArticleRevision::TenantId).uuid().not_null())
|
||||
.col(ColumnDef::new(ArticleRevision::ArticleId).uuid().not_null())
|
||||
.col(ColumnDef::new(ArticleRevision::RevisionNumber).integer().not_null())
|
||||
.col(ColumnDef::new(ArticleRevision::Title).string_len(255).not_null())
|
||||
.col(ColumnDef::new(ArticleRevision::Content).text().not_null())
|
||||
.col(ColumnDef::new(ArticleRevision::Summary).text().null())
|
||||
.col(ColumnDef::new(ArticleRevision::CreatedBy).uuid().null())
|
||||
.col(ColumnDef::new(ArticleRevision::CreatedAt).timestamp_with_time_zone().not_null().default(Expr::current_timestamp()))
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
manager
|
||||
.create_index(
|
||||
Index::create()
|
||||
.name("idx_article_revision_article")
|
||||
.table(ArticleRevision::Table)
|
||||
.col(ArticleRevision::ArticleId)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager.drop_table(Table::drop().table(ArticleRevision::Table).to_owned()).await?;
|
||||
manager.drop_table(Table::drop().table(ArticleArticleTag::Table).to_owned()).await?;
|
||||
manager.drop_table(Table::drop().table(ArticleTag::Table).to_owned()).await?;
|
||||
manager.drop_table(Table::drop().table(ArticleCategory::Table).to_owned()).await?;
|
||||
|
||||
manager
|
||||
.alter_table(
|
||||
Table::alter()
|
||||
.table(Article::Table)
|
||||
.drop_column(Article::Status)
|
||||
.drop_column(Article::Slug)
|
||||
.drop_column(Article::ContentType)
|
||||
.drop_column(Article::ReviewedBy)
|
||||
.drop_column(Article::ReviewedAt)
|
||||
.drop_column(Article::ReviewNote)
|
||||
.drop_column(Article::ViewCount)
|
||||
.drop_column(Article::SortOrder)
|
||||
.drop_column(Article::CategoryId)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum Article {
|
||||
Table,
|
||||
Status,
|
||||
Slug,
|
||||
ContentType,
|
||||
ReviewedBy,
|
||||
ReviewedAt,
|
||||
ReviewNote,
|
||||
ViewCount,
|
||||
SortOrder,
|
||||
CategoryId,
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum ArticleCategory {
|
||||
Table,
|
||||
Id,
|
||||
TenantId,
|
||||
Name,
|
||||
Slug,
|
||||
ParentId,
|
||||
Description,
|
||||
SortOrder,
|
||||
CreatedAt,
|
||||
UpdatedAt,
|
||||
CreatedBy,
|
||||
UpdatedBy,
|
||||
DeletedAt,
|
||||
Version,
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum ArticleTag {
|
||||
Table,
|
||||
Id,
|
||||
TenantId,
|
||||
Name,
|
||||
CreatedAt,
|
||||
UpdatedAt,
|
||||
CreatedBy,
|
||||
UpdatedBy,
|
||||
DeletedAt,
|
||||
Version,
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum ArticleArticleTag {
|
||||
Table,
|
||||
ArticleId,
|
||||
TagId,
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum ArticleRevision {
|
||||
Table,
|
||||
Id,
|
||||
TenantId,
|
||||
ArticleId,
|
||||
RevisionNumber,
|
||||
Title,
|
||||
Content,
|
||||
Summary,
|
||||
CreatedBy,
|
||||
CreatedAt,
|
||||
}
|
||||
@@ -212,14 +212,10 @@ async fn main() -> anyhow::Result<()> {
|
||||
std::process::exit(1);
|
||||
}
|
||||
if config.health.aes_key == "__MUST_SET_VIA_ENV__" || config.health.hmac_key == "__MUST_SET_VIA_ENV__" {
|
||||
tracing::error!(
|
||||
"健康数据加密密钥为默认占位值,拒绝启动。请设置环境变量 ERP__HEALTH__AES_KEY 和 ERP__HEALTH__HMAC_KEY(64 字符 hex 编码)"
|
||||
// 注: health 密钥已被统一 KEK (ERP__CRYPTO__KEK) 替代,此处仅保留兼容性检查
|
||||
tracing::warn!(
|
||||
"ERP__HEALTH__AES_KEY/HMAC_KEY 未设置(已迁移到 ERP__CRYPTO__KEK 统一密钥体系)"
|
||||
);
|
||||
std::process::exit(1);
|
||||
}
|
||||
if let Err(e) = erp_health::HealthCrypto::from_keys(&config.health.aes_key, &config.health.hmac_key) {
|
||||
tracing::error!("健康数据加密密钥无效: {}。密钥必须为 64 字符 hex 编码(32 字节)", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
// Initialize tracing
|
||||
@@ -449,6 +445,21 @@ async fn main() -> anyhow::Result<()> {
|
||||
};
|
||||
|
||||
// Build shared state
|
||||
let pii_crypto = if config.crypto.kek == "__MUST_SET_VIA_ENV__" {
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
tracing::warn!("⚠️ PII KEK 使用开发默认值,仅用于本地开发");
|
||||
erp_core::crypto::PiiCrypto::dev_default()
|
||||
}
|
||||
#[cfg(not(debug_assertions))]
|
||||
{
|
||||
panic!("ERP__CRYPTO__KEK must be set in production. Use a 64-char hex string (32 bytes).");
|
||||
}
|
||||
} else {
|
||||
erp_core::crypto::PiiCrypto::from_kek_hex(&config.crypto.kek)
|
||||
.expect("PII KEK must be valid 64-char hex (32 bytes). Set ERP__CRYPTO__KEK")
|
||||
};
|
||||
|
||||
let state = AppState {
|
||||
db,
|
||||
config,
|
||||
@@ -462,6 +473,7 @@ async fn main() -> anyhow::Result<()> {
|
||||
.time_to_idle(std::time::Duration::from_secs(300))
|
||||
.build(),
|
||||
ai_state,
|
||||
pii_crypto,
|
||||
};
|
||||
|
||||
// --- Build the router ---
|
||||
|
||||
@@ -22,6 +22,8 @@ pub struct AppState {
|
||||
pub plugin_entity_cache: moka::sync::Cache<String, erp_plugin::state::EntityInfo>,
|
||||
/// AI 模块状态(启动时构建,避免每次请求重建)
|
||||
pub ai_state: erp_ai::AiState,
|
||||
/// PII 加密服务(KEK + DEK 管理)
|
||||
pub pii_crypto: erp_core::crypto::PiiCrypto,
|
||||
}
|
||||
|
||||
/// Allow handlers to extract `DatabaseConnection` directly from `State<AppState>`.
|
||||
@@ -104,16 +106,10 @@ impl FromRef<AppState> for erp_plugin::state::PluginState {
|
||||
/// Allow erp-health handlers to extract their required state.
|
||||
impl FromRef<AppState> for erp_health::HealthState {
|
||||
fn from_ref(state: &AppState) -> Self {
|
||||
let crypto = erp_health::HealthCrypto::from_keys(
|
||||
&state.config.health.aes_key,
|
||||
&state.config.health.hmac_key,
|
||||
)
|
||||
.expect("Health encryption keys must be valid 32-byte hex strings. Set ERP__HEALTH__AES_KEY and ERP__HEALTH__HMAC_KEY");
|
||||
|
||||
Self {
|
||||
db: state.db.clone(),
|
||||
event_bus: state.event_bus.clone(),
|
||||
crypto,
|
||||
crypto: state.pii_crypto.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ use erp_health::service::{
|
||||
appointment_service, doctor_service, patient_service,
|
||||
};
|
||||
use erp_health::state::HealthState;
|
||||
use erp_health::HealthCrypto;
|
||||
use erp_core::crypto::PiiCrypto;
|
||||
|
||||
use super::test_db::TestDb;
|
||||
|
||||
@@ -21,7 +21,7 @@ fn make_state(db: &sea_orm::DatabaseConnection) -> HealthState {
|
||||
HealthState {
|
||||
db: db.clone(),
|
||||
event_bus: EventBus::new(100),
|
||||
crypto: HealthCrypto::dev_default(),
|
||||
crypto: PiiCrypto::dev_default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ use erp_core::events::EventBus;
|
||||
use erp_health::dto::patient_dto::CreatePatientReq;
|
||||
use erp_health::service::patient_service;
|
||||
use erp_health::state::HealthState;
|
||||
use erp_health::HealthCrypto;
|
||||
use erp_core::crypto::PiiCrypto;
|
||||
|
||||
use super::test_db::TestDb;
|
||||
|
||||
@@ -16,7 +16,7 @@ fn make_state(db: &sea_orm::DatabaseConnection) -> HealthState {
|
||||
HealthState {
|
||||
db: db.clone(),
|
||||
event_bus: EventBus::new(100),
|
||||
crypto: HealthCrypto::dev_default(),
|
||||
crypto: PiiCrypto::dev_default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user