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

@@ -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,
}

View File

@@ -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_KEY64 字符 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 ---

View File

@@ -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(),
}
}
}

View File

@@ -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(),
}
}

View File

@@ -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(),
}
}