Files
syops/backend/app/services/shipping_notice/audit_service.py
T
hugo 95cdfe66b0 feat(shipping-notice): 增强订单抽取与审计功能,支持取消与保留策略
- 在环境配置中新增进度细化、订单提取取消与审计导出相关的开关
- 实现订单抽取运行的取消功能,允许管理员在运行中进行操作
- 引入审计事件的保留策略,支持三年保留期的自动清理
- 更新相关模型与服务,确保新功能的完整性与可追溯性
- 增强文档与代码注释,反映新的业务逻辑与审计要求
2026-07-30 14:52:21 +08:00

285 lines
12 KiB
Python

"""
backend/app/services/shipping_notice/audit_service.py
用途:集中追加货代领域审计事件并拒绝含敏感业务载荷的元数据与快照。
依赖:ShippingAuditEvent、progress_audit_contract、SQLAlchemy 会话。
逻辑:Run、Task、会话 PDF 工作项、库存和 Chatflow 服务调用本模块写入状态与决策事实;
本服务不提交事务,由调用方保证业务与审计原子性。支持 operation_id、白名单前后快照、
证据引用、会话工作项关联、属主与三年保留到期;IP / User-Agent 仅持久化哈希。
"""
from __future__ import annotations
import hashlib
import json
from datetime import datetime, timedelta
from typing import Any
from app import db
from app.core.errors import ValidationError
from app.models import ShippingAuditEvent
from app.services.shipping_notice.progress_audit_contract import (
AUDIT_FORBIDDEN_KEYS,
AUDIT_SNAPSHOT_ALLOWED_KEYS,
is_forbidden_audit_key,
)
from app.services.shipping_notice.progress_feature_flags import audit_retention_days
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 hash_client_context_value(raw: str | None) -> str | None:
"""
将客户端上下文(IP / User-Agent)转为不可逆哈希。
核心逻辑:空白返回 None;否则 UTF-8 SHA-256 十六进制,永不落库原文。
Args:
raw: 原始 IP 或 User-Agent;禁止已是哈希的二次哈希由调用方自行保证。
Returns:
64 位十六进制哈希,或 None。
"""
text = str(raw or '').strip()
if not text:
return None
return hashlib.sha256(text.encode('utf-8')).hexdigest()
def _collect_forbidden_keys(payload: Any, *, path: str = '') -> list[str]:
"""
递归收集命中敏感黑名单的键路径。
核心逻辑:遍历 dict/list;键名大小写不敏感匹配;返回稳定排序路径便于测试断言。
"""
found: list[str] = []
if isinstance(payload, dict):
for key, child in payload.items():
key_text = str(key)
child_path = f'{path}.{key_text}' if path else key_text
if is_forbidden_audit_key(key_text):
found.append(child_path)
found.extend(_collect_forbidden_keys(child, path=child_path))
elif isinstance(payload, list):
for index, child in enumerate(payload):
found.extend(_collect_forbidden_keys(child, path=f'{path}[{index}]'))
return found
def _sanitize_metadata(metadata: dict[str, Any] | None) -> dict[str, Any]:
"""验证元数据仅含脱敏诊断事实,阻断正文、凭据和字段值进入统一审计。"""
safe = dict(metadata or {})
forbidden = _collect_forbidden_keys(safe)
if forbidden:
raise ValidationError(
'Shipping audit metadata contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN',
details={'forbidden_keys': sorted(set(forbidden))},
)
return safe
def project_audit_snapshot(value: Any | None) -> dict[str, Any] | None:
"""
将业务状态投影为审计白名单快照。
核心逻辑:仅保留 AUDIT_SNAPSHOT_ALLOWED_KEYS 顶层键;命中敏感键直接拒绝而非静默丢弃。
Args:
value: 受控状态 dict;非 dict 返回 None。
Returns:
白名单快照,或 None。
Raises:
ValidationError: 包含禁止键。
"""
if value is None:
return None
if not isinstance(value, dict):
raise ValidationError(
'Shipping audit snapshot must be an object',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
)
# 敏感键拒绝入库;未授权业务键静默剔除,避免“悄悄丢敏感字段”造成审计假完整。
sensitive = [key for key in value if is_forbidden_audit_key(str(key))]
if sensitive:
raise ValidationError(
'Shipping audit snapshot contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
details={'forbidden_keys': sorted(set(str(k) for k in sensitive))},
)
projected = {
str(key): value[key]
for key in value
if str(key) in AUDIT_SNAPSHOT_ALLOWED_KEYS
}
nested_forbidden = _collect_forbidden_keys(projected)
if nested_forbidden:
raise ValidationError(
'Shipping audit snapshot contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
details={'forbidden_keys': sorted(set(nested_forbidden))},
)
return projected or None
def _sanitize_refs(refs: list[dict[str, Any]] | None, *, field_name: str) -> list[dict[str, Any]] | None:
"""校验证据/产物引用仅含标识类字段,拒绝 URL 与正文。"""
if refs is None:
return None
if not isinstance(refs, list):
raise ValidationError(
f'Shipping audit {field_name} must be a list',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
)
forbidden = _collect_forbidden_keys(refs)
if forbidden:
raise ValidationError(
f'Shipping audit {field_name} contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
details={'forbidden_keys': sorted(set(forbidden))},
)
return refs
def default_retention_expires_at(*, now: datetime | None = None) -> datetime:
"""
计算审计默认保留到期时间(默认三年,可由 SHIPPING_NOTICE_AUDIT_RETENTION_DAYS 覆盖)。
Args:
now: 可选当前时间,便于测试注入。
Returns:
UTC naive 到期时间。
"""
base = now or datetime.utcnow()
return base + timedelta(days=audit_retention_days())
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,
actor_role: str | None = None,
request_id: str | None = None,
operation_id: str | None = None,
correlation_id: str | None = None,
source: str | None = None,
result: str | None = None,
error_code: str | None = None,
conversation_id: str | None = None,
unit_id: str | int | None = None,
document_id: str | int | None = None,
review_case_no: str | None = None,
session_item_id: str | None = None,
owner_user_id: str | int | None = None,
client_ip: str | None = None,
user_agent: str | None = None,
client_ip_hash: str | None = None,
user_agent_hash: str | None = None,
attempt_no: int | None = None,
action: str | None = None,
reason_code: str | None = None,
reason: str | None = None,
before: Any = None,
after: Any = None,
evidence_refs: list[dict[str, Any]] | None = None,
artifact_refs: list[dict[str, Any]] | None = None,
context_refs: dict[str, Any] | None = None,
metadata: dict[str, Any] | None = None,
retention_expires_at: datetime | None = None,
persist_snapshots: bool = True,
) -> ShippingAuditEvent:
"""
追加一条货代审计事实。
Args:
event_type: 稳定业务事件名,例如 ``session_work_item_created``;禁止传入用户自由文本。
aggregate_type/aggregate_id: 业务聚合类型与稳定编号,不使用可删除记录的外键。
operation_id: 同一次用户/系统操作的关联键,与 request_id 共同贯通事件链。
session_item_id: 会话 PDF 工作项 item_no;软引用。
owner_user_id: 业务属主,与 actor_id(实际操作者)区分,支撑代操作审计。
client_ip/user_agent: 原始客户端上下文,仅哈希后入库;也可直接传 *_hash。
before/after: 可复现的受控状态投影;持久化白名单快照及其哈希。
evidence_refs/artifact_refs: FileAsset ID、SHA-256、版本与证据坐标,禁止 URL/正文。
metadata: 仅允许原因码、计数、版本等脱敏诊断事实。
persist_snapshots: False 时只写哈希(兼容历史调用方仅传 before/after 哈希语义)。
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')
if result is not None and result not in {'success', 'failure', 'rejected', 'ignored'}:
raise ValidationError('Invalid shipping audit result', code='SHIPPING_NOTICE.AUDIT_RESULT_INVALID')
before_snapshot = project_audit_snapshot(before) if before is not None else None
after_snapshot = project_audit_snapshot(after) if after is not None else None
if context_refs is not None:
_sanitize_metadata(context_refs)
resolved_ip_hash = client_ip_hash or hash_client_context_value(client_ip)
resolved_ua_hash = user_agent_hash or hash_client_context_value(user_agent)
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,
actor_role=str(actor_role)[:64] if actor_role else None,
request_id=str(request_id)[:64] if request_id else None,
operation_id=str(operation_id)[:64] if operation_id else None,
correlation_id=str(correlation_id)[:64] if correlation_id else None,
source=str(source)[:32] if source else None,
result=result,
error_code=str(error_code)[:64] if error_code else None,
conversation_id=str(conversation_id)[:100] if conversation_id else None,
unit_id=str(unit_id)[:64] if unit_id is not None else None,
document_id=str(document_id)[:64] if document_id is not None else None,
review_case_no=str(review_case_no)[:64] if review_case_no else None,
session_item_id=str(session_item_id)[:64] if session_item_id else None,
owner_user_id=str(owner_user_id)[:64] if owner_user_id is not None else None,
client_ip_hash=str(resolved_ip_hash)[:64] if resolved_ip_hash else None,
user_agent_hash=str(resolved_ua_hash)[:64] if resolved_ua_hash else None,
attempt_no=int(attempt_no) if attempt_no is not None else None,
action=str(action)[:64] if action else None,
reason_code=str(reason_code)[:128] if reason_code else None,
reason=str(reason)[:2000] if reason else None,
before_hash=_stable_hash(before_snapshot if before_snapshot is not None else before)
if before is not None else None,
after_hash=_stable_hash(after_snapshot if after_snapshot is not None else after)
if after is not None else None,
before_snapshot_json=before_snapshot if persist_snapshots else None,
after_snapshot_json=after_snapshot if persist_snapshots else None,
evidence_refs_json=_sanitize_refs(evidence_refs, field_name='evidence_refs'),
artifact_refs_json=_sanitize_refs(artifact_refs, field_name='artifact_refs'),
context_refs_json=dict(context_refs) if context_refs else None,
metadata_json=_sanitize_metadata(metadata),
retention_expires_at=retention_expires_at or default_retention_expires_at(),
)
db.session.add(event)
return event
# 供测试与 OpenAPI 契约引用的冻结黑名单导出。
FORBIDDEN_AUDIT_METADATA_KEYS = AUDIT_FORBIDDEN_KEYS