""" backend/app/services/shipping_notice/audit_service.py 用途:集中追加货代领域审计事件并拒绝含敏感业务载荷的元数据。 依赖:ShippingAuditEvent、SQLAlchemy 会话。 逻辑:Run、Task、库存和 Chatflow 服务调用本模块写入状态与决策事实;本服务不提交事务,由调用方保证业务与审计原子性。 """ from __future__ import annotations import hashlib import json from typing import Any from app import db from app.core.errors import ValidationError from app.models import ShippingAuditEvent _FORBIDDEN_METADATA_KEYS = frozenset({ 'api_key', 'api_base_url', 'authorization', 'body', 'content', 'document_text', 'email_body', 'password', 'prompt', 'provider_config', 'quote', 'token', }) def _stable_hash(value: Any) -> str: """对受控状态投影生成 SHA-256,避免审计表重复保存原始业务值。""" encoded = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str) return hashlib.sha256(encoded.encode('ascii')).hexdigest() def _sanitize_metadata(metadata: dict[str, Any] | None) -> dict[str, Any]: """验证元数据仅含脱敏诊断事实,阻断正文、凭据和字段值进入统一审计。""" safe = dict(metadata or {}) forbidden = sorted(key for key in safe if str(key).lower() in _FORBIDDEN_METADATA_KEYS) if forbidden: raise ValidationError( 'Shipping audit metadata contains forbidden keys', code='SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN', ) return safe def append_shipping_audit_event( *, event_type: str, aggregate_type: str, aggregate_id: str, run_no: str | None = None, task_no: str | None = None, intake_no: str | None = None, actor_type: str = 'system', actor_id: str | int | None = None, request_id: str | None = None, correlation_id: str | None = None, reason_code: str | None = None, before: Any = None, after: Any = None, metadata: dict[str, Any] | None = None, ) -> ShippingAuditEvent: """ 追加一条货代审计事实。 Args: event_type: 稳定业务事件名,例如 ``run_status_changed``;禁止传入用户自由文本。 aggregate_type/aggregate_id: 业务聚合类型与稳定编号,不使用可删除记录的外键。 before/after: 可复现的受控状态投影;只持久化其哈希。 metadata: 仅允许原因码、计数、版本等脱敏诊断事实。 Returns: 尚未提交的审计事件,由调用方与业务写入在同一事务提交。 Raises: ValidationError: actor 类型或元数据包含正文、凭据等敏感字段。 """ allowed_actor_types = {'user', 'system', 'rpa', 'chatflow', 'admin'} if actor_type not in allowed_actor_types: raise ValidationError('Invalid shipping audit actor type', code='SHIPPING_NOTICE.AUDIT_ACTOR_INVALID') event = ShippingAuditEvent( event_type=str(event_type)[:64], aggregate_type=str(aggregate_type)[:64], aggregate_id=str(aggregate_id)[:128], run_no=str(run_no)[:64] if run_no else None, task_no=str(task_no)[:64] if task_no else None, intake_no=str(intake_no)[:64] if intake_no else None, actor_type=actor_type, actor_id=str(actor_id)[:128] if actor_id is not None else None, request_id=str(request_id)[:64] if request_id else None, correlation_id=str(correlation_id)[:64] if correlation_id else None, reason_code=str(reason_code)[:128] if reason_code else None, before_hash=_stable_hash(before) if before is not None else None, after_hash=_stable_hash(after) if after is not None else None, metadata_json=_sanitize_metadata(metadata), ) db.session.add(event) return event